NextJS Lambda webpack plugin
This plugin modifies a serverless NextJS build to add in a compatibility layer for AWS Lambda together with a handler that handles routing.
The standard handler reacts to Application Load Balancer events but it also has an alternative handler for API Gateway V2.
Warning: this is still early software and only supports SSR pages, static generation is still a work in progress
Usage
Add this plugin to your NextJS project as a dev dependency with either of the following commands:
# npm
npm install nextjs-lambda-webpack-plugin --save-dev
# yarn
yarn add -D nextjs-lambda-webpack-plugin
Next up add the plugin to your next.config.js
:
const NextJSLambdaWebpackPlugin = require('nextjs-lambda-webpack-plugin')
const isServerless = (target) => target === ('serverless' || 'experimental-serverless-trace')
module.exports = {
webpack: (config, options) => {
if (config.mode === 'production' && isServerless(options.config.target)) {
config.plugins.push(new NextJSLambdaWebpackPlugin(options))
}
}
}
After the build two folders will be available in the default dist_lambda/
build folder.
-
lambda/
contains the code and should be uploaded to a lambda function -
assets/
contains the assets that should be uploaded to a S3 bucket
Note: To properly access static files, it's best to set an asset prefix to your s3 bucket
Setting the correct handler
The build exports two lambda handlers
-
index.handler
is the default and should be invocated by an Application Load Balancer -
index.ApiGatewayHandler
is an alternative that can be invocated by Api Gateway V2
Thanks
A lot of the code has been made available by the serverless-next.js project, major thanks for all their work.