Vingtoft
Vingtoft

Reputation: 14656

Nestjs on AWS Lambda (Serverless Framework) | How to access the event parameter?

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.'
    };
}; 

Upvotes: 5

Views: 3541

Answers (2)

cooow
cooow

Reputation: 869

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

Upvotes: 0

Vingtoft
Vingtoft

Reputation: 14656

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

Upvotes: 5

Related Questions