Adding user Authentication in Next.js using NextAuth
In this article, we will learn How we can add user authentication in our NextJS project. 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 in our project first we will install the nextauth module. After that, we will create a dynamic file with […nextauth].js name. Then we will add different providers inside this file for authenticating. After that, we will add login and signout option on our homepage.
Create NextJS Application:
Step 1: You can create a new NextJs project using the below command:
npx create-next-app gfg
Project Structure: It will look like this.
Step 2: Install NextAuth using the below command:
npm i next-auth
Step 3: Now go to Google developer console and get your Oauth API ID and key.
Step 4: Now create a new folder inside the page/api directory and name that folder auth. Inside that folder create a new file with the name […nextauth].js and add the below code in that file.
Here first we are import NextAuth and GoogleProvider from next-auth. After that, we are using only Google as our authentication provider.
Step 5: Now we are going to add Provider on every page and for that, we will add Provider in our _app.js file. Add the below code in your _app.js file.
Step 6: Now we can add the login and logout buttons on our homepage. For that, we are going to use the useSession() hook to check if the user is logged in or not. We will add the below code in our index.js file.
Here first we are checking if a session exists or not. If a session exists that means the user is already logged in then we are showing the user Sign out button but if the user is not logged in then we are showing the Sign In button.
Step to run the application: Now run the app using the below code:
npm run dev