Authentication in a Next.js App with AWS Amplify
Published: 2022-06-06 10:14:29

Protecting an application starts with authentication and authorization, ensuring users have access to the right information. This tutorial will show you how to add authentication and authorization with ease to your next.js application using AWS Amplify.

{% embed https://www.youtube.com/watch?v=0ofxWRzBLWY %}

## Prerequisites

To follow along you need to have;

1. [AWS account](https://aws.amazon.com/)
2. [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) installed in your Next.js app
## Create an Amplify Project

To create an Amplify project, Navigate to your AWS console, search for AWS Amplify, 
then click on **New App**, and select **Build an app** from the dropdown.

![](https://paper-attachments.dropbox.com/s_C38F5CEC8BB29CD3A19182E3C7142AF8195960DD2E8DBCAAA81F54DFCB0CBDEE_1650516755146_amplify_new.PNG)

![](https://paper-attachments.dropbox.com/s_C38F5CEC8BB29CD3A19182E3C7142AF8195960DD2E8DBCAAA81F54DFCB0CBDEE_1650516761571_select_new.PNG)


Give the **App** a name and click on **Confirm deployment** button to deploy.

![](https://paper-attachments.dropbox.com/s_C38F5CEC8BB29CD3A19182E3C7142AF8195960DD2E8DBCAAA81F54DFCB0CBDEE_1650516940959_deploy_new.PNG)


Once the deployment is completed, click the **Launch Studio** button to launch the Amplify studio.

![](https://paper-attachments.dropbox.com/s_C38F5CEC8BB29CD3A19182E3C7142AF8195960DD2E8DBCAAA81F54DFCB0CBDEE_1650516955737_launch_new.PNG)



## Enable Auth

The Amplify studio gives access to many cool features like Database modeling, UI library storage, authentication, and more. For this tutorial, you will be using the authentication feature of AWS Amplify.

Click on authentication at the sidebar to configure the authentication. Make the password less strict by disabling uppercase, symbol, and character when creating a password.


![](https://paper-attachments.dropbox.com/s_C38F5CEC8BB29CD3A19182E3C7142AF8195960DD2E8DBCAAA81F54DFCB0CBDEE_1650517076504_auth_new.PNG)

![](https://paper-attachments.dropbox.com/s_C38F5CEC8BB29CD3A19182E3C7142AF8195960DD2E8DBCAAA81F54DFCB0CBDEE_1650517081761_pass_new.PNG)


Click on **Deploy** and **Confirm Deployment**. 

## 
## Create Next.js App

Now that the backend is all set, head back to your local machine and create a Next.js app. To do that, Run the command below in your project directory.

```sh
npx create-next-app amplify-next-auth
```

## Install Amplify Dependencies

Next is to install all the Amplify dependencies needed for this project. Run the command below to install them.

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

The `aws-amplify` SDK allows you to connect your application to Amplify while 
`@aws-amplify/ui-react` is the Amplify component SDK.


## Pull Amplify Project into React Project

Now that we have the back-end and client-side ready, you need to link the two together. Head back to your AWS Amplify studio and click the deployment link at the top right hand corner.

![](https://paper-attachments.dropbox.com/s_C38F5CEC8BB29CD3A19182E3C7142AF8195960DD2E8DBCAAA81F54DFCB0CBDEE_1650531545706_pull_new.PNG)


Copy the pull command and run it in your project directory.

AWS Amplify will prompt you to confirm access. Click yes and head back to the terminal. Amplify will ask you a series of questions, choose default for most except for the last three, 

![](https://paper-attachments.dropbox.com/s_C38F5CEC8BB29CD3A19182E3C7142AF8195960DD2E8DBCAAA81F54DFCB0CBDEE_1650531707678_Screenshot+41.png)



## Configure Amplify for React Project

After pulling the Amplify project, you should have some files and folders added to your project.


![](https://paper-attachments.dropbox.com/s_C38F5CEC8BB29CD3A19182E3C7142AF8195960DD2E8DBCAAA81F54DFCB0CBDEE_1650531774215_Screenshot+43.png)



**amplify** folder**:** This is where all the back-end code resides.
**aws-export** file: This is the configuration file. 
**Note**: This should not be committed to git.

To use the Amplify SDK, you need to configure it at the root level of your project. Next.js uses the `_app.js` as the root file.
Head to _app.js and import the SDK. paste the code below in your `_app.js` file.

```js
import '../styles/globals.css'
import {Amplify} from "aws-amplify"
import awsconfig from "../aws-exports"
import '@aws-amplify/ui-react/styles.css'
    
Amplify.configure({...awsconfig,ssr:true})

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

export default MyApp
``` 

The above code snippet imports and set configurations for the AWS Amplify, for easy integration and display of an interactive user interface. 
****
## Protecting the Client

After configuring the Amplify project, the next is to protect the components, head to the `pages/index.js` file, and replace the code with the below.

```js
import { withAuthenticator } from "@aws-amplify/ui-react";
    
function Home({signOut,user}){
    return (
        <>
          <h1>hello {user.username}</h1>
          <button onClick={signOut}>Sign Out</button>
        </>
      )
}
export default withAuthenticator(Home)
```

The `withAuthenticator` higher order component handles the protection by allowing only authenticated users to access the `Home` component, also providing a pre-built login and registration feature.

## Testing

To test the application run the command below,

```sh
npm run dev
```

Amplify protects the `Home` component by providing a login and registration feature.

You can log in by providing your email and password; afterward, you will be sent a confirmation token. 
Enter the token sent and click confirm to access the `Home` component. 

![](https://paper-attachments.dropbox.com/s_C38F5CEC8BB29CD3A19182E3C7142AF8195960DD2E8DBCAAA81F54DFCB0CBDEE_1650666852902_login_new.PNG)



## Protect SSR Pages

After signing in, AWS Amplify saves your authentication token in the local storage. You will use that in protecting your server side rendered (SSR) pages. 
Navigate to the `/pages` folder and create a `protected.js` file. Paste the command below.

```js
import {withSSRContext} from "aws-amplify"
    
function Protected({authenticated,username}){
    if(!authenticated){
        return <h1>Not Authenticated</h1>
    }
    return <h1>Hello {username} from SSR route!</h1>
}

export async function getServerSideProps(context){

const {Auth} = withSSRContext(context)

try{
    const user = await Auth.currentAuthenticatedUser()

return {
    props:{
        authenticated:true, username:user.username
    }
}

}catch(err){
    console.log(err)
    return {
        props:{
            authenticated:false
        }
    }
}
}
export default Protected 

```

This component will receive `authenticated`, and `username` props which will be used to render the component conditionally whether authenticated props is true or false.
The protected component receives the props through the `getServerSideprops` function. The function grabs the `Auth` function from the `withSSRContext` imported from the AWS Amplify SDK.


## Conclusion

This tutorial discussed on how to easily implement authentication and authorization to a Next.js app. Don't forget to check the official documentation of [AWS Amplify](https://docs.amplify.aws/console/)  to explore further and add more features to your app. 
[](http://)