Adding User Authentication in Next.js using Auth0
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:
AUTH0_SECRET= "[A 32 characters secret used to encrypt the cookies]" AUTH0_BASE_URL="http://localhost:3000" AUTH0_ISSUER_BASE_URL="YOUR_AUTH0_DOMAIN" AUTH0_CLIENT_ID="YOUR_AUTH0_CLIENT_ID" AUTH0_CLIENT_SECRET="YOUR_AUTH0_CLIENT_SECRET"
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.
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.
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.
Step to run application: After that run the app with the below command:
npm run dev
Please Login to comment...