Implementing Authentication in Next.js with NextAuth.js

Reading Time: 7 min read

Introduction

Authentication is a critical aspect of web applications, ensuring that users can securely access their data and interact with your platform. Next.js, combined with NextAuth.js, offers a straightforward way to implement authentication in your applications. In this post, we'll explore how to set up authentication in a Next.js app using NextAuth.js.

Why Use NextAuth.js?

NextAuth.js is a flexible and easy-to-implement authentication library designed specifically for Next.js applications. It supports various authentication providers, including OAuth, email/password, and custom credentials.

Setting Up Your Project

  1. Create a Next.js App:

    Start by creating a new Next.js application.

    npx create-next-app next-auth-app
    cd next-auth-app
  2. Install NextAuth.js:

    Install NextAuth.js and its dependencies.

    npm install next-auth

Configuring NextAuth.js

  1. Create an API Route:

    NextAuth.js requires an API route to handle authentication. Create a new file at pages/api/auth/[...nextauth].js.

    // pages/api/auth/[...nextauth].js
    import NextAuth from 'next-auth'
    import Providers from 'next-auth/providers'
     
    export default NextAuth({
      providers: [
        Providers.Google({
          clientId: process.env.GOOGLE_CLIENT_ID,
          clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        }),
        // Add more providers here
      ],
      database: process.env.DATABASE_URL,
    })
  2. Environment Variables:

    Create a .env.local file in the root of your project to store your environment variables.

    GOOGLE_CLIENT_ID=your-google-client-id
    GOOGLE_CLIENT_SECRET=your-google-client-secret
    DATABASE_URL=your-database-url

Setting Up the Sign-In Page

NextAuth.js automatically handles the sign-in page, but you can customize it as needed.

Create a Sign-In Page

Create a new file at pages/signin.js.

// pages/signin.js
import { signIn, signOut, useSession } from 'next-auth/client'
 
const SignInPage = () => {
  const [session, loading] = useSession()
 
  return (
    <div>
      {!session && (
        <>
          <h1>Sign In</h1>
          <button onClick={() => signIn('google')}>Sign in with Google</button>
        </>
      )}
      {session && (
        <>
          <h1>Welcome, {session.user.name}</h1>
          <button onClick={() => signOut()}>Sign Out</button>
        </>
      )}
    </div>
  )
}
 
export default SignInPage

Protecting Routes

To protect routes and ensure that only authenticated users can access certain pages, use the useSession hook.

Example: Protected Page

Create a new file at pages/protected.js.

// pages/protected.js
import { useSession, getSession } from 'next-auth/client'
 
const ProtectedPage = () => {
  const [session, loading] = useSession()
 
  if (loading) return <p>Loading...</p>
  if (!session) return <p>You are not authenticated.</p>
 
  return (
    <div>
      <h1>Protected Page</h1>
      <p>Welcome, {session.user.name}</p>
    </div>
  )
}
 
export async function getServerSideProps(context) {
  const session = await getSession(context)
 
  if (!session) {
    return {
      redirect: {
        destination: '/signin',
        permanent: false,
      },
    }
  }
 
  return {
    props: { session },
  }
}
 
export default ProtectedPage

Customizing NextAuth.js

NextAuth.js is highly customizable. You can add callbacks, events, and even customize the session and JWT.

Example: Custom Callbacks

Modify the [...nextauth].js file to include custom callbacks.

// pages/api/auth/[...nextauth].js
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
 
export default NextAuth({
  providers: [
    Providers.Google({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  callbacks: {
    async jwt(token, user) {
      if (user) {
        token.id = user.id
      }
      return token
    },
    async session(session, token) {
      session.user.id = token.id
      return session
    },
  },
})

Conclusion

Implementing authentication in Next.js using NextAuth.js is straightforward and flexible. By following the steps outlined in this post, you can set up a secure and efficient authentication system in your Next.js applications. Start leveraging NextAuth.js today to enhance your user experience and security.

For more detailed information, visit the NextAuth.js documentation.

Go back Home.