NextJS Authentication with Next Auth

In this post we will learn to do authentication in our NextJS app easily, though the awesome Next Auth package. The link for the same is NextAuth.js (next-auth.js.org)

First, we need to create a new NextJS app with the below command.

After that as per the documentation, inside the api folder, create an auth folder. Inside it create a file […nextauth].js and add the below boiler plate code in it.

Now, we need to get the Github credentials. So, go to Your Profile (github.com) and scroll down and click on Developer settings tab.

Now, in the next page, click on New Github App button.

Now, we need to give the app a name, description and also Homepage URL and Callback URL as mentioned below.

While scrolling down also unselect Webhook. After that towards the end give the profile access and click on Create Github App button.

Now, you will get the Client ID on the next screen. Also need to click on Generate a new client secret button.

Now, you will also get the Client secrets exposed.

Back in our application, we need to create an .env.local file in the root directory. Here, we are adding the client secret from the previous steps.

Now, in the _app.js file, we need to wrap the SessionProvider as shown below. We also need to install next-auth in our app.

Now, in the index.js file, we will use signIn, useSession, signOut from next-auth. Here, we have two buttons, one for Sign in and other for sign out.

Both of these are using the inbuilt functions. We are also using session to check if the session exists.

Now, in localhost, we will see the Not siged in text and Sign in button.

On clicking on the Sign in button, we will be shown the Sign in with Github page. Here, we need to click on it.

And we will be signed in successfully and the Sign out button will be displayed.

If we click on the Sign out button, we will be sign out again.

This completes our small app. The code for the same can be found in this github link.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nabendu Biswas

Nabendu Biswas

Founder TWD, JavaScript & ReactJS Trainer, Youtuber, Blogger