Search code examples
node.jsamazon-web-servicesapiaws-lambdaundefined

Why is event.requestContext undefined for my AWS Lambda function?


Why was I unable to obtain the remote IP address of the user?

When I clicked on the test button or the function URL, it seems that event.requestContext was undefined. Why?

const res = { 
    statusCode: 200,
    isBase64Encoded: false,
    headers: { 
        "Access-Control-Allow-Origin":"*",
        "Content-Type": "text/plain" 
    },
    multiValueHeader: {}
};

export const handler = async(event) => {
    const ip = event.requestContext.identity.sourceIp;
    res.body="hi "+ip; 
    return res;
}

Solution

  • It seems that the event format is incorrect. This works:

    const ip = event.requestContext.http.sourceIp;
    

    What I used was the format for Lambda version 1 but I am now using version 2.