Front-End Web & Mobile

Deploy a Next.js 13 app with authentication to AWS Amplify

Introduction

AWS Amplify Hosting is a fully managed hosting service for applications built using static site generation (SSG) and server-side rendering (SSR) frameworks including Next.js 12 and 13. This tutorial explains how to create and deploy a Next.js 13 app with user authentication to Amplify Hosting in five steps.

  1. Create a Next.js app
  2. Create an Amplify project and configure authentication
  3. Create client-side UI
  4. Test locally
  5. Deploy to Amplify Hosting

Before you begin

This tutorial assumes the following prerequisites.

  • You have an AWS account.
  • Node.js 16 and Next.js 13 are installed on your machine.
  • Amplify CLI (version 10.4 or newer) is installed and configured on your machine.
  • You have some development experience including JavaScript, working in the terminal and using Git.

1. Create a Next.js app

Create a new app using Create Next App. Open Terminal then enter the commands to create a new Next.js app and change to the app’s directory.

npx create-next-app amplify-nextjs --javascript --no-eslint
cd amplify-nextjs

2. Create an Amplify project and configure authentication

Enter the command to create a new Amplify project.

amplify init -y

After it has been successfully initialized and connected to the cloud, enter the command to add authentication to your project.

amplify add auth

You will be prompted to answer three questions. Select the default answers as indicated below.

Do you want to use the default authentication and security configuration?
❯ Default configuration
  Default configuration with Social Provider (Federation)
  Manual configuration
  I want to learn more.
  
  How do you want users to be able to sign in? (Use arrow keys)
❯ Username
  Email
  Phone Number
  Email or Phone Number
  I want to learn more.
  
  Do you want to configure advanced settings?
❯ No, I am done.
  Yes, I want to make some additional changes.

After auth resource has been added, enter the command to push the auth resources to the Amplify project.

amplify push -y

3. Create client-side UI

Enter the command to install the Amplify JavaScript libraries and Amplify UI.

npm install aws-amplify @aws-amplify/ui-react

In your editor, replace the contents of the `pages/_app.js` file with the code below. This change allows all pages within the app to access the Amplify JavaScript libraries and Amplify UI.

import "@aws-amplify/ui-react/styles.css";
import { Amplify } from "aws-amplify";
import awsExports from "../src/aws-exports";
import "../styles/globals.css";

Amplify.configure({ ...awsExports, ssr: true });

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

export default MyApp;

Replace the contents of the `pages/index.js` file with the code below. The export default withAuthenticator(Home) line will show a login/register prompt for users who are not signed in.

For users who are signed in, the getServerSideProps() function returns a string containing the current date and time. The Home component displays the username, current date and time, and a button allowing the user to sign out.

import { withAuthenticator } from "@aws-amplify/ui-react";

export function getServerSideProps() {
  const renderedAt = new Date();
  const formattedBuildDate = renderedAt.toLocaleDateString("en-US", {
    dateStyle: "long",
  });
  const formattedBuildTime = renderedAt.toLocaleTimeString("en-US", {
    timeStyle: "long",
  });
  return {
    props: {
      renderedAt: `${formattedBuildDate} at ${formattedBuildTime}`,
    },
  };
}

function Home({ signOut, user, renderedAt }) {
  return (
    <div style={{ padding: 50 }}>
      <h1>Logged in as {user.username}.</h1>
      <div>
        <button onClick={signOut}>Sign out</button>
      </div>
      <p>This page was server-side rendered on {renderedAt}.</p>
    </div>
  );
}

export default withAuthenticator(Home);

4. Test locally

With the above changes saved, you can try out the app on your machine. Enter the command to start the Next.js development server then visit http://localhost:3000 using your web browser.

npm run dev

The app is fully functional on your machine, allowing you to create accounts, sign in and sign out. When signed in, you will see your username, the time (the page was rendered on your local server) and an option to log out.

After you have verified your app is working locally, commit your code to Git, using a provider of your choice—Amplify supports AWS CodeCommit, GitHub, GitLab and Bitbucket.

5. Deploy to Amplify Hosting

With your app committed to Git, you are ready to deploy to Amplify Hosting.

Visit the Amplify Console in the AWS region you chose when you configured the Amplify CLI before you began this tutorial. On the All apps page, select the amplifynextjs project you created earlier via the Amplify CLI.

Navigate to the Hosting environments tab, choose your Git repository hosting provider then select Connect branch.

Depending on your Git provider, you will be prompted to allow Amplify Hosting access to your repositories. After a successful authorization, choose the repository for this app from the Recently updated repositories list then select Next.

On the Build settings page, in the App build and test settings section, choose `dev` from the Environment list.

Enable the Full-stack CI/CD allows you to continously deploy frontend and backend changes on every code commit feature.

You must select or create a service role to grant Amplify Hosting permissions to run and create logs on your behalf. For this tutorial, we recommend you create a new role that is distinct from your other projects.

Create a new service role

Select the Create new role button in the blue panel, opening a new IAM tab in your browser. Leaving everything unchanged, select the Next: Permissions, Next: Tags then Next:Review buttons at the bottom of each page. On the Review page note the value of the Role name, then select the Create role button to create the role.

Close the IAM tab in your browser and return to the Amplify Build settings page. Select the refresh button, choose the new role name you just created then select the Next button.

On the Review page, select Save and deploy.

Amplify Hosting will provision an isolated build and hosting environment for your project and deploy it. The process will take 3–4 minutes; you can monitor progress by selecting the Provision, Build or Deploy links as shown below

After the deployment has completed, visit the URL shown in the console (like https://<branch-name>.<app-id>.amplifyapp.com).

Congratulations, you’ve successfully deployed a Next.js 13 app that uses SSR and user authentication to Amplify Hosting. Learn more at docs.amplify.aws.