Nextjs User Login Authentication in 5 simple steps using Auth0.
Tags: nextjs, auth0, authentication, tailwindcss
Published: 2022-02-18 02:39:10

---
title: Nextjs User Login Authentication in 5 simple steps using Auth0.
published: true
date: 2022-01-09 07:04:00 UTC
tags: Nextjs, Auth0 ,Authentication,#tailwindcss
canonical_url: https://nextjsdev.com/nextjs-user-login-authentication-in-5-simple-steps-using-auth0/
---

 ![Nextjs User Login Authentication in 5 simple steps using Auth0.](https://nextjsdev.com/content/images/2022/01/nextjs-image-3.PNG)

Hello everyone, I hope you all are well. In this post we are going to discuss, how you can set up a user Login authentication using Auth0 in Next.js projects.

Here is a little demo of the project, that we are going to build:

[Demo Video Link](https://www.loom.com/share/aa0dbb52628949178364fb3b5e8ad2fa)

So, let's jump right into it. We will be doing this in 5 easy steps:

<!--kg-card-begin: markdown-->

> Note: I have used Tailwind CSS for as a CSS framework and created a custom Navbar for this project , If you wish to get the code for the same , you can visit my [Github project link](https://github.com/raiv200/Nextjs-Auth0) and copy from there.

<!--kg-card-end: markdown-->
## STEP-1 Create your Auth0 Account

Create an Auth0 Account. Then visit your dashboard and under Applications click on Application, then click on Create Application and provide a name to the application and choose the " **Regular web Application**" category.

Now you will see 5 tabs, one of them is Settings, click on setting and then scroll down a little bit and you will find "Application URIs".

Inside that, you have to fill the ALLOWED\_CALLBACK\_URL and the ALLOWED\_LOGOUT\_URL like this.

![Nextjs User Login Authentication in 5 simple steps using Auth0.](https://nextjsdev.com/content/images/2022/01/Step1-create-application.PNG)
_Auth0 create application_

![Nextjs User Login Authentication in 5 simple steps using Auth0.](https://nextjsdev.com/content/images/2022/01/step-1-Allowed-Url.PNG)
_Auth0 change application URL_

After this scroll down to the end and then click on save changes.

## STEP-2  Setup Next.js App and download the Auth0 package

Create a Nextjs App using the create-next-app app-name.

For this tutorial I have created the Next.js app with TailwindCSS, just to style the application a little bit, you don't need to do that.

In case you want to set up nextjs-app with tailwindCSS, just use this one command it will do the rest.

<!--kg-card-begin: markdown-->
```bash
npx create-next-app -e with-tailwindcss my-project
cd my-project

```
<!--kg-card-end: markdown-->

And now cd into your folder and install the **@auth0/nextjs-auth0** package.

<!--kg-card-begin: markdown-->
```bash
npm install @auth0/nextjs/auth0

```
<!--kg-card-end: markdown-->
## Step-3 Create .env.local file to store the credentials.

Create a **.env.local**  file in the root directory of your project and paste this in your **.env.local** file and change the values with your Client\_ID, Client\_Secret, and ISSUER\_BASE\_URL, which you can find in your Auth0 dashboard.

<!--kg-card-begin: markdown-->
```bash
AUTH0_SECRET='LONG_RANDOM_VALUE_32_CHARACTERS_LONG'
AUTH0_BASE_URL='http://localhost:3000'
AUTH0_ISSUER_BASE_URL='https://YOUR_AUTH0_DOMAIN.auth.com'
AUTH0_CLIENT_ID='YOUR_AUTH0_CLIENT_ID'
AUTH0_CLIENT_SECRET='YOUR_AUTH0_CLIENT_SECRET'

```
<!--kg-card-end: markdown-->

![Nextjs User Login Authentication in 5 simple steps using Auth0.](https://nextjsdev.com/content/images/2022/01/step-3-auth-secret.PNG)
_Auth0 Client Secret & ID_

The base URL will remain the same and the rest three you can find in your Auth0 dashboard.

One more thing in the ISSUER\_BASE\_URL make sure that **https://** is present in the URL do not remove it.

And to generate the 32 characters string you can paste this code in your terminal and it will generate a 32 characters long random string.

<!--kg-card-begin: markdown-->
```bash
node -e "console.log(crypto.randomBytes(32).toString('hex'))"_

```
<!--kg-card-end: markdown-->
## Step-4 Create API routes

Now we have to create an API route for the login, logout, callback. In Next.js it is very simple to do.

Just navigate to the /pages/api folder and inside that create a folder name auth and inside that create a file name [...auth0].js  inside a square bracket like this:

![Nextjs User Login Authentication in 5 simple steps using Auth0.](https://nextjsdev.com/content/images/2022/01/Auth-api-route.PNG)
_Auth API Route_

So we can create any route like this **api/auth/login** , **api/auth/logout** , **api/auth/callback** like this.

The file name in the square bracket will accept any route, it is called catch-all routes.

Then navigate inside the [...auth0].js and paste these two line of code and save it.

<!--kg-card-begin: markdown-->
```jsx
import {handleAuth} from "@auth0/nextjs-auth0";

export default handleAuth();

```
<!--kg-card-end: markdown-->

Make sure you have installed the package "@auth0/nextjs-auth0" .

## Step-5 Final Step

So the last step is here. Navigate to /pages/\_app.js and inside that wrap the  inside a  Component like this and make sure to import it also.

![Nextjs User Login Authentication in 5 simple steps using Auth0.](https://nextjsdev.com/content/images/2022/01/Uerprovider-Component.PNG)
_Code snippet Image_

So these were the 5 steps to make authentication work in a Next.js Application.

If you open your terminal and cd to your project and type "npm run dev", you will see the application is running on port 3000.

Now change the URL and visit **http://localhost:3000/api/auth/login**.

You will see the Auth0 Login page and you will be able to use it and sign in to it.

![Nextjs User Login Authentication in 5 simple steps using Auth0.](https://nextjsdev.com/content/images/2022/01/Auth0-login-page.PNG)
_Auth0 Login Page_

But, the important question arises, how to use it, and how do we know we are authenticated or not?

## How to use

We can use it for the following things:

1. To show some pages in our website which can only be seen if the user is authenticated.
2. If a user is not logged In, we can show a Sign In button, and if the user is Signed In we can show him a Logout button.

So to use this we need to use a Custom Hook provided by the auth0 package, which is **useUser** hook.

Navigate to **pages/index.js** and  write the following code:

<!--kg-card-begin: markdown-->
```jsx

import {useUser} from "@auth0/nextjs-auth0";

  // you can use the error and loading state to show an error message or a loading spinner while loading.

Inside the Home function just above return, statement write this 

const {user ,error , isLoading} = useUser();

if (isLoading) {
    return (
      <div className="text-5xl font-semibold text-center text-indigo-600">
        ...loading{" "}
      </div>
    );
  }

  if(error){
    return (
      <div className="text-5xl font-semibold text-center text-indigo-600">
        {error.message}
      </div>
    )
  }

```
<!--kg-card-end: markdown-->

and then below the **H1** tag paste this code:

<!--kg-card-begin: markdown-->
```
<div className="max-w-[500px] border-4 border-indigo-400 rounded-lg p-6 mx-auto text-3xl mt-16 font-bold text-indigo-700 text-center">
       {user && (
         <p className="mb-6">Welcome 
         <span className="text-amber-600">{user.name}</span></p>
         )}
        {!user && (
          <p>You are Not signed In, Please Sign In to view the Secret Pages.</p>
          )}
  </div>

```
<!--kg-card-end: markdown-->

You can do the same thing as above to show the S **ign In** button only if the user is not logged In and the **Logout** button only if the user is already logged In.

Now suppose you have a members-only page in your application and you want only authenticated users can visit that page.

This can be easily done using the **withPageAuthRequired** Hook provided with nextjs-auth0 SDK.

Create a members-only.js file inside the **pages** directory and paste this code inside the file givenn below.

<!--kg-card-begin: markdown-->
```jsx

import {withPageAuthRequired } from "@auth0/nextjs-auth0";

const membersOnly = () => {
    return (
        <div>
        <h1 className="text-5xl font-semibold mt-10 text-center text-indigo-600">This page is for Members Only.</h1>   
        </div>
    )
}

export default membersOnly;

export const getServerSideProps = withPageAuthRequired();

```
<!--kg-card-end: markdown-->

So by doing this only authenticated users can visit the page and those who are not authenticated and try to visit the page will be shown a **404 page** or may be redirected to the login page automatically.

## Conclusion

So that was all about Nextjs Authentication using Auth0. I hope you like this and enjoyed building this project.

If you really think that this was helpful and then please do consider to visit my original blog link  and do follow me on **twitter** and connect with me on **linkedIn**.

If you were stuck somewhere and not able to find the solution you can check out my completed repository here.

Thanks for your time to read this project, if you like this please share it on Twitter and Facebook or any other social media and tag me there.

Some Useful Link:

1. [Next.js and Tailwind Installation Docs](https://tailwindcss.com/docs/guides/nextjs)
2. [Auth0](https://auth0.com/)
3. [Github link for project](https://github.com/raiv200/Nextjs-Auth0)

Connect with me:

1. [Twitter Link](https://twitter.com/raivikas200)
2. [LinkedIn link](https://www.linkedin.com/in/raivikas200/)
3. [Facebook Link](https://www.facebook.com/raiv200/)
4. [Github Link](https://github.com/raiv200)

More articles to read:

* [Top 5 CSS frameworks to check out in 2022.](https://nextjsdev.com/top-5-css-frameworks-to-check-out-in-2022/)

* [Top 20 Vs Code shortcuts you must know and try.](https://nextjsdev.com/top-20-vscode-shortcuts-you-must-try-in-2021/)