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

Authentication and Authorization in Next.js

7 min read ยท
In this lesson6

In a world where personal data and secure access to resources are invaluable, authentication and authorization are fundamental aspects of any modern web application. Next.js, as a framework oriented toward production use, offers extensive tools and integrations that enable the implementation of secure authentication systems.

Authentication basics

Authentication is the process of verifying a user's identity - it answers the question "Who are you?". Authorization, on the other hand, determines what resources an authenticated user can access - it answers the question "What can you do?".

In Next.js applications, we can implement authentication in different ways:

  1. Custom approach - building an authentication system from scratch
  2. Libraries and SDKs - using ready-made solutions like NextAuth.js/Auth.js
  3. External services - integration with services like Firebase Auth, Auth0, Supabase Auth

NextAuth.js / Auth.js

NextAuth.js (now also known as Auth.js) is a popular, comprehensive library for authentication in Next.js applications. Its biggest advantages are:

  • Support for multiple authentication providers (Google, GitHub, Facebook, Twitter, etc.)
  • Built-in support for sessions and JWT tokens
  • Compatibility with API Routes and App Router
  • Easy configuration and minimal boilerplate code

Basic Auth.js configuration in App Router

Here is a simple Auth.js configuration example in an App Router application:

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

const handler = NextAuth({
  providers: [
    GitHubProvider({
      clientId: process.env.GITHUB_ID as string,
      clientSecret: process.env.GITHUB_SECRET as string,
    }),
    CredentialsProvider({
      name: 'Credentials',
      credentials: {
        username: { label: "Email", type: "email" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials) {
        // Here you should implement your own credentials verification logic
        // e.g. checking in the database
        if (credentials?.username === "admin@example.com" && credentials?.password === "password") {
          return { id: "1", name: "Admin", email: "admin@example.com" };
        }
        return null;
      }
    }),
  ],
  pages: {
    signIn: '/auth/signin',
    signOut: '/auth/signout',
    error: '/auth/error',
  },
  callbacks: {
    async session({ session, token }) {
      // Here we can add additional data to the session
      return session;
    },
    async jwt({ token, user }) {
      // Here we can add additional data to the JWT token
      if (user) {
        token.role = user.role;
      }
      return token;
    }
  }
});

export { handler as GET, handler as POST };

Authentication strategies

Auth.js supports three main authentication strategies:

  1. OAuth - authentication via external providers (Google, Facebook, GitHub, etc.)
  2. Credentials - authentication via your own login/password system
  3. Email - authentication using links sent by email (passwordless)

Using client components for session management

In client components we can use hooks provided by Auth.js:

// app/components/login-button.tsx
'use client';

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

export function LoginButton() {
  const { data: session, status } = useSession();

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

  if (session) {
    return (
      <div>
        <p>Logged in as: {session.user?.name}</p>
        <button onClick={() => signOut()}>Log out</button>
      </div>
    );
  }

  return <button onClick={() => signIn()}>Log in</button>;
}

Session Provider in the main layout

To use useSession() in client components, we need to add SessionProvider to the main application layout:

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

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

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

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

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

Middleware for protecting routes

Next.js allows using middleware to secure routes against unauthorized access. Here is an example middleware that checks the user's session and redirects to the login page if no session exists:

// middleware.ts
import { NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
import type { NextRequest } from 'next/server';

export async function middleware(request: NextRequest) {
  const token = await getToken({ req: request });

  // Paths that should be protected
  const protectedPaths = ['/dashboard', '/profile', '/settings'];

  // Check if the current path is protected
  const isProtectedPath = protectedPaths.some(path =>
    request.nextUrl.pathname.startsWith(path)
  );

  if (isProtectedPath && !token) {
    // If the user tries to access a protected path without being logged in,
    // we redirect them to the login page
    const loginUrl = new URL('/auth/signin', request.url);
    loginUrl.searchParams.set('callbackUrl', request.nextUrl.pathname);
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/dashboard/:path*', '/profile/:path*', '/settings/:path*'],
};

User roles and permissions

In more complex applications, we often need to implement a role and permission system. We can extend the default Auth.js mechanisms to support roles:

// We extend the types for Auth.js
declare module "next-auth" {
  interface User {
    role?: string;
  }

  interface Session {
    user?: {
      id?: string;
      name?: string;
      email?: string;
      role?: string;
    };
  }
}

// In the Auth.js callbacks
callbacks: {
  async jwt({ token, user }) {
    if (user) {
      token.role = user.role;
    }
    return token;
  },
  async session({ session, token }) {
    if (session.user) {
      session.user.role = token.role as string;
    }
    return session;
  }
}

Then we can create conditional components based on roles:

// app/components/role-guard.tsx
'use client';

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

interface RolesGuardProps {
  children: React.ReactNode;
  allowedRoles: string[];
}

export function RolesGuard({ children, allowedRoles }: RolesGuardProps) {
  const { data: session, status } = useSession();

  if (status === "loading") {
    return <div>Checking permissions...</div>;
  }

  if (!session || !session.user?.role || !allowedRoles.includes(session.user.role)) {
    return <div>Access denied. Required permissions: {allowedRoles.join(', ')}</div>;
  }

  return <>{children}</>;
}

Application security

When implementing authentication, keep in mind several key security aspects:

  1. Secure password storage - always use hashing functions like bcrypt, never store passwords in plain text
  2. HTTPS - all authentication requests should use HTTPS
  3. CSRF (Cross-Site Request Forgery) - Auth.js automatically protects against CSRF attacks
  4. Login attempt limits - implement limits on the number of failed login attempts
  5. Secure tokens - ensure JWT tokens are properly signed and have a reasonable validity period
  6. Secure environment variables - store secret keys and passwords in environment variables

Example implementation of login attempt limits

import { NextRequest, NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';

// Simple in-memory implementation (in production you would use Redis or another store)
const loginAttempts = new Map<string, { count: number, lastAttempt: number }>();

export async function middleware(request: NextRequest) {
  if (request.nextUrl.pathname === '/api/auth/callback/credentials') {
    const ip = request.ip || 'unknown';
    const currentAttempts = loginAttempts.get(ip) || { count: 0, lastAttempt: Date.now() };

    // Reset the counter after 30 minutes
    if (Date.now() - currentAttempts.lastAttempt > 30 * 60 * 1000) {
      currentAttempts.count = 0;
    }

    // If the attempt limit has been exceeded
    if (currentAttempts.count >= 5) {
      return new NextResponse(
        JSON.stringify({ error: 'Too many login attempts. Try again in 30 minutes.' }),
        { status: 429 }
      );
    }

    // Update the counter
    loginAttempts.set(ip, {
      count: currentAttempts.count + 1,
      lastAttempt: Date.now()
    });
  }

  return NextResponse.next();
}

Summary

Authentication and authorization are key elements of every web application. Next.js together with Auth.js offers powerful tools for implementing secure authentication systems, from simple solutions to complex systems with roles and permissions.

When choosing an authentication solution for your Next.js application, it's worth considering:

  1. Project requirements - what login methods are needed?
  2. Target users - do they prefer social or traditional login?
  3. Application scale - is a complex role and permission system needed?
  4. Security - what security measures are necessary for your application?

A proper approach to authentication and authorization not only protects your application but also improves the user experience, building trust in your product.

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

// Demo: Overview of Auth and Authorization methods in Next.js
interface AuthMethod {
  id: string; name: string; icon: string; category: 'authentication' | 'authorization';
  pros: string[]; cons: string[]; useCase: string; difficulty: string;
  code: string;
}

const methods: AuthMethod[] = [
  { id: 'session', name: 'Session Auth', icon: '[S]', category: 'authentication',
    pros: ['Easy implementation', 'Can be revoked', 'Data on the server'],
    cons: ['Requires storage', 'Scaling', 'CSRF'],
    useCase: 'Traditional web applications',
    difficulty: 'easy',
    code: 'const session = await getServerSession(authOptions);\nif (!session) redirect("/login");' },
  { id: 'jwt', name: 'JWT Tokens', icon: '[J]', category: 'authentication',
    pros: ['Stateless', 'Scalable', 'Cross-domain'],
    cons: ['Cannot be revoked', 'Size', 'Storage in the browser'],
    useCase: 'API, microservices, SPA',
    difficulty: 'medium',
    code: 'const token = req.headers.authorization?.split(" ")[1];\nconst decoded = jwt.verify(token, SECRET);' },
  { id: 'oauth', name: 'OAuth 2.0', icon: '[O]', category: 'authentication',
    pros: ['No passwords in the database', 'Fast login', 'Trusted providers'],
    cons: ['External dependency', 'Configuration', 'Privacy'],
    useCase: 'Login via Google, GitHub',
    difficulty: 'medium',
    code: 'providers: [\n  GoogleProvider({ clientId, clientSecret }),\n]' },
  { id: 'rbac', name: 'RBAC', icon: '[R]', category: 'authorization',
    pros: ['Clear model', 'Easy management', 'Auditability'],
    cons: ['Can be too simple', 'Role explosion'],
    useCase: 'Applications with user types',
    difficulty: 'easy',
    code: 'if (session.user.role !== "admin")\n  return redirect("/unauthorized");' },
  { id: 'middleware', name: 'Middleware', icon: '[M]', category: 'authorization',
    pros: ['Centralized', 'Edge Runtime', 'Before rendering'],
    cons: ['Limited API', 'No database access'],
    useCase: 'Route protection, redirects',
    difficulty: 'easy',
    code: 'export function middleware(req: NextRequest) {\n  const token = req.cookies.get("token");\n  if (!token) return NextResponse.redirect("/login");\n}' },
];

const diffColors: Record<string, string> = { easy: '#10b981', medium: '#f59e0b', hard: '#ef4444' };

function AuthOverview() {
  const [filter, setFilter] = useState<'all' | 'authentication' | 'authorization'>('all');
  const [selected, setSelected] = useState<AuthMethod | null>(null);

  const filtered = methods.filter(m => filter === 'all' || m.category === filter);

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
      <h1 style={{ color: '#64ffda', marginBottom: '8px' }}>Auth & Authorization - Overview</h1>
      <p style={{ color: '#8892b0', marginBottom: '20px' }}>Comparison of authentication and authorization methods</p>

      <div style={{ display: 'flex', gap: '8px', marginBottom: '20px' }}>
        {(['all', 'authentication', 'authorization'] as const).map(f => (
          <button key={f} onClick={() => setFilter(f)} style={{ padding: '8px 16px', borderRadius: '8px', border: 'none', cursor: 'pointer', background: filter === f ? '#64ffda' : '#1a1a2e', color: filter === f ? '#0f0f23' : '#8892b0', fontWeight: 'bold' }}>
            {f === 'all' ? 'All' : f}
          </button>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(250px, 1fr))', gap: '16px', marginBottom: '24px' }}>
        {filtered.map(m => (
          <div key={m.id} onClick={() => setSelected(m)} style={{
            padding: '16px', borderRadius: '12px', cursor: 'pointer',
            background: selected?.id === m.id ? '#1a2a3e' : '#1a1a2e',
            border: selected?.id === m.id ? '1px solid #64ffda' : '1px solid #333',
          }}>
            <div style={{ fontSize: '20px', marginBottom: '8px' }}>{m.icon}</div>
            <h3 style={{ color: '#64ffda', margin: '0 0 4px', fontSize: '16px' }}>{m.name}</h3>
            <div style={{ display: 'flex', gap: '8px', marginBottom: '8px' }}>
              <span style={{ fontSize: '11px', padding: '2px 6px', borderRadius: '4px', background: '#333', color: '#8892b0' }}>{m.category}</span>
              <span style={{ fontSize: '11px', padding: '2px 6px', borderRadius: '4px', background: diffColors[m.difficulty] + '30', color: diffColors[m.difficulty] }}>{m.difficulty}</span>
            </div>
            <p style={{ fontSize: '13px', color: '#8892b0', margin: 0 }}>{m.useCase}</p>
          </div>
        ))}
      </div>

      {selected && (
        <div style={{ background: '#1a1a2e', padding: '20px', borderRadius: '12px', border: '1px solid #333' }}>
          <h3 style={{ color: '#64ffda', marginTop: 0 }}>{selected.icon} {selected.name}</h3>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '16px' }}>
            <div>
              <h4 style={{ color: '#10b981', fontSize: '14px' }}>Advantages:</h4>
              <ul style={{ fontSize: '13px', color: '#8892b0', paddingLeft: '20px', margin: 0 }}>{selected.pros.map((p, i) => <li key={i}>{p}</li>)}</ul>
            </div>
            <div>
              <h4 style={{ color: '#ef4444', fontSize: '14px' }}>Cons:</h4>
              <ul style={{ fontSize: '13px', color: '#8892b0', paddingLeft: '20px', margin: 0 }}>{selected.cons.map((c, i) => <li key={i}>{c}</li>)}</ul>
            </div>
          </div>
          <pre style={{ background: '#0f0f23', padding: '12px', borderRadius: '6px', fontSize: '12px', color: '#64ffda', overflow: 'auto' }}>{selected.code}</pre>
        </div>
      )}
    </div>
  );
}

export default AuthOverview;

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. Which of the authentication methods you learned is stateless and does not require storing sessions on the server?

  2. 2. Which mechanism lets you protect routes before the page is rendered?

Hands-on tasks in the game

  • Vertical ordering

    Arrange the stages of implementing authentication and authorization in a Next.js application:

  1. QuestionStateless Method
  2. Put in orderStages of Adding Authentication to an Application
  3. QuestionRoute Protection Before Rendering
  4. Project to submitAuthentication System Project
  5. VideoSummary: Authentication and Authorization in Next.js

Useful articles