Back to articles

Modern Authentication with Next.js and NextAuth.js

AuthorMajd Muhtaseb04/28/20258 minutes
Modern Authentication with Next.js and NextAuth.js

Introduction

Authentication is a critical aspect of modern web applications. NextAuth.js simplifies the process of adding authentication to your Next.js applications, supporting various providers like Google, GitHub, and more. This article guides you through setting up NextAuth.js in your Next.js project.

Prerequisites

  • Node.js and npm installed
  • Next.js project set up

Installation

First, install NextAuth.js:

npm install next-auth
# or
yarn add next-auth
# or
pnpm add next-auth

Configuration

Create a file named [...nextauth].js inside the pages/api/auth directory. This file will handle the authentication routes.

// pages/api/auth/[...nextauth].js
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"

export const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET
    })
  ],
  secret: process.env.NEXTAUTH_SECRET
}

export default NextAuth(authOptions)

Remember to set the GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, and NEXTAUTH_SECRET environment variables. You can obtain the Google Client ID and Secret from the Google Cloud Console. Generate a secure random string for NEXTAUTH_SECRET.

Usage

In your Next.js components, you can use the useSession hook to access the user's session:

// components/Profile.js
import { useSession, signOut } from "next-auth/react"

export default function Profile() {
  const { data: session } = useSession()

  if (session) {
    return (
      <>
        Signed in as {session.user.email} <br />
        <button onClick={() => signOut()}>Sign out</button>
      </>
    )
  }
  return (
    <>
      Not signed in <br />
      <a href="/api/auth/signin">Sign in</a>
    </>
  )
}

Wrap your application with the SessionProvider in _app.js:

// pages/_app.js
import { SessionProvider } from "next-auth/react"

function MyApp({ Component, pageProps }) {
  return (
    <SessionProvider session={pageProps.session}>
      <Component {...pageProps} />
    </SessionProvider>
  )
}

export default MyApp

API Routes (Optional)

You can also protect API routes using the getSession function:

// pages/api/protected.js
import { getSession } from "next-auth/react"

export default async function handler(req, res) {
  const session = await getSession({ req })

  if (session) {
    res.send({ content: "This is protected content." })
  } else {
    res.status(401).send({ error: "You must be signed in to view the protected content." })
  }
}

Conclusion

NextAuth.js simplifies authentication in Next.js applications, allowing you to quickly add secure and modern authentication flows. By leveraging providers and the useSession hook, you can easily manage user sessions and protect your application's resources.