What is aws-serverless-express?
The aws-serverless-express package allows you to easily run Node.js web applications, such as those built with Express, on AWS Lambda and Amazon API Gateway. It simplifies the process of creating serverless applications by handling the integration between Lambda and API Gateway, allowing you to focus on your application logic.
What are aws-serverless-express's main functionalities?
Create a Serverless Express Application
This feature allows you to create a serverless Express application that can be deployed on AWS Lambda. The code sample demonstrates how to set up a simple Express app with a single route and export a Lambda handler that uses aws-serverless-express to handle incoming requests.
const awsServerlessExpress = require('aws-serverless-express');
const app = require('express')();
const server = awsServerlessExpress.createServer(app);
app.get('/hello', (req, res) => {
res.send('Hello, world!');
});
exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context);
Custom Lambda Proxy Integration
This feature allows you to customize the Lambda proxy integration, such as specifying custom binary MIME types. The code sample shows how to create a server with custom binary MIME types and handle requests with a custom route.
const awsServerlessExpress = require('aws-serverless-express');
const app = require('express')();
const server = awsServerlessExpress.createServer(app, null, ['*/*']);
app.get('/custom', (req, res) => {
res.json({ message: 'Custom integration' });
});
exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context);
Middleware Support
This feature demonstrates how to use middleware in your serverless Express application. The code sample shows how to log incoming requests using middleware and handle a route that responds with a message.
const awsServerlessExpress = require('aws-serverless-express');
const app = require('express')();
const server = awsServerlessExpress.createServer(app);
app.use((req, res, next) => {
console.log('Request received');
next();
});
app.get('/middleware', (req, res) => {
res.send('Middleware example');
});
exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context);
Other packages similar to aws-serverless-express
serverless-http
The serverless-http package is a similar tool that allows you to run web applications on AWS Lambda. It supports various frameworks like Express, Koa, and Hapi. Compared to aws-serverless-express, serverless-http offers broader framework support and a simpler API for converting your web application into a Lambda-compatible handler.
lambda-api
The lambda-api package is a lightweight web framework designed specifically for AWS Lambda. It provides a similar experience to Express but is optimized for serverless environments. Compared to aws-serverless-express, lambda-api is more lightweight and tailored for Lambda, offering better performance and lower cold start times.
express
While not a direct competitor, the express package is the core framework that aws-serverless-express is designed to work with. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. aws-serverless-express leverages Express to create serverless applications, whereas Express itself is not inherently serverless.
This library enables you to utilize AWS Lambda and Amazon API Gateway to respond to web and API requests using your existing Node.js application framework. The sample provided allows you to easily build serverless web applications/services and RESTful APIs using the Express framework.
Getting Started
npm install aws-serverless-express
'use strict'
const awsServerlessExpress = require('aws-serverless-express')
const app = require('./express-server')
const server = awsServerlessExpress.createServer(app)
exports.handler = (event, context) => 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.
Example
In addition to a basic Lambda function and API Gateway API, the example
directory includes a swagger file, CloudFormation template, and helper scripts to get you up and running quickly.
Steps for running the example
cd example
- Replace "YOUR_ACCOUNT_ID" in
simple-proxy-api.yaml
: use your preferred text editor, or from Linux|OSX run sed -i '' 's/YOUR_ACCOUNT_ID/xxxxxxxxxxxx/g' simple-proxy-api.yaml
- Replace all instances of "YOUR_UNIQUE_BUCKET_NAME" in the
package.json
scripts
with a unique bucket name: use your preferred text editor, or from Linux|OSX run sed -i '' 's/YOUR_UNIQUE_BUCKET_NAME/xxxxxxxxxxxx/g' package.json
. If the bucket does not yet exist, the next step will create it for you. - Run
npm run setup
- this installs the node dependencies; creates the S3 bucket (if it does not already exist); packages and uploads your serverless Express application assets to S3; uploads the API Swagger file to S3; and finally spins up a CloudFormation stack, creating your API Gateway API and Lambda Function. - After the setup command completes, your browser will be opened to the CloudFormation console (sign in if necessary). Select the
AwsServerlessExpressStack
, and click the ApiUrl
value under Outputs. This should open a new page with your running API. The API index lists the routes available in the example Express server (express-server.js
). - See the sections below for details on how to migrate an existing (or create a new) Node.js project based on this example. If you would prefer to delete AWS assets that were just created, simply run
npm run delete-stack
to delete the CloudFormation Stack, including the API and Lambda Function. For safety, this does not delete the S3 bucket, but after verifying the contents of the S3 bucket pointed at by the delete-bucket
command, you can run npm run delete-bucket
.
Creating a new Node.js project based on the example
To use this example as a base for a new Node.js project, simply copy the files in the example
directory into a new project directory. After making updates to express-server.js
, simply run npm run package-upload-update-function
. This will compress lambda.js
, express-server.js
, and your node_modules
directory into lambda-function.zip
, upload that zip to S3, and update your Lambda function.
Migrating an existing Node.js project
To migrate an existing Node server, you can utilize a lot of the files in the example
directory. For example, the package.json
has a lot of helpful scripts to manage your AWS serverless assets and perform basic local simulation of API Gateway and Lambda.
- Copy the files in the
example
directory to your existing project (you won't need express-server.js
; you also likely already have a package.json
, so just copy the scripts
section). api-gateway-event.json
helps with testing locally; cloudformation.json
and simple-proxy-api.yaml
help with managing your AWS assets. - Modify
lambda.js
to import your server configuration, eg. require('./express-server')
=> require('./my-app-dir/app')
. You will need to ensure you export your app configuration from the necessary file (eg. module.exports = app
), and remove your call to app.listen()
(if you have a server.listen
callback, you can provide it as the second parameter in the setup
method, eg. awsServerlessExpress.createServer(app, serverListenCallback
). This library takes your app configuration and listens on a Unix Domain Socket for you. - To performa a basic local simulation of API Gateway and Lambda with your Node server, update
api-gateway-event.json
with some values that are valid for your server (httpMethod
, path
, etc.) and run npm run local
(AWS Lambda uses NodeJS 4.3 LTS, and it is recommended to use the same version for testing purposes). - Once you have verified everything runs locally, modify the
package-function
script in package.json
to include all files necessary to run your application. If everything you need is in a single child directory, this is as simple as changing express-server.js
to my-app-dir
. If you are using a build tool, you will have some additional changes to make. - Run
npm run package-upload-update-function
to package (zip), upload (to S3), and update your Lambda function.