Back to articles

Modern Authentication with Next.js and NextAuth.js

AuthorMajd Muhtaseb08/09/20257 minutes
Modern Authentication with Next.js and NextAuth.js

Introduction

Authentication is crucial for modern web applications. NextAuth.js provides a simple and secure way to add authentication to your Next.js apps, supporting various providers like Google, GitHub, and more. This guide outlines setting up NextAuth.js for your project.

Prerequisites

  • Node.js and npm installed
  • Next.js project created

Installation

Install next-auth:

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

Configuration

  1. Create the API route:

    Create a file pages/api/auth/[...nextauth].js:

    import NextAuth from "next-auth"
    import GoogleProvider from "next-auth/providers/google"
    
    export default NextAuth({
      providers: [
        GoogleProvider({
          clientId: process.env.GOOGLE_CLIENT_ID,
          clientSecret: process.env.GOOGLE_CLIENT_SECRET
        })
      ],
      secret: process.env.NEXTAUTH_SECRET
    })
    
  2. Environment Variables:

    Set the following environment variables in your .env.local file:

    GOOGLE_CLIENT_ID=your_google_client_id
    GOOGLE_CLIENT_SECRET=your_google_client_secret
    NEXTAUTH_SECRET=your_secret_key
    NEXTAUTH_URL=http://localhost:3000 #or your deployed URL
    
    • Get GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET from the Google Cloud Console.
    • Generate a random string for NEXTAUTH_SECRET.
  3. Wrap your app with SessionProvider:

    In _app.js or _app.tsx:

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

Usage

  1. Get the Session:

    Use the useSession hook to access the current user's session:

    import { useSession, signIn, signOut } from "next-auth/react"
    
    export default function Component() {
      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 />
          <button onClick={() => signIn()}>Sign in</button>
        </>
      )
    }
    

Conclusion

NextAuth.js simplifies the process of adding authentication to your Next.js applications. By following these steps, you can integrate secure and modern authentication with various providers, enhancing the security and user experience of your application. Remember to consult the official NextAuth.js documentation for advanced configurations and customization options.