Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Adding User Authentication in Next.js using Auth0

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In this article, we will learn How we can add user authentication in our NextJS project using Auth0. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally.

Approach: To add the user authentication using auth0 in our project first we will install the auth0 module. After that, we will create a dynamic file with […auth0].js name. Then we will add UserProvider on every page. After that, we will add a login and signout option on our homepage.

Create NextJS Application:

Step 1: Create a new NextJs project using the below command:

npx create-next-app gfg

Project Structure: It will look like this.

Step 2: Create a free account on the auth0 website and create a new application.

Step 3: Get your domain, client id, and client secret key from the setting tab in your account.

Step 4: Add the callback and logout URL. Callback user is used to redirecting the user after logging in and logout URL is used to redirect the user after logging out.

Step 5: Now we will install the auth0 module using the following command:

npm install @auth0/nextjs-auth0

Step 6: Create a new .env.local file with the following code:

  "[A 32 characters secret used to encrypt the cookies]"

Step 7: Create a new folder inside the page/api directory with name auth. Inside this folder create a new dynamic route file with name […auth0].js and add the below content inside the file.

Filename: […auth0].js


import { handleAuth } from '@auth0/nextjs-auth0';
export default handleAuth();

Step 8: Now we have to add auth0’s UserProvider on every page. For that, we will change the content of the _app.js file with the below content.

Filename: _app.js 


import React from 'react';
import { UserProvider } from '@auth0/nextjs-auth0';
export default function App({ Component, pageProps }) {
  return (
      <Component {...pageProps} />

Step 9: Now we will add the login and logout button on our homepage. For that, add the below lines in the index.js file.

Filename: index.js 


import { useUser } from "@auth0/nextjs-auth0";
export default function Login(){
 const { user, error, isLoading } = useUser()
 if (user) {
   return (
       <h2>Hey {}, You are logged in</h2>
       <a href="/api/auth/logout"><h1>Logout</h1></a>
 return <a href="/api/auth/login"><h1>Login</h1></a>;

Step to run application: After that run the app with the below command:

npm run dev


My Personal Notes arrow_drop_up
Last Updated : 05 Jan, 2023
Like Article
Save Article
Similar Reads
Related Tutorials