DEV Community

Cover image for ⚡️ 5 Minute Tutorial: Deploying a NextJS app with AWS Amplify Hosting
Nader Dabit
Nader Dabit

Posted on • Updated on

⚡️ 5 Minute Tutorial: Deploying a NextJS app with AWS Amplify Hosting

Cover image by Lubo Minar

In this tutorial you'll learn how to deploy a Next app to AWS using Amplify Hosting.

There are two options: One using the Amplify CLI, and the other using a Git repository. We will cover both.

  1. CLI workflow
  2. Git-based workflow

CLI workflow

To get started, create a new Next site:

$ npm init next-app

✔ What is your project named? my-app
✔ Pick a template › Default starter app
Enter fullscreen mode Exit fullscreen mode

Next, change into the new directory and update package.json to add the export script to the existing build script:

"scripts": {
  "dev": "next dev",
  "build": "next build && next export",
  "start": "next start"
},
Enter fullscreen mode Exit fullscreen mode

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

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

$ npm install -g @aws-amplify/cli

$ amplify configure
Enter fullscreen mode Exit fullscreen mode

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

Next, initialize a new Amplify project. Make sure you se the Distribution Directory Path to out.

$ amplify init

? Enter a name for the project: mynextapp
? Enter a name for the environment: dev
? Choose your default editor: Visual Studio Code (or your preferred editor)
? Choose the type of app that youre building: javascript
? What javascript framework are you using: react
? Source Directory Path: src
? Distribution Directory Path: out
? Build Command: npm run-script build
? Start Command: npm run-script start
? Do you want to use an AWS profile? Y
? Please choose the profile you want to use: <your profile>
Enter fullscreen mode Exit fullscreen mode

Now, add hosing with the Amplify add command:

$ amplify add hosting

? Select the plugin module to execute: Hosting with Amplify Console
? Choose a type: Manual deployment
Enter fullscreen mode Exit fullscreen mode

Next, deploy the app:

$ amplify publish

? Are you sure you want to continue? Yes
Enter fullscreen mode Exit fullscreen mode

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

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

$ amplify console
Enter fullscreen mode Exit fullscreen mode

For a complete walkthrough of how to do this, check out this video:

Deploying updates

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

$ amplify publish
Enter fullscreen mode Exit fullscreen mode

Deleting the app

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

$ amplify delete
Enter fullscreen mode Exit fullscreen mode

Git-based deployments

Amplify also offers Git-based deployments with features like CI/CD and branch previews.

To host using a Git-based deployment, follow these steps instead.

1. Create your app

$ npm init next-app

✔ What is your project named? my-app
✔ Pick a template › Default starter app
Enter fullscreen mode Exit fullscreen mode

2. Be sure to set the new build script in your package.json:

"scripts": {
  "dev": "next dev",
  "build": "next build && next export",
  "start": "next start"
},
Enter fullscreen mode Exit fullscreen mode

3. Create a Git repository, then push your code to Git.

$ git init
$ git remote add origin git@github.com:your-name/my-next-app.git
$ git add .
$ git commit -m 'initial commit'
$ git push origin master
Enter fullscreen mode Exit fullscreen mode

4. Go to the Amplify Console and click "Connect App"

5. Follow the steps to choose your Git provider and your branch.

6. Set the baseDirectory to out.

Setting the baseDirectory property

7. Click Next then Save and deploy.

For a complete walkthrough of how to do this, check out this video:

Kicking off a new build

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

  1. Make some changes to your code

  2. Push the changes to git

$ git add .
$ git commit -m 'updates'
$ git push origin master
Enter fullscreen mode Exit fullscreen mode

Dynamic routes

Next also supports dynamic routes.

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

/pages/posts/[id].js
Enter fullscreen mode Exit fullscreen mode

This component needs to read the ID of the URL parameter and use this data in some way in the app. To make this happen, we can use next/router:

// /pages/posts/[id].js
import { useRouter } from 'next/router'

const Post = () => {
  const router = useRouter()
  const { id } = router.query

  return <p>Post: {id}</p>
}

export default Post
Enter fullscreen mode Exit fullscreen mode

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:

Dynamic Routes with Amplify Console hosting

API routes

At this time, Amplify hosting does not support API routes with NextJS.

If you are interested in this functionality, I would recommend instead checking out Vercel or the Serverless NextJS Component.

Top comments (15)

Collapse
 
chrisrbailey profile image
Chris Bailey

Nader, thanks for this. I'm struggling with dynamic routes for a Nuxt app. I'm wondering if you've seen how to do this for that case? I believe that the main problem is that Nuxt doesn't generate a page during the generate/build stage that I can redirect to. I have their regular dynamic routes setup and working locally (and it works when I do a push in my Nuxt app - just not if I try to directly navigate to a dynamic page, as if I'd bookmarked it for example). If you know of any solutions for Nuxt, I'd love to know.

Collapse
 
chrisrbailey profile image
Chris Bailey

I figured out a workaround. If I add a trailing slash it works. So, using URL's like, "somepath/somepage/?param1=foo" (instead of the usual somepath/somepage?param1=foo) works.

Collapse
 
dabit3 profile image
Nader Dabit

Hey Chris, thanks for the follow up here, I had yet to try this but will now be trying more with Nuxt so this helps.

Collapse
 
zural profile image
Shiva

Hi Developers,

I have problem in next rewrite rules,
(working) example.com --> index.html
(not working) example.com/country --> /pages/[country]/index.html
(not working) example.com/country/city --> /pages/[country]/[city]/index.html

My configuration in rewrite rules,

[
    {
        "source": "/<*>",
        "target": "/index.html",
        "status": "404-200",
        "condition": null
    },
    {
        "source": "/<*>/",
        "target": "/pages/[country]/index.html",
        "status": "200",
        "condition": null
    },
    {
        "source": "/<*>/<*>/",
        "target": "/pages/[country]/[city]/index.html",
        "status": "200",
        "condition": null
    }
]
Enter fullscreen mode Exit fullscreen mode

Ref code repo : github.com/hosseinAMD/next-playground

Help me to fix this !!

Collapse
 
jrosales90 profile image
Juan Antonio

Hi! Did you can resolve this fix?

Collapse
 
ywroh profile image
ywroh

Thanks for the good info. As you told me, I deployed the nextjs app with amplify, but an error occurred in the build commands. To fix the error, I changed the pre build commands to yarn install --frozen-lockfile and the build commands to yarn build, and it deployed well without any errors.

Collapse
 
vasujogani profile image
vasujogani

Hey Nader, this is a great post! Could you please do something similar for React Native? Currently, I am using Expo and Amplify (App sync, lambda, Cognito) for development. There isn't great documentation that I could find for the deployment of these apps to the app store/play store and how to maintain and update over time. Could you please do something similar for RN, that would be really really helpful.

Also, slightly relevant question: is hosting category useful for React native development? Also, how can I set up my Frontend and Backend on Amplify for RN?

Thank you

Collapse
 
mdabdulhalimrafi profile image
Md. Abdul Halim Rafi

Can you please teach how can I host nextJs with SSR (server.js) in aws?

Collapse
 
ibrahimcesar profile image
Ibrahim Cesar

You can using CDK, an exemple repo: github.com/ibrahimcesar/nextjs-ssr...

Collapse
 
cweekly profile image
Chris Weekly

Thanks for sharing, @ibrahim Cesar.
Cool PoC, and nice writeup (ibrahimcesar.cloud/blog/nextjs-typ...).

For the sake of other readers I want to point out that the CDK construct for serverless-nextjs is still experimental (serverless-nextjs.com/docs/cdkcons...), and observability (especially tracing, but also logging) is still problematic with the serverless-nextjs component in general.

Collapse
 
shypixel profile image
shypixel

Thank you for the excellent tutorials~
When I tried, I got an error related to images:
github.com/vercel/next.js/blob/mas...
When I deployed the same build to Vercel I did not experience the same issue as specified here nextjs.org/docs/basic-features/ima...

I guess I will just do this initial deployment test without an image but could anyone enlighten me... if there's an easy way around it?
I could be wrong but it seems to allow these cloud providers only -- Imgix, Cloudinary, Akama-- how about S3 or WITHOUT any?

Collapse
 
ponyjackal profile image
ponyjackal

Thank you for your post

Collapse
 
imewish profile image
Vishnu Prassad

This so Cool. Can we deploy Next apps with SSR enabled to amplify? @dabit3

Collapse
 
dabit3 profile image
Nader Dabit

Not yet, but we are working on supporting hosting SSR support.

Collapse
 
krankj profile image
Sudarshan K J • Edited

Starting 18th May, 2021, AWS has started support for SSR and API Routes.
More info here: aws.amazon.com/blogs/mobile/host-a...