5

I'm hosting a Nestjs application on AWS Lambda (using the Serverless Framework). Please note that the implementation is behind AWS API Gateway.

Question: How can I access to event parameter in my Nest controller?

This is how I bootstrap the NestJS server:

import { APIGatewayProxyHandler } from 'aws-lambda';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Server } from 'http';
import { ExpressAdapter } from '@nestjs/platform-express';
import * as awsServerlessExpress from 'aws-serverless-express';
import * as express from 'express';

let cachedServer: Server;

const bootstrapServer = async (): Promise<Server> => {
    const expressApp = express();
    const adapter = new ExpressAdapter(expressApp);
    const app = await NestFactory.create(AppModule, adapter);
    app.enableCors();
    await app.init();
    return awsServerlessExpress.createServer(expressApp);
}

export const handler: APIGatewayProxyHandler = async (event, context) => {
    if (!cachedServer) {
        cachedServer = await bootstrapServer()
    }
    return awsServerlessExpress.proxy(cachedServer, event, context, 'PROMISE')
        .promise;
};

Here is a function in one controller:

@Get()
getUsers(event) { // <-- HOW TO ACCESS event HERE?? This event is undefined.
    return {
        statusCode: 200,
        body: "This function works and returns this JSON as expected."
    }

I'm struggling to understand how I can access the event paramenter, which is easily accessible in a "normal" node 12.x Lambda function:

module.exports.hello = async (event) => {
    return {
        statusCode: 200,
        body: 'In a normal Lambda, the event is easily accessible, but in NestJS its (apparently) not.'
    };
}; 

2 Answers 2

5

Solution:

Add AwsExpressServerlessMiddleware to your setup during bootstrap:

const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')
app.use(awsServerlessExpressMiddleware.eventContext())

Note: The app.use should be before app.init()

Now the event and context object can be accessed:

var event = req.apiGateway.event;
var context = req.apiGateway.context;

Credits: This answer on SO

Sign up to request clarification or add additional context in comments.

Comments

0

With the latest version of the @codegenie/serverless-express package, you can easily access the API Gateway event context in your controllers without any additional middleware.

Nothing to do in handler function.

Simply add to your controller :

const { getCurrentInvoke } = require('@codegenie/serverless-express')
...
const currentInvoke = getCurrentInvoke()
const context = currentInvoke.event.requestContext

Source

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.