Next.js course ยท Module 7: Authentication and Authorization

Implementing NextAuth.js / Auth.js

16 min read ยท
In this lesson14

NextAuth.js (now also known as Auth.js) is a comprehensive authentication solution for Next.js applications. It provides ready-made infrastructure for managing sessions, tokens, login, registration, and integration with external authentication providers. In this module, we will cover the detailed implementation of this tool in Next.js applications.

Why use NextAuth.js?

NextAuth.js offers many benefits:

  1. Ready-made solution - no need to implement authentication from scratch
  2. Support for various providers - offers integration with over 50 authentication providers
  3. Security - implements security best practices
  4. Session management - handles sessions on both server and client side
  5. Flexibility - can be customized to specific application needs
  6. App Router support - works with the new Next.js architecture
  7. Extended TypeScript typings - offers full type support

Installation and basic configuration

Let's start by installing NextAuth.js:

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

Basic configuration for the App Router

To configure NextAuth.js in the App Router architecture, we need to create a file to handle the Route API for authentication:

// app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import GithubProvider from "next-auth/providers/github";

export const authOptions = {
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID!,
      clientSecret: process.env.GITHUB_SECRET!
    })
  ],
  // Additional configuration options...
};

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

This file creates a dynamic API route that handles all necessary authentication endpoints.

Adding the SessionProvider component

To enable the use of the hook useSession in client-side components, we need to add SessionProvider to our application. It is best to do this in a Provider file or directly in the main layout:

// app/providers.tsx
'use client';

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

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

// app/layout.tsx
import { Providers } from "./providers";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

Environment variables configuration

NextAuth.js requires several environment variables. Create or update the file .env.local in the project's main directory:

# Basic configuration for NextAuth.js
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your_secret_key_for_jwt_encryption

# GitHub authentication data (example)
GITHUB_ID=your_github_client_id
GITHUB_SECRET=your_github_client_secret

In a production environment:

  • NEXTAUTH_URL should be the full URL of your application
  • NEXTAUTH_SECRET should be a long, random string of characters. You can generate it using the command openssl rand -base64 32.

Configuration of different authentication providers

NextAuth.js supports many authentication providers. Let's look at how to configure a few popular ones:

1. Authentication with GitHub

import GithubProvider from "next-auth/providers/github";

export const authOptions = {
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID!,
      clientSecret: process.env.GITHUB_SECRET!,
      // Optional parameters
      scope: "read:user user:email", // Specifies access scope
      profile(profile) {
        // Customizing user profile
        return {
          id: profile.id.toString(),
          name: profile.name || profile.login,
          email: profile.email,
          image: profile.avatar_url,
          // Additional fields
          username: profile.login,
        };
      },
    }),
  ],
  // Other configuration options...
};

2. Authentication with Google

import GoogleProvider from "next-auth/providers/google";

export const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
      // Optional parameters
      authorization: {
        params: Promise<{
          prompt: "consent",
          access_type: "offline",
          response_type: "code"
        }>
      }
    }),
  ],
  // Other configuration options...
};

3. Authentication with credentials (email/password)

import CredentialsProvider from "next-auth/providers/credentials";
import { compare } from "bcrypt";
import { prisma } from "@/lib/prisma"; // We assume you have a configured Prisma instance

export const authOptions = {
  providers: [
    CredentialsProvider({
      // Name displayed on the login page
      name: "Credentials",
      // Login form field configuration
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials) {
        // Check if credentials exist
        if (!credentials?.email || !credentials?.password) {
          return null;
        }

        try {
          // Find the user in the database
          const user = await prisma.user.findUnique({
            where: { email: credentials.email },
          });

          if (!user || !user.password) {
            return null;
          }

          // Check if the password is correct
          const isPasswordValid = await compare(
            credentials.password,
            user.password
          );

          if (!isPasswordValid) {
            return null;
          }

          // Return the user object (without password)
          return {
            id: user.id,
            name: user.name,
            email: user.email,
            role: user.role,
            // Other fields you want to include
          };
        } catch (error) {
          console.error("Authentication error:", error);
          return null;
        }
      },
    }),
  ],
  // Other configuration options...
};

4. Authentication from multiple providers

You can combine multiple authentication providers:

export const authOptions = {
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID!,
      clientSecret: process.env.GITHUB_SECRET!,
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
    CredentialsProvider({
      // Configuration...
      async authorize(credentials) {
        // Authentication logic...
      },
    }),
    // You can add more providers...
  ],
  // Other configuration options...
};

Configuring session and JWT options

NextAuth.js offers different session strategies:

export const authOptions = {
  // Provider configuration...

  session: {
    // Choose strategy: 'jwt' or 'database'
    strategy: 'jwt',

    // Maximum session lifetime (in seconds)
    maxAge: 30 * 24 * 60 * 60, // 30 days

    // Session update on each request, extending its validity
    updateAge: 24 * 60 * 60, // 24 hours
  },

  // JWT configuration (only for the 'jwt' strategy)
  jwt: {
    // Secret key used to sign JWT tokens
    // By default uses NEXTAUTH_SECRET
    secret: process.env.JWT_SECRET,

    // You can customize JWT encoder/decoder
    // encode: async ({ secret, token, maxAge }) => {},
    // decode: async ({ secret, token }) => {},
  },
};

Custom authentication pages

By default, NextAuth.js provides simple login pages, but you can replace them with your own:

export const authOptions = {
  // Provider configuration...

  pages: {
    signIn: '/auth/login',
    signOut: '/auth/logout',
    error: '/auth/error', // Authentication error (e.g. invalid credentials)
    verifyRequest: '/auth/verify-request', // Used for Magic Links
    newUser: '/auth/new-user' // Page shown after first registration
  },
};

Then you need to create these pages in your application. Here is an example login page:

// app/auth/login/page.tsx
'use client';

import { signIn, useSession } from 'next-auth/react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useState, useEffect } from 'react';

export default function LoginPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get('callbackUrl') || '/dashboard';
  const { status } = useSession();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  // Redirect the logged-in user
  useEffect(() => {
    if (status === 'authenticated') {
      router.push(callbackUrl);
    }
  }, [status, router, callbackUrl]);

  // GitHub login handling
  const handleGitHubSignIn = () => {
    setIsLoading(true);
    signIn('github', { callbackUrl });
  };

  // Google login handling
  const handleGoogleSignIn = () => {
    setIsLoading(true);
    signIn('google', { callbackUrl });
  };

  // Credentials login handling
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError('');

    try {
      const result = await signIn('credentials', {
        redirect: false,
        email,
        password,
      });

      if (result?.error) {
        setError('Invalid email or password');
        setIsLoading(false);
      } else {
        router.push(callbackUrl);
      }
    } catch (error) {
      setError('An error occurred during login');
      setIsLoading(false);
    }
  };

  if (status === 'loading') {
    return <div>Loading...</div>;
  }

  return (
    <div className="max-w-md mx-auto mt-10 p-6 bg-white rounded-lg shadow-md">
      <h1 className="text-2xl font-bold mb-6 text-center">Log in</h1>

      {error && (
        <div className="mb-4 p-3 bg-red-100 text-red-700 rounded">
          {error}
        </div>
      )}

      <div className="space-y-4 mb-6">
        <button
          type="button"
          onClick={handleGitHubSignIn}
          disabled={isLoading}
          className="w-full flex items-center justify-center gap-2 p-2 border border-gray-300 rounded-md hover:bg-gray-50"
        >
          <svg width="20" height="20" fill="currentColor" viewBox="0 0 24 24">
            {/* Logo GitHub */}
            <path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z" />
          </svg>
          Continue with GitHub
        </button>

        <button
          type="button"
          onClick={handleGoogleSignIn}
          disabled={isLoading}
          className="w-full flex items-center justify-center gap-2 p-2 border border-gray-300 rounded-md hover:bg-gray-50"
        >
          <svg width="20" height="20" fill="currentColor" viewBox="0 0 24 24">
            {/* Logo Google */}
            <path d="M12 24C5.385 24 0 18.615 0 12S5.385 0 12 0s12 5.385 12 12-5.385 12-12 12zm0-22.5C6.21 1.5 1.5 6.21 1.5 12S6.21 22.5 12 22.5 22.5 17.79 22.5 12 17.79 1.5 12 1.5zm-5.25 9v3h3v3h3v-3h3v-3h-3v-3h-3v3h-3z" />
          </svg>
          Continue with Google
        </button>
      </div>

      <div className="relative my-6">
        <div className="absolute inset-0 flex items-center">
          <div className="w-full border-t border-gray-300"></div>
        </div>
        <div className="relative flex justify-center text-sm">
          <span className="px-2 bg-white text-gray-500">
            or sign in with email
          </span>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label htmlFor="email" className="block text-sm font-medium mb-1">
            Email
          </label>
          <input
            id="email"
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            className="w-full px-3 py-2 border border-gray-300 rounded-md"
          />
        </div>

        <div>
          <label htmlFor="password" className="block text-sm font-medium mb-1">
            Password
          </label>
          <input
            id="password"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
            className="w-full px-3 py-2 border border-gray-300 rounded-md"
          />
        </div>

        <button
          type="submit"
          disabled={isLoading}
          className="w-full bg-blue-500 text-white py-2 px-4 rounded-md hover:bg-blue-600 disabled:opacity-50"
        >
          {isLoading ? 'Logging in...' : 'Log in'}
        </button>
      </form>
    </div>
  );
}

Callbacks and events

NextAuth.js allows reacting to various events in the authentication lifecycle through callbacks:

export const authOptions = {
  // Provider configuration...

  callbacks: {
    // Called when creating a session
    async session({ session, token }) {
      // Add token data to the session
      if (token.sub && session.user) {
        session.user.id = token.sub;
      }

      // Add custom fields, e.g. user role
      if (token.role && session.user) {
        session.user.role = token.role as string;
      }

      return session;
    },

    // Called when creating a JWT
    async jwt({ token, user, account, profile }) {
      // Add user data on first login
      if (user) {
        token.role = user.role;
        // Other custom fields...
      }

      return token;
    },

    // Called after login
    async signIn({ user, account, profile, email, credentials }) {
      // Check if the user has access to the application
      return true; // Return false to deny access
    },

    // Called during redirect
    async redirect({ url, baseUrl }) {
      // Redirect rules
      if (url.startsWith(baseUrl)) {
        return url;
      }
      // By default redirect to the base page
      return baseUrl;
    },
  },

  // Events
  events: {
    async signIn(message) {
      // Called after login
      console.log('User signed in:', message);
    },
    async signOut(message) {
      // Called after logout
      console.log('User signed out:', message);
    },
    async createUser(message) {
      // Called after user creation
      console.log('User created:', message);
    },
    async linkAccount(message) {
      // Called after account linking
      console.log('Account linked:', message);
    },
    async session(message) {
      // Called after session creation
      console.log('Session created/updated:', message);
    },
  },
};

Extending types for TypeScript

If you use TypeScript, you can extend NextAuth.js types to include custom fields:

// In the type extension file (e.g. types/next-auth.d.ts)
import 'next-auth';
import 'next-auth/jwt';

declare module 'next-auth' {
  interface Session {
    user: {
      id: string;
      name?: string | null;
      email?: string | null;
      image?: string | null;
      role?: string;
      // Add other custom fields...
    };
  }

  interface User {
    id: string;
    name?: string | null;
    email?: string | null;
    image?: string | null;
    role?: string;
    // Add other custom fields...
  }
}

declare module 'next-auth/jwt' {
  interface JWT {
    role?: string;
    // Add other custom fields...
  }
}

Database adapters

To use the database-based session strategy or store user accounts, NextAuth.js offers adapters for various databases:

Configuration with Prisma

import { PrismaAdapter } from "@auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export const authOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    // Provider configuration...
  ],
  // Other options...
};

The Prisma schema should contain the appropriate models:

// prisma/schema.prisma
model Account {
  id                String  @id @default(cuid())
  userId            String
  type              String
  provider          String
  providerAccountId String
  refresh_token     String? @db.Text
  access_token      String? @db.Text
  expires_at        Int?
  token_type        String?
  scope             String?
  id_token          String? @db.Text
  session_state     String?

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
}

model Session {
  id           String   @id @default(cuid())
  sessionToken String   @unique
  userId       String
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  password      String?
  role          String?   @default("user")
  accounts      Account[]
  sessions      Session[]
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

Other available adapters

NextAuth.js offers adapters for many databases:

  • SQL adapters: PostgreSQL, MySQL, SQLite, SQL Server
  • Non-relational adapters: MongoDB, DynamoDB
  • ORM/ODM: Prisma, Mongoose, Typeorm, Sequelize, DrizzleORM
  • Others: Firebase, Supabase, Kysely, Planetscale, Xata

Using authentication in the application

1. Fetching session data on the client side

After configuring NextAuth.js, you can use the hook useSession in client components:

'use client';

import { useSession } from 'next-auth/react';
import { redirect } from 'next/navigation';

export default function Dashboard() {
  const { data: session, status } = useSession({
    required: true,
    onUnauthenticated() {
      redirect('/auth/login?callbackUrl=/dashboard');
    },
  });

  if (status === 'loading') {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>Dashboard</h1>
      <p>Hello, {session.user.name}!</p>
      <p>Your email: {session.user.email}</p>
      {session.user.role === 'admin' && (
        <div>
          <h2>Administrator panel</h2>
          {/* Content only for administrators */}
        </div>
      )}
    </div>
  );
}

2. Fetching session data on the server side

In server-rendered components, you can use getServerSession:

// app/profile/page.tsx
import { getServerSession } from 'next-auth/next';
import { redirect } from 'next/navigation';
import { authOptions } from '../api/auth/[...nextauth]/route';

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

  if (!session) {
    redirect('/auth/login?callbackUrl=/profile');
  }

  return (
    <div>
      <h1>Profile</h1>
      <p>Hello, {session.user.name}!</p>
      <p>Your email: {session.user.email}</p>
      {/* Rest of the profile content */}
    </div>
  );
}

3. Authentication state management

NextAuth.js provides functions for managing authentication state:

'use client';

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

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

  if (session) {
    return (
      <button
        onClick={() => signOut({ callbackUrl: '/' })}
        className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
      >
        Log out
      </button>
    );
  }

  return (
    <button
      onClick={() => signIn()}
      className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
    >
      Log in
    </button>
  );
}

Adapting the UI to NextAuth.js

We can create a component that renders different interface elements depending on the authentication state:

'use client';

import { useSession } from 'next-auth/react';
import Link from 'next/link';
import { AuthButton } from './AuthButton';

export function Navbar() {
  const { data: session, status } = useSession();
  const isLoading = status === 'loading';

  return (
    <nav className="bg-white shadow-md p-4">
      <div className="container mx-auto flex justify-between items-center">
        <Link href="/" className="text-xl font-bold">
          MyApp
        </Link>

        <div className="flex items-center space-x-4">
          <Link href="/" className="hover:text-blue-500">
            Home page
          </Link>

          {session ? (
            <>
              <Link href="/dashboard" className="hover:text-blue-500">
                Dashboard
              </Link>
              <Link href="/profile" className="hover:text-blue-500">
                Profile
              </Link>
              {session.user.role === 'admin' && (
                <Link href="/admin" className="hover:text-blue-500">
                  Admin
                </Link>
              )}
            </>
          ) : (
            <Link href="/features" className="hover:text-blue-500">
              Features
            </Link>
          )}

          {!isLoading && (
            <div className="flex items-center space-x-2">
              {session && (
                <div className="flex items-center">
                  {session.user.image && (
                    <img
                      src={session.user.image}
                      alt={session.user.name || 'User'}
                      className="w-8 h-8 rounded-full mr-2"
                    />
                  )}
                  <span className="text-sm font-medium">
                    {session.user.name}
                  </span>
                </div>
              )}
              <AuthButton />
            </div>
          )}
        </div>
      </div>
    </nav>
  );
}

Authentication with API Routes

NextAuth.js can also be used to secure API endpoints:

// app/api/protected-data/route.ts
import { getServerSession } from 'next-auth/next';
import { NextResponse } from 'next/server';
import { authOptions } from '../auth/[...nextauth]/route';

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

  if (!session) {
    return NextResponse.json(
      { message: 'Unauthorized access' },
      { status: 401 }
    );
  }

  // Check permissions based on role (optional)
  if (session.user.role !== 'admin') {
    return NextResponse.json(
      { message: 'Insufficient permissions' },
      { status: 403 }
    );
  }

  // Data available only to logged-in users (and admins if we check roles)
  return NextResponse.json({
    message: 'Success',
    data: {
      secretContent: 'This data is protected',
      timestamp: new Date().toISOString()
    }
  });
}

Best practices for implementing NextAuth.js

  1. Security first

    • Use HTTPS in production
    • Generate a strong NEXTAUTH_SECRET
    • Never store sensitive data in JWT tokens
  2. Performance optimization

    • Use session strategies appropriate to your needs
    • Consider using the JWT strategy for greater scalability
  3. Error handling

    • Implement custom error pages
    • Log authentication errors for analysis
  4. User experience

    • Design user-friendly login forms
    • Allow smooth switching between providers
  5. Testing

    • Test different authentication scenarios
    • Check how the application reacts to expired sessions

Advanced scenarios

1. Multi-step authentication

In some cases, you may want to implement multi-step authentication (e.g. password + SMS code):

// Implement a custom CredentialsProvider
CredentialsProvider({
  name: 'TwoFactor',
  credentials: {
    email: { label: "Email", type: "email" },
    password: { label: "Password", type: "password" },
    code: { label: "Verification code", type: "text" }
  },
  async authorize(credentials) {
    if (!credentials?.email || !credentials?.password) {
      return null;
    }

    // First step: verify password
    const user = await prisma.user.findUnique({
      where: { email: credentials.email }
    });

    if (!user || !await compare(credentials.password, user.password)) {
      return null;
    }

    // Second step: verify the verification code
    if (credentials.code) {
      const isValidCode = await verifyTwoFactorCode(user.id, credentials.code);

      if (!isValidCode) {
        return null;
      }
    } else {
      // If the code was not provided and is required
      if (user.twoFactorEnabled) {
        // Sending the code to email/phone
        await sendTwoFactorCode(user);

        // Return a special object so App Router knows we need a code
        throw new Error('TwoFactorRequired');
      }
    }

    // Authentication successful
    return {
      id: user.id,
      email: user.email,
      name: user.name,
      role: user.role
    };
  }
})

2. Implementing custom registration logic

// app/api/register/route.ts
import { NextResponse } from 'next/server';
import { hash } from 'bcrypt';
import { prisma } from '@/lib/prisma';
import { z } from 'zod';

// Validation schema
const userSchema = z.object({
  name: z.string().min(2, 'First name must be at least 2 characters'),
  email: z.string().email('Invalid email address'),
  password: z.string().min(8, 'Password must be at least 8 characters')
});

export async function POST(request: Request) {
  try {
    const body = await request.json();

    // Validate data
    const result = userSchema.safeParse(body);

    if (!result.success) {
      return NextResponse.json(
        { message: result.error.errors[0].message },
        { status: 400 }
      );
    }

    const { name, email, password } = result.data;

    // Check if user already exists
    const existingUser = await prisma.user.findUnique({
      where: { email }
    });

    if (existingUser) {
      return NextResponse.json(
        { message: 'A user with this email address already exists' },
        { status: 409 }
      );
    }

    // Hash the password
    const hashedPassword = await hash(password, 10);

    // Create new user
    const user = await prisma.user.create({
      data: {
        name,
        email,
        password: hashedPassword,
        role: 'user' // Default role
      }
    });

    // Do not return password in response
    const { password: _, ...userWithoutPassword } = user;

    return NextResponse.json(
      { message: 'Registration completed successfully', user: userWithoutPassword },
      { status: 201 }
    );
  } catch (error) {
    console.error('Registration error:', error);
    return NextResponse.json(
      { message: 'A server error occurred' },
      { status: 500 }
    );
  }
}

Summary

NextAuth.js (Auth.js) is a comprehensive tool for implementing authentication in Next.js applications. It offers:

  1. Flexibility - supports multiple authentication strategies
  2. Integration - easily integrates with various providers
  3. Security - implements best security practices
  4. Scalability - works with various databases and architectures
  5. Extensibility - can be adapted to specific needs

Thanks to NextAuth.js, you can quickly implement a complete authentication system in your Next.js application, saving time and minimizing the risk of security-related errors.

In the following modules, we will discuss more advanced aspects of authentication, including authentication strategies, session and token management, and implementation of roles and permissions.

Code for this lesson: App.tsx
import React, { useState } from 'react';

// Demo: NextAuth.js / Auth.js - configuration and providers
interface AuthConfig {
  provider: string;
  callbackUrl: string;
  strategy: 'jwt' | 'database';
  maxAge: number;
}

const defaultProviders: AuthConfig[] = [
  { provider: 'credentials', callbackUrl: '/dashboard', strategy: 'jwt', maxAge: 3600 },
  { provider: 'google', callbackUrl: '/dashboard', strategy: 'jwt', maxAge: 86400 },
  { provider: 'github', callbackUrl: '/dashboard', strategy: 'database', maxAge: 604800 },
];

function AuthConfigBuilder() {
  const [configs, setConfigs] = useState<AuthConfig[]>(defaultProviders);
  const [newProvider, setNewProvider] = useState('');
  const [strategy, setStrategy] = useState<'jwt' | 'database'>('jwt');
  const [showCode, setShowCode] = useState(false);

  const addProvider = () => {
    if (!newProvider.trim()) return;
    setConfigs(prev => [...prev, {
      provider: newProvider.trim(),
      callbackUrl: '/dashboard',
      strategy,
      maxAge: strategy === 'jwt' ? 3600 : 86400,
    }]);
    setNewProvider('');
  };

  const removeProvider = (index: number) => {
    setConfigs(prev => prev.filter((_, i) => i !== index));
  };

  // Keywords from variables: the editor preview strips import/export lines from the code, even inside template text
  const kw = { imp: 'import', exp: 'export' };
  const generatedCode = `// app/api/auth/[...nextauth]/route.ts
${kw.imp} NextAuth from 'next-auth';
${configs.map(c => {
  if (c.provider === 'credentials') return kw.imp + " CredentialsProvider from 'next-auth/providers/credentials';";
  return kw.imp + " " + c.provider.charAt(0).toUpperCase() + c.provider.slice(1) + "Provider from 'next-auth/providers/" + c.provider + "';";
}).join('\n')}

${kw.exp} const authOptions = {
  providers: [
${configs.map(c => "    // " + c.provider + " provider\n    // strategy: " + c.strategy).join(',\n')}
  ],
  session: {
    strategy: '${configs[0]?.strategy || 'jwt'}',
    maxAge: ${configs[0]?.maxAge || 3600},
  },
  callbacks: {
    async jwt({ token, user }) {
      if (user) token.role = user.role;
      return token;
    },
    async session({ session, token }) {
      session.user.role = token.role;
      return session;
    },
  },
};`;

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
      <h1 style={{ color: '#64ffda', marginBottom: '8px' }}>NextAuth.js / Auth.js Configuration</h1>
      <p style={{ color: '#8892b0', marginBottom: '24px' }}>Interactive NextAuth.js configurator - add providers and generate code</p>

      <div style={{ display: 'flex', gap: '12px', marginBottom: '24px', flexWrap: 'wrap' }}>
        <input
          value={newProvider}
          onChange={e => setNewProvider(e.target.value)}
          placeholder="Provider name (e.g. discord)"
          style={{ padding: '8px 12px', borderRadius: '6px', border: '1px solid #333', background: '#1a1a2e', color: '#fff', flex: 1, minWidth: '200px' }}
        />
        <select
          value={strategy}
          onChange={e => setStrategy(e.target.value as 'jwt' | 'database')}
          style={{ padding: '8px 12px', borderRadius: '6px', border: '1px solid #333', background: '#1a1a2e', color: '#fff' }}
        >
          <option value="jwt">JWT Strategy</option>
          <option value="database">Database Strategy</option>
        </select>
        <button onClick={addProvider} style={{ padding: '8px 16px', borderRadius: '6px', background: '#64ffda', color: '#0f0f23', border: 'none', cursor: 'pointer', fontWeight: 'bold' }}>
          + Add Provider
        </button>
      </div>

      <div style={{ display: 'grid', gap: '12px', marginBottom: '24px' }}>
        {configs.map((config, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 16px', background: '#1a1a2e', borderRadius: '8px', border: '1px solid #333' }}>
            <div>
              <strong style={{ color: '#64ffda' }}>{config.provider}</strong>
              <span style={{ color: '#8892b0', marginLeft: '12px', fontSize: '14px' }}>
                Strategy: {config.strategy} | MaxAge: {config.maxAge}s
              </span>
            </div>
            <button onClick={() => removeProvider(i)} style={{ background: '#ef4444', color: '#fff', border: 'none', borderRadius: '4px', padding: '4px 8px', cursor: 'pointer' }}>
              Remove
            </button>
          </div>
        ))}
      </div>

      <button
        onClick={() => setShowCode(!showCode)}
        style={{ padding: '10px 20px', borderRadius: '6px', background: showCode ? '#333' : '#7c3aed', color: '#fff', border: 'none', cursor: 'pointer', marginBottom: '16px' }}
      >
        {showCode ? 'Hide code' : 'Generate configuration code'}
      </button>

      {showCode && (
        <pre style={{ background: '#1a1a2e', padding: '16px', borderRadius: '8px', overflow: 'auto', fontSize: '13px', lineHeight: 1.5, border: '1px solid #333' }}>
          <code style={{ color: '#e0e0e0' }}>{generatedCode}</code>
        </pre>
      )}
    </div>
  );
}

export default AuthConfigBuilder;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Authentication means:

  2. 2. Authorization means:

Hands-on tasks in the game

  • Code editor

    Build an interface with protected sections that require login

  • Vertical ordering

    Arrange the elements in the correct order: import 'server-only' โ†’ export async โ†’ fu

  • Click in order

    Arrange the elements in the correct order: import โ†’ NextAuth โ†’ from

  • Code editor

    Create a login component with JWT authentication

  1. QuestionAuthentication means:
  2. QuestionAuthorization means:
  3. Coding taskPractice: Protected Sections with Login
  4. Put in orderOrder: import 'server-only' โ†’ export async โ†’ ...
  5. Click in orderOrder: import โ†’ NextAuth โ†’ from
  6. Coding taskPractice: Login with JWT

Useful articles