paint-brush
Nextjs User Login Authentication in 5 Simple Steps Using Auth0by@raivikas
898 reads
898 reads

Nextjs User Login Authentication in 5 Simple Steps Using Auth0

by Vikas RaiApril 14th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this post we are going to discuss, how you can set up a user Login authentication using Auth0 in Next.js projects. We will be doing this in 5 easy steps: Create an Auth0 account, create an API route and create routes. I have used Tailwind CSS for CSS and created a cutom Navbar for this project,. If you wish to get the code for the same, you can visit my [Github project link] and copy from there. 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.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - Nextjs User Login Authentication in 5 Simple Steps Using Auth0
Vikas Rai HackerNoon profile picture




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


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


Note: I have used Tailwind CSS for CSS and created a cutom Navbar for this project , If you wish to get the code for the same , you can visit my Github project link and copy from there.


STEP-1 Create your Auth0 Account

Create an Auth0 Account. The 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.

Auth0 create application


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.


npx create-next-app -e with-tailwindcss my-project
cd my-project

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

npm install @auth0/nextjs/auth0


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.


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'

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.

node -e "console.log(crypto.randomBytes(32).toString('hex'))"_

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:

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.


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

export default handleAuth();


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


Step-5

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.


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.


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:


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>
    )
  }

and then below the H1 tag paste this code:

<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>


You can do the same thing as above to show the Sign 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.

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();


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 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.


  1. Next.js and Tailwind Installation Docs
  2. Auth0
  3. Github link for project


Connect with me:


  1. Twitter Link
  2. LinkedIn link
  3. Facebook Link
  4. Github Link



Also Published Here