Deploy a Next.js app

In this guide you'll learn how to deploy a Next.js app using Amplify Hosting. Amplify supports the hosting of static apps and apps with dynamic server-side rendered routes (SSR).

Prerequisites

If you haven't already, install and configure the latest version of the Amplify CLI:

1npm install -g @aws-amplify/cli
1curl -sL https://aws-amplify.github.io/amplify-cli/install | bash && $SHELL
1curl -sL https://aws-amplify.github.io/amplify-cli/install-win -o install.cmd && install.cmd
1amplify configure

To see a video walkthrough of how to configure the CLI, click here.

Deploy and host an SSG only app

You can deploy static (SSG) apps with manual deployments or with Git-based continuous deployments. This example demonstrates how to manually deploy an SSG app.

Getting started

Create a new Next.js app:

1$ npm init next-app
2
3✔ What is your project named? my-app
4✔ Pick a template › Default starter app

Image Optimization using Next.js' default loader is not compatible with next export. To manually deploy the next-app example, you must disable image optimization.

In the root of the project, open next.config.js and add the following code to the configuration:

1images: {
2 unoptimized: true,
3 }

The edited next.config.js will look similar as the example below

1const nextConfig = {
2 reactStrictMode: true,
3 swcMinify: true,
4 images: {
5 unoptimized: true,
6 },
7};
8
9module.exports = nextConfig;

Next, change to the my-app directory to update the package.json file. When you deploy a Next.js app, Amplify inspects the app's build script in the package.json file to detect whether the app is static (SSG) or server-side rendered (SSR).

To deploy a static app, add the export script to the existing build script:

1"scripts": {
2 "dev": "next dev",
3 "build": "next build && next export",
4 "start": "next start"
5},

The build script next build && next export indicates that the app supports SSG pages only.next export allows you to export your app to static HTML, which can be run standalone without the need of a Node.js server.

Adding Amplify hosting

Initialize a new Amplify project. The Distribution Directory Path depends on whether you are deploying a static or SSR app. For a static app, set the Distribution Directory Path to out.

1$ amplify init
2
3? Enter a name for the project: mynextapp
4? Enter a name for the environment: dev
5? Choose your default editor: Visual Studio Code (or your preferred editor)
6? Choose the type of app that youre building: javascript
7? What javascript framework are you using: react
8? Source Directory Path: src
9? Distribution Directory Path: out
10? Build Command: npm run-script build
11? Start Command: npm run-script start
12? Do you want to use an AWS profile? Y
13? Please choose the profile you want to use: <your profile>

Add hosting with the Amplify add command:

1amplify add hosting
1? Select the plugin module to execute Hosting with Amplify Console (Managed hosting with custom do
2mains, Continuous deployment)
3? Choose a type Manual deployment
4
5You can now publish your app using the following command:
6
7Command: amplify publish

Deploy the app with the Amplify publish command:

1amplify publish
2
3✔ Successfully pulled backend environment dev from the cloud.
4
5 Current Environment: dev
6
7┌──────────┬────────────────┬───────────┬───────────────────┐
8│ Category │ Resource name │ Operation │ Provider plugin │
9├──────────┼────────────────┼───────────┼───────────────────┤
10│ Hosting │ amplifyhosting │ Create │ awscloudformation │
11└──────────┴────────────────┴───────────┴───────────────────┘
12
13? Are you sure you want to continue? Yes

Congratulations, your app has now been successfully deployed! The URL for the app should be displayed in your terminal.

CLI Output

To see your app in the Amplify console at any time, run the following command:

1$ amplify console

Deploying updates

Once you make changes to your app and are ready to deploy them, you can run the publish command again:

1$ amplify publish

Deleting the app

To delete the app and the deployment, run the delete command:

1$ amplify delete

Dynamic routes

Next.js also supports dynamic routes.

Let's say you have a folder and file structure that looks like this:

1/pages/posts/[id].js

This component needs to read the ID from the URL and do something useful with it in the app. To make this happen, you can use next/router:

1// /pages/posts/[id].js
2import { useRouter } from 'next/router'
3
4const Post = () => {
5 const router = useRouter()
6 const { id } = router.query
7
8 return <p>Post: {id}</p>
9}
10
11export default Post

To enable this, you need to set up a rewrite for /pages/posts/[id].html in the Rewrites and redirects section of the Amplify Console:

Rewrites

Setting up rewrites for SPAs

Most SPA frameworks support HTML5 history.pushState() to change browser location without triggering a server request. This works for users who begin their journey from the root (or /index.html), but fails for users who navigate directly to any other page. Using regular expressions, the following example sets up a 200 rewrite for all files to index.html, except for the specific file extensions specified in the regular expression.

To set up rewrites, follow the guide on AWS Amplify Hosting's documentation.

Make sure you list the file extensions used in your application (i.e. .json, .webp, etc.) in the regular expression.

Deploy and host a hybrid app (SSG and SSR)

To deploy a hybrid (SSG and SSR) app, use Amplify's Git-based CI/CD and hosting service.

For reference, the current support for Next.js SSR in Amplify Hosting is outlined here.

Getting started

Create a new Next.js app:

1$ npm init next-app
2
3✔ What is your project named? my-app
4✔ Pick a template › Default starter app

When you deploy a Next.js app, Amplify inspects the app's build script in the package.json file to detect whether the app is static (SSG) or server-side rendered (SSR). Change into the my-app directory to view the package.json file. The build script next build indicates that the app supports both SSG and SSR pages.

To deploy an SSR app, keep the following default build script:

1"scripts": {
2 "dev": "next dev",
3 "build": "next build",
4 "start": "next start"
5},

Creating the Git repository

Create a new Git repository for your project. For a Github repo, you can run the following commands in the root of your project to initialize the repo and push the code to Github:

1$ git init
2$ git remote add origin git@github.com:username/my-next-app.git
3$ git add .
4$ git commit -m "initial commit"
5$ git push origin main

Adding Amplify hosting

Next, initialize a new Amplify project. The Distribution Directory Path that you set depends on whether you are deploying a static or SSR app.

For an SSR app, set the Distribution Directory Path to .next.

1$ amplify init
2
3? Enter a name for the project: mynextapp
4? Enter a name for the environment: dev
5? Choose your default editor: Visual Studio Code (or your preferred editor)
6? Choose the type of app that youre building: javascript
7? What javascript framework are you using: react
8? Source Directory Path: src
9? Distribution Directory Path: .next
10? Build Command: npm run-script build
11? Start Command: npm run-script start
12? Do you want to use an AWS profile? Y
13? Please choose the profile you want to use: <your profile>

Add hosting with the Amplify add command:

1$ amplify add hosting
2
3? Select the plugin module to execute: # Hosting with Amplify Console (Managed hosting with custom domains, Continuous deployment)
4? Choose a type: # Continuous deployment (Git-based deployments)

The Amplify Console opens and displays your deployed backend environment.

image

Choose the Frontend environments tab, select your Git provider, then choose Connect Branch.

image

Follow the steps in the Amplify console to choose the branch to connect, and deploy your app.

Note: Your CloudFront Distribution may take several minutes to go from "In Progress" to "Active". Visit your CloudFront Console to monitor progress.

After your site is successfully deployed, you'll see four green checkmarks. To view the live site, click on the automatically generated URL circled in red in the following screenshot.

image

Congratulations, your app has now been successfully deployed!

Kicking off a new build

You can kick off a new build directly from the Amplify console or by pushing changes to main.

  1. Make some changes to your code

  2. Push the changes to git

1$ git add .
2$ git commit -m 'updates'
3$ git push origin main

API routes

Amplify now supports API routes in Next.js apps. Any file inside the folder pages/api is mapped to /api/* and treated as an API endpoint instead of a page. You can use these APIs to interface with any backend service to fetch data.