NextAuth.js Setup in Next.js

In this tutorial, you will learn how to set up NextAuth.js in Next.js.

NextAuth.js is the most popular authentication library for Next.js. It provides secure, flexible, and easy-to-use authentication.

It supports many things like

  1. Email & Password
  2. OAuth (Google, GitHub, Facebook, etc.)
  3. Credentials login
  4. JWT & Database sessions

Note: NextAuth works perfectly with the Next.js App Router.

NextAuth.js Setup process

Step 1: Firstly, install next-auth package


npm install next-auth

Step 2: For App Router, create file below:


app/api/auth/[...nextauth]/route.js

Step 3: Basic NextAuth Configuration Setup


import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

export const authOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",

      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Password", type: "password" },
      },

      async authorize(credentials) {
        // Temporary static login (for learning)
        if (
          credentials.email === "admin@gmail.com" &&
          credentials.password === "123456"
        ) {
          return {
            id: "1",
            email: "admin@gmail.com",
          };
        }

        return null;
      },
    }),
  ],

  session: {
    strategy: "jwt",
  },

  secret: process.env.NEXTAUTH_SECRET,
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

Step 4: Add Environment Variables

Create a .env.local file in the root folder and put the code below.


NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=mysecretkey

Now, generate a secret through command below


openssl rand -base64 32

Step 5: Add Session Provider (Required)

NextAuth needs a provider to share session data across your app.

Now, create a providers.js file (app/providers.js)


"use client";

import { SessionProvider } from "next-auth/react";

export default function Providers({ children }) {
  return <SessionProvider>{children}</SessionProvider>;
}

Step 6: Add the provider to the app/layout.js file.


import Providers from "./providers";

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

Step 7: Login & Logout Example

Now, you will see login and Logout functionality.


"use client";

import { signIn, signOut, useSession } from "next-auth/react";

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

  if (session) {
    return (
      <>
        <p>Welcome {session.user.email}</p>
        <button onClick={() => signOut()}>Logout</button>
      </>
    );
  }

  return (
    <button
      onClick={() =>
        signIn("credentials", {
          email: "admin@gmail.com",
          password: "123456",
        })
      }
    >
      Login
    </button>
  );
}

Step 8: Protect Any Page (Server Side)

Now, you will see how to protect any page.


import { getServerSession } from "next-auth";
import { authOptions } from "../api/auth/[...nextauth]/route";
import { redirect } from "next/navigation";

export default async function Dashboard() {
  const session = await getServerSession(authOptions);

  if (!session) {
    redirect("/login");
  }

  return <h1>Dashboard Page</h1>;
}

How NextAuth Works?

There are some steps NextAuth works

  1. When the user clicks the Login button.
  2. NextAuth checks credentials (username and password).
  3. If logged in successfully, then a session is created.
  4. User will stay logged in.
  5. Protected pages require a session.

Advantages of NextAuth.js

There are many advantages of NextAuth.js

1. It is very easy to setup.

2. Authentication is very secure.

3. Supports Email, Google, GitHub, etc.

4. It is used for session handling.

5. It works with App Router.

NextAuth.js Setup in Next.js – Interview Questions

Q 1: What is NextAuth.js?
Ans: An authentication library for Next.js.
Q 2: Which authentication providers are supported?
Ans: Google, GitHub, Email, Credentials, etc.
Q 3: Where is NextAuth configured?
Ans: In app/api/auth/[...nextauth]/route.js.
Q 4: Does NextAuth support JWT?
Ans: Yes.
Q 5: Is NextAuth secure?
Ans: Yes, it follows industry standards.

NextAuth.js Setup in Next.js – Objective Questions (MCQs)

Q1. NextAuth.js is used for:






Q2. Which route is used to configure NextAuth in App Router?






Q3. Which authentication method is supported by NextAuth.js?






Q4. Which function initializes NextAuth?






Q5. Session management in NextAuth.js is handled using:






Related NextAuth.js Setup in Next.js Topics