SimpleNext.js

Add authentication to your Next.js app with NextAuth.js

Cover Image for Add authentication to your Next.js app with NextAuth.js
Marouane Reda
Marouane Reda

Implementing authentication in an app from the ground app is a sensitive and tedious process, luckily several new ways emerged to make this task easier (Firebase authentication, Auth0, passport.js, …) . We will see in this article how to implement authentication in our Next.js app using NextAuth.js.

What is NextAuth

NextAuth.js is a flexible, easy to use and secure open source authentication solution designed from the ground up to support Next.js and Serverless. It support multiple providers like Facebook, Google, Twitter, Github, … and the traditionnal email/password authentication method.

We will see now how to implement authentication using NextAuth.js and Github as a provider.

Step 1 : Create our app and install the packages

Let’s create our app first :

npx create-next-app nextauth-app

and install NextAuth.js:

npm install next-auth

Step2 : Configure our Github provider

To configure the authentication providers for our app, we will go to pages/api, then create the directory auth and under it the file […nextauth].js :

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'

export default NextAuth({
  providers: [
    // OAuth authentication providers, here GitHub...
    Providers.GitHub({
        clientId: process.env.GITHUB_ID,
        clientSecret: process.env.GITHUB_SECRET
      }),
    
  ],
  
})

Here we configure the Github provider with the clientId and the secret. these will be configured for the test environnement in the .env.local file in the root of our project :

GITHUB_ID=<Your_github_id>
GITHUB_SECRET=<Your_github_secret>

Where do I get these credentials?

You need to log in to your GitHub account, then go to https://github.com/settings/applications/new

https://firebasestorage.googleapis.com/v0/b/kmx1-16598.appspot.com/o/blog%2FCapture%20d%E2%80%99e%CC%81cran%202021-08-23%20a%CC%80%2023.03.47.png?alt=media&token=7d4aff06-38e3-49a3-8e5b-8109783a4685

From there you will add the application name, the url of your app ( localhost in our case, since we are only testing in our case) , and the callback url ( the callback is [url of your app]/api/auth/callback/[provider] , so in our case http://localhost:3000/api/auth/callback/github )

then you will be redirected to a page where you will see you client ID and can generate the secret.

https://firebasestorage.googleapis.com/v0/b/kmx1-16598.appspot.com/o/blog%2FCapture%20d%E2%80%99e%CC%81cran%202021-08-23%20a%CC%80%2022.16.35.png?alt=media&token=24439221-bed1-40cd-a434-beac195e0c96

Step 3 : Update your index.js and _app.js

In your index.js, we will now check if the user is logged in , which means a session exists, and show his username and a button to logout or if it is not logged in, then we show the log in button. Note that the session , the sign in and sign out method come out of the box with NextAuth.js.

The index.js file will look like this :

import {
  useSession, signIn, signOut
} from 'next-auth/client'

export default function Component() {
  const [ session, loading ] = useSession()
  if(session) {
    return <>
      Signed in as {session.user.name} <br/>
      <button onClick={() => signOut()}>Sign out</button>
    </>
  }
  return <>
    Not signed in <br/>
    <button onClick={() => signIn()}>Sign in</button>
  </>
}

We need also to add the provider we configured earlier to _app.js so the session can be verified in all the pages of the app.

_app.js :

import { Provider } from 'next-auth/client'

export default ({ Component, pageProps }) => {
  return (
    <Provider session={pageProps.session} >
      <Component {...pageProps} />
    </Provider>
  )
}

Step4 : Check the final result

So There is our home page :

https://firebasestorage.googleapis.com/v0/b/kmx1-16598.appspot.com/o/blog%2FCapture%20d%E2%80%99e%CC%81cran%202021-08-23%20a%CC%80%2022.33.35.png?alt=media&token=7653b63d-949b-4df6-b051-3c3f1d573f6f

We will now login, and we are redirected to the Github authentication screens :

https://firebasestorage.googleapis.com/v0/b/kmx1-16598.appspot.com/o/blog%2FCapture%20d%E2%80%99e%CC%81cran%202021-08-23%20a%CC%80%2022.35.31.png?alt=media&token=7f1113fe-1a81-43b2-b233-d8906d4f7e9c

https://firebasestorage.googleapis.com/v0/b/kmx1-16598.appspot.com/o/blog%2FCapture%20d%E2%80%99e%CC%81cran%202021-08-23%20a%CC%80%2022.35.57.png?alt=media&token=dd8df713-c8d3-4bde-a8cd-b95ad41f199a

https://firebasestorage.googleapis.com/v0/b/kmx1-16598.appspot.com/o/blog%2FCapture%20d%E2%80%99e%CC%81cran%202021-08-23%20a%CC%80%2022.41.49.png?alt=media&token=e798e97d-d655-44ff-9884-7c28958b51b0

https://firebasestorage.googleapis.com/v0/b/kmx1-16598.appspot.com/o/blog%2FCapture%20d%E2%80%99e%CC%81cran%202021-08-23%20a%CC%80%2022.36.54.png?alt=media&token=a9980323-0ce1-44a4-9156-4d201121a349

We are now logged in :

https://firebasestorage.googleapis.com/v0/b/kmx1-16598.appspot.com/o/blog%2FCapture%20d%E2%80%99e%CC%81cran%202021-08-23%20a%CC%80%2022.43.27.png?alt=media&token=b422171d-286c-4077-8328-39a407a93c9f

Conclusion

We have seen in this article how to implement easily authentication in our app using NextAuth.js and Github. The same process can be done using Facebook, Google, Twitter, …