How to use NextAuth in Next.js?

How to use NextAuth in Next.js?

Published 8th, November, 2022

3 min read

Next.js is a blessing for many React.js developers as it made developing the front-end much of a convenience than before, and many have even gone full-stack because of it. And the main reason here is that Next.js comes packed with many tools and APIs that do a lot of heavy-lifting.

One such feature that Next.js includes, out of many is the NextAuth authentication solution that allows you to create robust user authentication swiftly and smoothly for your application. And here are some reasons why would you want to go for it

  1. It supports the most sought-after OAuth service with versions 1.0, 1.A and version 2.0
  2. Apart from having compatibility for many built-in systems, it also supports email and no-password authentications.
  3. It supports serverless applications on platforms such as AWS Lambda, Heroku and Docker.
  4. It works fine with database sessions as well as JSON-based web tokens/

Also, its highly secure built and design deserves a separate mention with other points.

  1. No-password sign-in methods are also considered as an alternative.
  2. It uses CSRF tokens for POST methods.
  3. Implements recent standards set by Open Web Application Security Project.
  4. Default encryption for JSON Web Tokens.

Data flexibility

  1. NextAuth.js can also be used without a database
  2. It can not only be used any database, whether SQL or no SQL, but also supports the Bring Your Own Database.
  3. You don’t need to install additional modules because it inherently supports MySQL, MongoDB and Postgres to name a few.
  4. This provides a great amount of data storage flexibility and autonomy to the application developers.

Without a further ado, let’s get to the main part

Local installation

npm install next-auth

This simple command installs the local implementation tools for Next Auth

Adding your API route

To create a dynamic route handler for your API, create a file named nextAuthAPI.js in the directory api/auth/. This file will contain all universal configuration settings for NextAuth.js
After importing a. NextAuth from next-auth and b. GithubProvider from “github” directory from the providers directory

We setup up a function that registers the ready-to-use authentication providers such as the GithubProvider inbuilt module.


export const authOptions = { 

providers: 
	[ GithubProvider({ 
		clientId: process.env.GITHUB_ID, 
		clientSecret: process.env.GITHUB_SECRET, 

	}), 

	],

}

export default NextAuth(authOptions)

Configuring session state

Go to your main application file and add the SessionProvider into your code to expose the so-called ‘session context’.


import  { SessionProvider } from “next-auth/react”
export default function frontApp({
Component,
pageProps: {session, ...pageProps }, 
	})
	{
return (
		<SessionProvider session = {session}>
			<Component  {… pageProps },
		<SessionProvider>
	)
}

Adding React-Hook for the front-end

The useSession() React Hook enables your code to check if the user has signed into his account. We ’ll implement this inside the login-btn.jsx file.

First you need to import useSession, signIn and signOut from the next-auth/react directory


export default function Component() {
  const { data: currentSession } = useSession()
  if (currentSession) {
    return (
      <>
        Signed in as {currentSession.user.email} <br />
        <button onClick={() => signOut()}>Sign out</button>
      </>
    )
  }

Having written the above logic, we now write how the front-end will handle this

  return (
    <>
      User not signed in <br />
      <button onClick={() => signIn()}>Sign in</button>
    </>
  )
}

Implementing API Route in the back-end

The highlight of this section is to use the unstable_getServerSession() function for protecting your API route. Therefore, we shall import the unstable _getServerSession function from next-auth/next
and authOptions from ./auth/[...nextauth] in the restricted.js file in pages/api

export default async (req, res) => {
  const currentSession = await unstable_getServerSession(req, res, authOptions)

  if (currentSession) {
    res.send({
      content:
       “This content is only meant for authorized users, and since you are seeing this, you’ve been let in."
    })
  } else {
    res.send({
      error: "Since you are not signed in, you are seeing this message instead of the main content",
    })
  }
}

Login page token sent to client-side

Next-Auth.js comes with built-in callbacks that let your application forward a value from the login backend to the front-end/client-side, by allowing you to implement both standard sessions and JSON Web Tokens.

Inside the nextauth.js file

callbacks: {
  async jwt({ mainToken, user_account }) {
    if (user_account) {
      mainToken.jwtaccessToken = user_account.useraccessToken
    }
    return mainToken
  },
  async session({ currentSession, mainToken, user_account }) {
    currentSession.useraccessToken = mainToken.useraccessToken
    return currentSession
  }
}

In the accessToken.js file we will import useSession, signIn and signOut from the next-auth/react


export default function Component() {
  const { data } = useSession()
  const { accessToken } = data

  return <div>Access Token: {accessToken}</div>
}

After creating a useSession() object, we can return it in the HTML rendering in form of a data variable.

And that’s it! If you have gotten the gist of the whole process, go ahead and implement this either at work or for your side-hustle projects.

References:

  1. nextauth