Skip to content

Ferdinand Agyei-Yeboah

Deploy NextJS App Using Serverless NextJS

August 15, 2022

The basic way to deploy a NextJS app is simply to run it on a node server. However, wouldn’t it be great if you could deploy it serverlessly using a cloudfront distribution? This is where serverless-nextjs comes in. serverless next-js allows you to deploy a NextJS app using Cloudfront, S3 and Lambda. Using serverless options reduces management overhead as well as operational cost (pay for what you need).

To deploy a NextJS app to AWS (only AWS is currently supported) using serverless-nextjs, follow the basic steps.

1. Install Node, Serverless and AWS CLI.

Install NodeJS

NodeJS

Install Serverless

The serverless version must have serverless-components in beta (read more here). I used v2.65.0 but I assume it works up till v3.18.2. After installing node, run npm to install serverless.

npm install -g serverless@2.65.0

Install AWS CLI

  • Install the AWS CLI.
  • Create an IAM user that has cloudwatch, s3 and lambda permissions (or use an admin policy). The entire list of permissions needed is here.
  • Configure the AWS CLI to use new credentials.

2. Create a serverless.yml

Create a serverless.yml file in the root of your NextJS project. This file is responsible for configuring deployment details. An example is below, this would deploy to example.domain.com and has specified names for the s3 bucket and lambdas that will be created (cannot name the cloudfront distribution, a randomly generated id is always used).

The domain name must be hosted by AWS Route53 - more details here. If you are using a custom domain name, you will have to verify the SSL certificate generated by ACM (more on that later).

MyApplicationName:
component: "@sls-next/serverless-component@3.6.0"
inputs:
domain: ["example", "domain.com"] # [ sub-domain, domain ]
cloudfront:
comment: My application details
name:
defaultLambda: myapplication-default-lambda
apiLambda: myapplication-api-lambda
imageLambda: myapplication-image-lambda
bucketName: myapplication-utility
description: Resources for myapplication

3. Deploy Into AWS

To deploy, make sure you are in the root of the NextJS project and run serverless.

Optional: Validate ACM Certificate

If you are using a custom domain name, you will have to verify the SSL certificate generated by ACM.

To do so - login to the AWS console, go to ACM, and find the newly requested certificate. It should be in pending validation status, then click Create Records in Route 53. The official AWS guide on ACM certificate validation is here.

Optional: Teardown Resources

To teardown, make sure you are in the root of the NextJS project and run serverless remove.


More Reading:


Software Engineering Tutorials & Best Practices