By using AWS re:Post, you agree to the Terms of Use
/Error when trying to use lambda to return client IP/

Error when trying to use lambda to return client IP

0

Hello. Attempting to create something similar to http://checkip.amazonaws.com/ . Am open to other solutions, but the one I found is https://stackoverflow.com/questions/33062097/how-can-i-retrieve-a-users-public-ip-address-via-amazon-api-gateway-lambda-n .

When I use this for the lambda function -

'use strict'; console.log('Loading function'); exports.handler = (event, context, callback) => { console.log('SourceIP =', event.identity.sourceIP); callback(null, event.identity.sourceIP); };

and this for the mapping template -

{ "sourceIP" : "$context.identity.sourceIp" }

I get this error -

{ "errorType": "TypeError", "errorMessage": "Cannot read property 'sourceIP' of undefined", "trace": [ "TypeError: Cannot read property 'sourceIP' of undefined", " at Runtime.exports.handler (/var/task/index.js:4:46)", " at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)" ] }

Can someone please walk me through the steps to correctly implement the lambda function and mapping template above or perhaps if you have a better method to return the client IP of a simple get request, please share?

Thank you

  • Can you log the "event" parameter? I think you should use "event.sourceIP"

1 Answers
1
Accepted Answer

It depends on which API you are using. If you are using HTTP API, the source IP is at event.requestContext.http.sourceIP or event.headers.x-forwarded-for. If you are using REST API it will be in event.headers.X-Forwarded-For or event.requestContext.identity.sourceIp. You are trying to access event.identity.sourceIP.

Note, in both cases you do not need a mapping template, just return a body from the Lambda function. If you are using REST API, you may be able to implement it using a Mock integration and a mapping template, although I did not test it.

EXPERT
answered a month ago
EXPERT
reviewed 24 days ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions