Run serverless applications and REST APIs using your existing Node.js application framework, on top of AWS Lambda and Amazon API Gateway. The sample provided allows you to easily build serverless web applications/services and RESTful APIs using the Express framework.
npm install aws-serverless-express
// lambda.js
'use strict'
const awsServerlessExpress = require('aws-serverless-express')
const app = require('./app')
const server = awsServerlessExpress.createServer(app)
exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context)
// NestJS
// lambda.ts
import * as awsServerlessExpress from 'aws-serverless-express';
import * as awsServerlessExpressMiddleware from 'aws-serverless-express/middleware';
import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './app.module';
export const handler = async (event, context) => {
const app = await NestFactory.create(ApplicationModule);
await app.init();
app.use(awsServerlessExpressMiddleware.eventContext());
const server = app.getHttpServer();
awsServerlessExpress.applyServer(server);
awsServerlessExpress.proxy(server, event, context);
};
Package and create your Lambda function, then configure a simple proxy API using Amazon API Gateway and integrate it with your Lambda function.
Want to get up and running quickly? Check out our example which includes:
- Lambda function
- Express server Swagger file
- Serverless Application Model (SAM)/CloudFormation template
- Helper scripts to configure, deploy, and manage your application
This package includes middleware to easily get the event object Lambda receives from API Gateway
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')
app.use(awsServerlessExpressMiddleware.eventContext())
app.get('/', (req, res) => {
res.json(req.apiGateway.event)
})
- Pay for what you use
- No infrastructure to manage
- Auto-scaling with no configuration needed
- Usage Plans
- Caching
- Authorization
- Staging
- SDK Generation
- API Monitoring
- Request Validation
- Documentation
- For apps that may not see traffic for several minutes at a time, you could see cold starts
- Cannot use native libraries (aka Addons) unless you package your app on an EC2 machine running Amazon Linux
- Stateless only
- API Gateway has a timeout of 30 seconds, and Lambda has a maximum execution time of 5 minutes.