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

Context Provider for authentication

24 min read ยท
In this lesson12

In previous modules, we learned the basics of authentication, connecting external providers, session management, the role and permission system, and middleware for route protection. Now we will deal with creating a Context Provider for authentication that will facilitate access to authentication data and functions throughout the React application.

React's Context API allows passing data through the component tree without the need to pass props at every level. This is an ideal solution for functionality that is needed in many places of the application - exactly like authentication.

Why is it worth creating your own Context Provider for authentication?

NextAuth.js already provides SessionProvider, which provides basic session information. However, it is often worth extending this functionality with additional capabilities:

  1. Centralization of authentication logic - all functions related to authentication in one place
  2. Additional methods - e.g. checking permissions, handling registration, password reset
  3. Loading state - easier management of session loading state
  4. Error handling - consistent authentication error management
  5. Typing contract - a clearly defined interface for TypeScript

Implementing AuthContext and AuthProvider

Let's start by defining the basic authentication context:

// lib/authContext.tsx
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { Session } from 'next-auth';
import { useSession, signIn, signOut } from 'next-auth/react';

// Defining the type for the authentication context
type AuthContextType = {
  session: Session | null;
  status: 'loading' | 'authenticated' | 'unauthenticated';
  isLoading: boolean;
  isAuthenticated: boolean;
  user: Session['user'] | null;
  hasRoles: (role: string | string[]) => boolean;
  hasPermission: (permission: string | string[]) => boolean;
  signIn: (provider?: string, options?: any) => Promise<any>;
  signOut: (options?: any) => Promise<any>;
  error: string | null;
};

// Creating context with default value (null)
const AuthContext = createContext<AuthContextType | null>(null);

// Hook that allows easy access to the context
export function useAuth() {
  const context = useContext(AuthContext);

  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }

  return context;
}

// Provider component
interface AuthProviderProps {
  children: ReactNode;
}

export function AuthProvider({ children }: AuthProviderProps) {
  // We use useSession from NextAuth.js to fetch session data
  const { data: session, status } = useSession();
  const [error, setError] = useState<string | null>(null);

  // Check if the user has a specific role
  const hasRoles = (role: string | string[]): boolean => {
    if (!session?.user?.role) return false;

    if (Array.isArray(role)) {
      return role.includes(session.user.role as string);
    }

    return session.user.role === role;
  };

  // Check if the user has a specific permission
  const hasPermission = (permission: string | string[]): boolean => {
    if (!session?.user?.permissions) return false;

    const userPermissions = session.user.permissions as string[];

    if (Array.isArray(permission)) {
      return permission.some(p => userPermissions.includes(p));
    }

    return userPermissions.includes(permission as string);
  };

  // Simple function wrapping signIn with error handling
  const handleSignIn = async (provider?: string, options?: any) => {
    try {
      setError(null);
      return await signIn(provider, options);
    } catch (err) {
      console.error('Login error:', err);
      setError('A problem occurred during login. Please try again.');
      throw err;
    }
  };

  // Simple function wrapping signOut
  const handleSignOut = async (options?: any) => {
    try {
      return await signOut(options);
    } catch (err) {
      console.error('Logout error:', err);
      setError('A problem occurred during logout.');
      throw err;
    }
  };

  // Context value that will be shared
  const value: AuthContextType = {
    session,
    status,
    isLoading: status === 'loading',
    isAuthenticated: status === 'authenticated',
    user: session?.user || null,
    hasRoles,
    hasPermission,
    signIn: handleSignIn,
    signOut: handleSignOut,
    error,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
}

Integrating AuthProvider with the application

Authorization is an application-wide functionality, so it is best to add AuthProvider at a high level in the component tree, preferably in the main application layout, wrapping SessionProvider from NextAuth.js:

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

import { SessionProvider } from 'next-auth/react';
import { AuthProvider } from '@/lib/authContext';
import { ReactNode } from 'react';

export function Providers({ children }: { children: ReactNode }) {
  return (
    <SessionProvider>
      <AuthProvider>
        {children}
      </AuthProvider>
    </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>
  );
}

Creating PasswordResetProvider as an example of a specialized provider

We often also need specialized contexts for specific authentication functionalities, such as password reset. Here is an example of such a provider:

// lib/passwordResetContext.tsx
import { createContext, useContext, useState, ReactNode } from 'react';

type PasswordResetContextType = {
  isLoading: boolean;
  error: string | null;
  message: string | null;
  requestPasswordReset: (email: string) => Promise<boolean>;
  resetPassword: (token: string, newPassword: string) => Promise<boolean>;
};

const PasswordResetContext = createContext<PasswordResetContextType | null>(null);

export function usePasswordReset() {
  const context = useContext(PasswordResetContext);

  if (!context) {
    throw new Error('usePasswordReset must be used within a PasswordResetProvider');
  }

  return context;
}

interface PasswordResetProviderProps {
  children: ReactNode;
}

export function PasswordResetProvider({ children }: PasswordResetProviderProps) {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);

  // Function to send password reset request
  const requestPasswordReset = async (email: string): Promise<boolean> => {
    setIsLoading(true);
    setError(null);
    setMessage(null);

    try {
      const response = await fetch('/api/auth/reset-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || 'A problem occurred while sending the reset link');
      }

      setMessage('Password reset instructions have been sent to the provided email address.');
      return true;
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An unknown error occurred');
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  // Function to set a new password
  const resetPassword = async (token: string, newPassword: string): Promise<boolean> => {
    setIsLoading(true);
    setError(null);
    setMessage(null);

    try {
      const response = await fetch('/api/auth/reset-password/confirm', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token, newPassword }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || 'A problem occurred while resetting the password');
      }

      setMessage('Password has been successfully changed. You can now log in.');
      return true;
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An unknown error occurred');
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  const value: PasswordResetContextType = {
    isLoading,
    error,
    message,
    requestPasswordReset,
    resetPassword,
  };

  return (
    <PasswordResetContext.Provider value={value}>
      {children}
    </PasswordResetContext.Provider>
  );
}

Extending AuthProvider with additional features

We can extend our AuthProvider with additional features that will often be needed in applications:

1. User registration

// Extended methods in AuthContext
type AuthContextType = {
  // ... existing fields
  registerUser: (userData: RegisterUserData) => Promise<boolean>;
};

// Registration data
type RegisterUserData = {
  name: string;
  email: string;
  password: string;
};

// Implementation in AuthProvider
export function AuthProvider({ children }: AuthProviderProps) {
  // ... existing code

  const registerUser = async (userData: RegisterUserData): Promise<boolean> => {
    try {
      setError(null);
      const response = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(userData),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || 'A problem occurred during registration');
      }

      return true;
    } catch (err) {
      console.error('Registration error:', err);
      setError(err instanceof Error ? err.message : 'An unknown error occurred during registration');
      return false;
    }
  };

  const value: AuthContextType = {
    // ... existing fields
    registerUser,
  };

  // ... existing code
}

2. User profile update

// Extended methods in AuthContext
type AuthContextType = {
  // ... existing fields
  updateUserProfile: (profileData: UpdateProfileData) => Promise<boolean>;
};

// Profile update data
type UpdateProfileData = {
  name?: string;
  email?: string;
  currentPassword?: string;
  newPassword?: string;
  image?: string;
};

// Implementation in AuthProvider
export function AuthProvider({ children }: AuthProviderProps) {
  // ... existing code

  const updateUserProfile = async (profileData: UpdateProfileData): Promise<boolean> => {
    try {
      setError(null);
      const response = await fetch('/api/user/profile', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(profileData),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || 'A problem occurred while updating the profile');
      }

      // Force session refresh to fetch updated data
      await refreshSession();

      return true;
    } catch (err) {
      console.error('Profile update error:', err);
      setError(err instanceof Error ? err.message : 'An unknown error occurred during profile update');
      return false;
    }
  };

  // Function that refreshes the session
  const refreshSession = async () => {
    // Currently in Next.js 13+ with App Router we can use:
    const event = new Event('visibilitychange');
    document.dispatchEvent(event);

    // Alternatively, we can implement session refresh ourselves
    // e.g. by re-rendering the provider
  };

  const value: AuthContextType = {
    // ... existing fields
    updateUserProfile,
  };

  // ... existing code
}

3. Handling two-factor authentication (2FA)

// Extended methods in AuthContext
type AuthContextType = {
  // ... existing fields
  enable2FA: () => Promise<{ secret: string; qrCodeUrl: string }>;
  verify2FA: (token: string) => Promise<boolean>;
  disable2FA: (token: string) => Promise<boolean>;
  is2FAEnabled: boolean;
};

// Implementation in AuthProvider
export function AuthProvider({ children }: AuthProviderProps) {
  // ... existing code
  const [is2FAEnabled, setIs2FAEnabled] = useState(false);

  // Update the 2FA state based on the session
  useEffect(() => {
    if (session?.user?.twoFactorEnabled) {
      setIs2FAEnabled(true);
    } else {
      setIs2FAEnabled(false);
    }
  }, [session]);

  // Enable 2FA
  const enable2FA = async () => {
    try {
      setError(null);
      const response = await fetch('/api/auth/2fa/enable', {
        method: 'POST',
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.message || 'A problem occurred while enabling 2FA');
      }

      const { secret, qrCodeUrl } = await response.json();
      return { secret, qrCodeUrl };
    } catch (err) {
      console.error('Enable 2FA error:', err);
      setError(err instanceof Error ? err.message : 'An unknown error occurred');
      throw err;
    }
  };

  // Verify the 2FA token
  const verify2FA = async (token: string) => {
    try {
      setError(null);
      const response = await fetch('/api/auth/2fa/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token }),
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.message || 'Invalid verification code');
      }

      // Refresh the session to update the 2FA state
      await refreshSession();
      setIs2FAEnabled(true);

      return true;
    } catch (err) {
      console.error('Verify 2FA error:', err);
      setError(err instanceof Error ? err.message : 'An unknown error occurred');
      return false;
    }
  };

  // Disable 2FA
  const disable2FA = async (token: string) => {
    try {
      setError(null);
      const response = await fetch('/api/auth/2fa/disable', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token }),
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.message || 'Invalid verification code');
      }

      // Refresh the session to update the 2FA state
      await refreshSession();
      setIs2FAEnabled(false);

      return true;
    } catch (err) {
      console.error('Disable 2FA error:', err);
      setError(err instanceof Error ? err.message : 'An unknown error occurred');
      return false;
    }
  };

  const value: AuthContextType = {
    // ... existing fields
    enable2FA,
    verify2FA,
    disable2FA,
    is2FAEnabled,
  };

  // ... existing code
}

Using AuthContext in components

Now we can use our AuthContext in application components:

1. Login/logout button component

// components/AuthButton.tsx
'use client';

import { useAuth } from '@/lib/authContext';

export function AuthButton() {
  const { isAuthenticated, isLoading, signIn, signOut, user } = useAuth();

  if (isLoading) {
    return <button className="btn btn-ghost animate-pulse">Loading...</button>;
  }

  if (isAuthenticated) {
    return (
      <button
        onClick={() => signOut({ callbackUrl: '/' })}
        className="btn btn-outline"
      >
        Log out {user?.name}
      </button>
    );
  }

  return (
    <button
      onClick={() => signIn()}
      className="btn btn-primary"
    >
      Log in
    </button>
  );
}

2. Protected page component

// app/dashboard/page.tsx
'use client';

import { useAuth } from '@/lib/authContext';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';

export default function DashboardPage() {
  const { isAuthenticated, isLoading, user, hasRoles } = useAuth();
  const router = useRouter();

  // Redirect to the login page if the user is not logged in
  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      router.push('/auth/login?callbackUrl=/dashboard');
    }
  }, [isLoading, isAuthenticated, router]);

  if (isLoading) {
    return <div className="flex justify-center p-8">Loading...</div>;
  }

  if (!isAuthenticated) {
    return null; // Avoid flicker before redirecting
  }

  return (
    <div className="container mx-auto p-6">
      <h1 className="text-2xl font-bold mb-6">Hello, {user?.name}!</h1>

      <div className="bg-white shadow rounded-lg p-6">
        <h2 className="text-xl font-semibold mb-4">Dashboard</h2>

        {/* Content available to all logged-in users */}
        <div className="mb-6">
          <h3 className="text-lg font-medium mb-2">Your profile</h3>
          <p>Email: {user?.email}</p>
          <p>Role: {user?.role}</p>
        </div>

        {/* Content visible only to administrators */}
        {hasRoles('admin') && (
          <div className="p-4 bg-purple-50 rounded-lg">
            <h3 className="text-lg font-medium mb-2 text-purple-800">Admin panel</h3>
            <p className="text-purple-700">This section is visible only to administrators.</p>
            <button className="mt-2 px-4 py-2 bg-purple-600 text-white rounded">Manage users</button>
          </div>
        )}

        {/* Content visible only to specific roles */}
        {hasRoles(['admin', 'editor']) && (
          <div className="mt-4 p-4 bg-blue-50 rounded-lg">
            <h3 className="text-lg font-medium mb-2 text-blue-800">Content management</h3>
            <p className="text-blue-700">This section is available to administrators and editors.</p>
          </div>
        )}
      </div>
    </div>
  );
}

3. Registration form with validation

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

import { useAuth } from '@/lib/authContext';
import { useState, FormEvent } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

export default function RegisterPage() {
  const { registerUser, error: authError, isAuthenticated } = useAuth();
  const router = useRouter();

  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);

  // If the user is already logged in, redirect to the dashboard
  if (isAuthenticated) {
    router.push('/dashboard');
    return null;
  }

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setFormError(null);
    setSuccessMessage(null);

    // Validate form
    if (password !== confirmPassword) {
      setFormError('Passwords do not match');
      return;
    }

    if (password.length < 8) {
      setFormError('Password must be at least 8 characters');
      return;
    }

    setIsLoading(true);

    try {
      const success = await registerUser({ name, email, password });

      if (success) {
        setSuccessMessage('Registration completed successfully! You can now log in.');
        // Optionally: redirect to the login page after a short delay
        setTimeout(() => {
          router.push('/auth/login');
        }, 2000);
      }
    } catch (err) {
      console.error('Registration error:', err);
      // Error is already handled by AuthProvider
    } finally {
      setIsLoading(false);
    }
  };

  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">Registration</h1>

      {/* Display errors */}
      {(formError || authError) && (
        <div className="mb-4 p-3 bg-red-100 text-red-700 rounded-md">
          {formError || authError}
        </div>
      )}

      {/* Display success message */}
      {successMessage && (
        <div className="mb-4 p-3 bg-green-100 text-green-700 rounded-md">
          {successMessage}
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label htmlFor="name" className="block text-sm font-medium mb-1">
            Full name
          </label>
          <input
            id="name"
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            required
          />
        </div>

        <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)}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            required
          />
        </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)}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            required
            minLength={8}
          />
        </div>

        <div>
          <label htmlFor="confirmPassword" className="block text-sm font-medium mb-1">
            Confirm password
          </label>
          <input
            id="confirmPassword"
            type="password"
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            required
          />
        </div>

        <button
          type="submit"
          disabled={isLoading}
          className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50"
        >
          {isLoading ? 'Processing...' : 'Sign up'}
        </button>
      </form>

      <div className="mt-6 text-center">
        <p className="text-sm text-gray-600">
          Already have an account?{' '}
          <Link href="/auth/login" className="text-blue-600 hover:underline">
            Log in
          </Link>
        </p>
      </div>
    </div>
  );
}

4. Password reset form

// app/auth/reset-password/page.tsx
'use client';

import { useState, FormEvent } from 'react';
import { usePasswordReset } from '@/lib/passwordResetContext';
import Link from 'next/link';

export default function PasswordResetPage() {
  const [email, setEmail] = useState('');
  const { requestPasswordReset, isLoading, error, message } = usePasswordReset();

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    await requestPasswordReset(email);
  };

  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">Password reset</h1>

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

      {message && (
        <div className="mb-4 p-3 bg-green-100 text-green-700 rounded-md">
          {message}
        </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)}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            required
            disabled={isLoading || !!message} // Block after successful send
          />
        </div>

        <button
          type="submit"
          disabled={isLoading || !!message}
          className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50"
        >
          {isLoading ? 'Sending...' : 'Reset password'}
        </button>
      </form>

      <div className="mt-6 text-center">
        <p className="text-sm text-gray-600">
          <Link href="/auth/login" className="text-blue-600 hover:underline">
            Back to login page
          </Link>
        </p>
      </div>
    </div>
  );
}

Creating higher-order components (HOC) to protect pages

We can also create higher-order components (HOCs) that will protect access to pages based on authentication state:

// components/withAuth.tsx
'use client';

import { useAuth } from '@/lib/authContext';
import { useRouter } from 'next/navigation';
import { useEffect, ComponentType } from 'react';

// HOC that requires authentication
export function withAuth<P extends object>(Component: ComponentType<P>) {
  return function AuthProtected(props: P) {
    const { isAuthenticated, isLoading } = useAuth();
    const router = useRouter();

    useEffect(() => {
      if (!isLoading && !isAuthenticated) {
        router.push(`/auth/login?callbackUrl=${encodeURIComponent(window.location.pathname)}`);
      }
    }, [isLoading, isAuthenticated, router]);

    if (isLoading) {
      return <div className="flex justify-center p-8">Loading...</div>;
    }

    if (!isAuthenticated) {
      return null; // Avoid flicker before redirecting
    }

    return <Component {...props} />;
  };
}

// HOC requiring a specific role
export function withRoles<P extends object>(Component: ComponentType<P>, requiredRoles: string | string[]) {
  return function RolesProtected(props: P) {
    const { isAuthenticated, isLoading, hasRoles, user } = useAuth();
    const router = useRouter();

    useEffect(() => {
      if (!isLoading) {
        if (!isAuthenticated) {
          router.push(`/auth/login?callbackUrl=${encodeURIComponent(window.location.pathname)}`);
        } else if (!hasRoles(requiredRoles)) {
          router.push('/auth/unauthorized');
        }
      }
    }, [isLoading, isAuthenticated, hasRoles, router]);

    if (isLoading) {
      return <div className="flex justify-center p-8">Loading...</div>;
    }

    if (!isAuthenticated || !hasRoles(requiredRoles)) {
      return null; // Avoid flicker before redirecting
    }

    return <Component {...props} />;
  };
}

// HOC requiring specific permissions
export function withPermission<P extends object>(Component: ComponentType<P>, requiredPermission: string | string[]) {
  return function PermissionProtected(props: P) {
    const { isAuthenticated, isLoading, hasPermission } = useAuth();
    const router = useRouter();

    useEffect(() => {
      if (!isLoading) {
        if (!isAuthenticated) {
          router.push(`/auth/login?callbackUrl=${encodeURIComponent(window.location.pathname)}`);
        } else if (!hasPermission(requiredPermission)) {
          router.push('/auth/unauthorized');
        }
      }
    }, [isLoading, isAuthenticated, hasPermission, router]);

    if (isLoading) {
      return <div className="flex justify-center p-8">Loading...</div>;
    }

    if (!isAuthenticated || !hasPermission(requiredPermission)) {
      return null; // Avoid flicker before redirecting
    }

    return <Component {...props} />;
  };
}

Example HOC usage:

// app/admin/settings/page.tsx
'use client';

import { withRoles } from '@/components/withAuth';

function AdminSettingsPage() {
  return (
    <div className="container mx-auto p-6">
      <h1 className="text-2xl font-bold mb-6">Administrator settings</h1>
      {/* Page content */}
    </div>
  );
}

// Export the component protected by the HOC
export default withRoles(AdminSettingsPage, 'admin');

// app/content/edit/page.tsx
'use client';

import { withPermission } from '@/components/withAuth';

function EditContentPage() {
  return (
    <div className="container mx-auto p-6">
      <h1 className="text-2xl font-bold mb-6">Content editing</h1>
      {/* Page content */}
    </div>
  );
}

// Export the component protected by the HOC
export default withPermission(EditContentPage, 'content:edit');

Integration with application state management system

Our AuthContext can also be integrated with a more complex application state management system such as Redux, Zustand, or Jotai. For example, integration with Zustand could look like this:

// lib/authStore.ts
import { create } from 'zustand';
import { Session } from 'next-auth';

type AuthState = {
  session: Session | null;
  status: 'loading' | 'authenticated' | 'unauthenticated';
  error: string | null;
  user: Session['user'] | null;
  setSession: (session: Session | null) => void;
  setStatus: (status: 'loading' | 'authenticated' | 'unauthenticated') => void;
  setError: (error: string | null) => void;
  hasRoles: (role: string | string[]) => boolean;
  hasPermission: (permission: string | string[]) => boolean;
  reset: () => void;
};

export const useAuthStore = create<AuthState>((set, get) => ({
  session: null,
  status: 'loading',
  error: null,
  user: null,

  setSession: (session) => set({
    session,
    user: session?.user || null,
    status: session ? 'authenticated' : 'unauthenticated'
  }),

  setStatus: (status) => set({ status }),

  setError: (error) => set({ error }),

  hasRoles: (role) => {
    const { user } = get();
    if (!user?.role) return false;

    if (Array.isArray(role)) {
      return role.includes(user.role as string);
    }

    return user.role === role;
  },

  hasPermission: (permission) => {
    const { user } = get();
    if (!user?.permissions) return false;

    const userPermissions = user.permissions as string[];

    if (Array.isArray(permission)) {
      return permission.some(p => userPermissions.includes(p));
    }

    return userPermissions.includes(permission as string);
  },

  reset: () => set({
    session: null,
    status: 'unauthenticated',
    error: null,
    user: null
  }),
}));

// Modified AuthProvider using Zustand
export function AuthProvider({ children }: { children: ReactNode }) {
  const { data: session, status } = useSession();
  const { setSession, setStatus, setError } = useAuthStore();

  // Update the store when the session changes
  useEffect(() => {
    setSession(session);
    setStatus(status);
  }, [session, status, setSession, setStatus]);

  return <>{children}</>;
}

Testing AuthContext

Testing Auth Context is key to ensuring the reliability of the authentication system. Below is an example of tests using React Testing Library and Jest:

// __tests__/authContext.test.tsx
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { AuthProvider, useAuth } from '@/lib/authContext';
import { SessionProvider } from 'next-auth/react';

// Mock next-auth
jest.mock('next-auth/react', () => ({
  useSession: jest.fn(),
  signIn: jest.fn(),
  signOut: jest.fn(),
}));

// Test component using useAuth
function TestComponent() {
  const { isAuthenticated, user, hasRoles, hasPermission } = useAuth();

  return (
    <div>
      <div data-testid="auth-status">
        {isAuthenticated ? 'Authenticated' : 'Not authenticated'}
      </div>
      {user && <div data-testid="user-name">{user.name}</div>}
      <div data-testid="admin-role">
        {hasRoles('admin') ? 'Has admin role' : 'No admin role'}
      </div>
      <div data-testid="edit-permission">
        {hasPermission('content:edit') ? 'Can edit content' : 'Cannot edit content'}
      </div>
    </div>
  );
}

// Wrapper for tests
function renderWithAuth(ui: React.ReactNode, sessionData: any = null) {
  const useSessionMock = require('next-auth/react').useSession;

  // Set up the mock for useSession
  useSessionMock.mockReturnValue(sessionData);

  return render(
    <SessionProvider>
      <AuthProvider>{ui}</AuthProvider>
    </SessionProvider>
  );
}

describe('AuthContext', () => {
  it('should show unauthenticated state when no session exists', () => {
    renderWithAuth(<TestComponent />, {
      data: null,
      status: 'unauthenticated'
    });

    expect(screen.getByTestId('auth-status')).toHaveTextContent('Not authenticated');
    expect(screen.getByTestId('admin-role')).toHaveTextContent('No admin role');
    expect(screen.getByTestId('edit-permission')).toHaveTextContent('Cannot edit content');
  });

  it('should show authenticated state with user data when session exists', () => {
    renderWithAuth(<TestComponent />, {
      data: {
        user: {
          name: 'Test User',
          email: 'test@example.com',
          role: 'user',
          permissions: ['content:read']
        }
      },
      status: 'authenticated'
    });

    expect(screen.getByTestId('auth-status')).toHaveTextContent('Authenticated');
    expect(screen.getByTestId('user-name')).toHaveTextContent('Test User');
    expect(screen.getByTestId('admin-role')).toHaveTextContent('No admin role');
    expect(screen.getByTestId('edit-permission')).toHaveTextContent('Cannot edit content');
  });

  it('should correctly check for admin role', () => {
    renderWithAuth(<TestComponent />, {
      data: {
        user: {
          name: 'Admin User',
          email: 'admin@example.com',
          role: 'admin',
          permissions: ['content:read', 'content:edit', 'user:manage']
        }
      },
      status: 'authenticated'
    });

    expect(screen.getByTestId('auth-status')).toHaveTextContent('Authenticated');
    expect(screen.getByTestId('admin-role')).toHaveTextContent('Has admin role');
    expect(screen.getByTestId('edit-permission')).toHaveTextContent('Can edit content');
  });

  it('should correctly check for permissions', () => {
    renderWithAuth(<TestComponent />, {
      data: {
        user: {
          name: 'Editor User',
          email: 'editor@example.com',
          role: 'editor',
          permissions: ['content:read', 'content:edit']
        }
      },
      status: 'authenticated'
    });

    expect(screen.getByTestId('auth-status')).toHaveTextContent('Authenticated');
    expect(screen.getByTestId('admin-role')).toHaveTextContent('No admin role');
    expect(screen.getByTestId('edit-permission')).toHaveTextContent('Can edit content');
  });
});

Advanced AuthContext use cases

1. Inactivity detection and automatic logout

// lib/useIdleTimer.ts
import { useState, useEffect, useCallback } from 'react';

type UseIdleTimerProps = {
  timeout: number; // Time in milliseconds
  onIdle: () => void;
  onActive?: () => void;
  events?: string[];
};

export function useIdleTimer({
  timeout,
  onIdle,
  onActive,
  events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart']
}: UseIdleTimerProps) {
  const [isIdle, setIsIdle] = useState(false);
  const [lastActive, setLastActive] = useState(Date.now());
  const [timeoutId, setTimeoutId] = useState<NodeJS.Timeout | null>(null);

  // Reset the inactivity timer
  const resetTimer = useCallback(() => {
    if (isIdle) {
      setIsIdle(false);
      onActive?.();
    }

    setLastActive(Date.now());

    if (timeoutId) {
      clearTimeout(timeoutId);
    }

    const id = setTimeout(() => {
      setIsIdle(true);
      onIdle();
    }, timeout);

    setTimeoutId(id);
  }, [isIdle, onActive, onIdle, timeout, timeoutId]);

  // Initialize the timer on mount
  useEffect(() => {
    resetTimer();

    // Add event listeners
    events.forEach(event => {
      window.addEventListener(event, resetTimer);
    });

    // Clean up on unmount
    return () => {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }

      events.forEach(event => {
        window.removeEventListener(event, resetTimer);
      });
    };
  }, [events, resetTimer, timeoutId]);

  return {
    isIdle,
    lastActive,
    resetTimer
  };
}

// Extending AuthProvider with automatic logout support
export function AuthProvider({ children }: AuthProviderProps) {
  // ... existing code

  // Idle time: 30 minutes
  const idleTimeout = 30 * 60 * 1000;
  const [showIdleWarning, setShowIdleWarning] = useState(false);

  // Handling logout after inactivity period
  const handleIdle = () => {
    // Show warning about impending logout
    setShowIdleWarning(true);

    // Give the user 1 minute to react before being logged out
    setTimeout(() => {
      if (showIdleWarning) {
        handleSignOut({ callbackUrl: '/' });
      }
    }, 60 * 1000);
  };

  // Handling return to activity
  const handleActive = () => {
    setShowIdleWarning(false);
  };

  // Use the idle timer hook
  useIdleTimer({
    timeout: idleTimeout,
    onIdle: handleIdle,
    onActive: handleActive
  });

  // ... existing code

  // Add inactivity warning modal
  return (
    <AuthContext.Provider value={value}>
      {children}

      {/* Inactivity warning modal */}
      {showIdleWarning && (
        <div className="fixed inset-0 flex items-center justify-center bg-black/50 z-50">
          <div className="bg-white p-6 rounded-lg shadow-lg max-w-md">
            <h2 className="text-xl font-bold mb-4">Inactivity detected</h2>
            <p className="mb-4">You will be automatically logged out in 1 minute due to inactivity.</p>
            <div className="flex justify-end space-x-4">
              <button
                onClick={() => handleSignOut({ callbackUrl: '/' })}
                className="px-4 py-2 bg-gray-300 rounded hover:bg-gray-400"
              >
                Log out now
              </button>
              <button
                onClick={handleActive}
                className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
              >
                Stay logged in
              </button>
            </div>
          </div>
        </div>
      )}
    </AuthContext.Provider>
  );
}

2. Implementing access delegation mechanism (token swapping)

// lib/delegatedAuth.ts
import { useAuth } from './authContext';
import { useState } from 'react';

type DelegatedToken = {
  token: string;
  expiresAt: number;
  service: string;
};

export function useDelegatedAuth() {
  const { isAuthenticated } = useAuth();
  const [delegatedTokens, setDelegatedTokens] = useState<Record<string, DelegatedToken>>({});
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Acquire a token for the external service
  const getDelegatedToken = async (service: string): Promise<string | null> => {
    // If the user is not logged in, a token cannot be acquired
    if (!isAuthenticated) {
      setError('You must be logged in to access the external service');
      return null;
    }

    // Check if we have a valid token in the cache
    const cachedToken = delegatedTokens[service];
    if (cachedToken && cachedToken.expiresAt > Date.now()) {
      return cachedToken.token;
    }

    // Acquire a new token
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch(`/api/auth/delegate/${service}`, {
        method: 'POST',
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.message || 'Error acquiring access token');
      }

      const { token, expiresIn } = await response.json();
      const expiresAt = Date.now() + expiresIn * 1000;

      // Cache the token
      const newToken = { token, expiresAt, service };
      setDelegatedTokens(prev => ({ ...prev, [service]: newToken }));

      return token;
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An unknown error occurred');
      return null;
    } finally {
      setIsLoading(false);
    }
  };

  // Clear all delegated tokens
  const clearDelegatedTokens = () => {
    setDelegatedTokens({});
  };

  return {
    getDelegatedToken,
    clearDelegatedTokens,
    isLoading,
    error,
  };
}

// Example usage in a component
// components/ExternalServiceWidget.tsx
'use client';

import { useDelegatedAuth } from '@/lib/delegatedAuth';
import { useState, useEffect } from 'react';

export function ExternalServiceWidget() {
  const { getDelegatedToken, isLoading, error } = useDelegatedAuth();
  const [data, setData] = useState(null);

  const fetchData = async () => {
    // Acquire a token for the external service
    const token = await getDelegatedToken('external-api');

    if (!token) return;

    try {
      // Use the token to call the external service's API
      const response = await fetch('https://api.external-service.com/data', {
        headers: {
          Authorization: `Bearer ${token}`
        }
      });

      const result = await response.json();
      setData(result);
    } catch (err) {
      console.error('Error fetching from external service:', err);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div className="bg-white p-4 rounded shadow">
      <h2 className="text-lg font-bold mb-2">Data from the external service</h2>

      {isLoading && <p>Loading data...</p>}
      {error && <p className="text-red-600">{error}</p>}

      {data && (
        <div className="mt-2">
          {/* Display data */}
        </div>
      )}

      <button
        onClick={fetchData}
        disabled={isLoading}
        className="mt-4 px-4 py-2 bg-blue-600 text-white rounded disabled:opacity-50"
      >
        Refresh data
      </button>
    </div>
  );
}

Authentication context security

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

  1. Do not store sensitive data in state - avoid storing passwords, full JWT tokens, or API keys in a client-accessible context.

  2. Validate data on the server side - always verify user permissions on the server, never rely solely on client-side validation.

  3. Use HTTPS - all authentication-related requests must be transmitted over HTTPS.

  4. Handle tokens securely - store tokens in httpOnly cookies, not localStorage or sessionStorage.

  5. Implement CSRF protection - use CSRF tokens to protect against Cross-Site Request Forgery attacks.

  6. Avoid information leaks - do not reveal detailed authentication error information that could help attackers.

  7. Regularly refresh and rotate tokens - implement token refresh and rotation mechanisms.

Summary

In this module, we discussed the design and implementation of a Context Provider for authentication in Next.js applications, specifically:

  1. Creating AuthContext and AuthProvider - centralizing authentication logic in one place
  2. Integration with NextAuth.js - using existing authentication mechanisms
  3. Extending with additional features - registration, profile management, 2FA
  4. Specialized providers - handling specific use cases like password reset
  5. Higher-order components (HOC) - protecting pages based on roles and permissions
  6. Integration with state management systems - combining with Zustand and other libraries
  7. Testing - writing tests for AuthContext
  8. Advanced use cases - automatic logout and access delegation

A well-designed Context Provider for authentication significantly simplifies authentication state management across the entire application, centralizes logic, and provides a consistent interface for using security-related functions.

In the next module, we will look at application security aspects and OWASP best practices that will help us create more secure and attack-resistant Next.js applications.

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

// Demo: Context Provider for authentication
interface User { id: string; name: string; email: string; role: 'admin' | 'user'; }

interface AuthContextType {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  login: (email: string) => void;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

function useAuth(): AuthContextType {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error('useAuth must be used within AuthProvider');
  return ctx;
}

const mockUsers: Record<string, User> = {
  'admin@quantum.city': { id: '1', name: 'Admin', email: 'admin@quantum.city', role: 'admin' },
  'user@quantum.city': { id: '2', name: 'User', email: 'user@quantum.city', role: 'user' },
};

function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  const login = async (email: string) => {
    setIsLoading(true);
    await new Promise(r => setTimeout(r, 600));
    setUser(mockUsers[email] || null);
    setIsLoading(false);
  };

  return (
    <AuthContext.Provider value={{ user, isAuthenticated: !!user, isLoading, login, logout: () => setUser(null) }}>
      {children}
    </AuthContext.Provider>
  );
}

function Navbar() {
  const { user, isAuthenticated, logout } = useAuth();
  return (
    <nav style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 20px', background: '#1a1a2e', borderRadius: '8px', marginBottom: '20px' }}>
      <span style={{ color: '#64ffda', fontWeight: 'bold' }}>QuantumAuth</span>
      {isAuthenticated ? (
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <span>{user?.name} ({user?.role})</span>
          <button onClick={logout} style={{ padding: '6px 12px', borderRadius: '6px', background: '#ef4444', color: '#fff', border: 'none', cursor: 'pointer', fontSize: '12px' }}>Log out</button>
        </div>
      ) : <span style={{ color: '#8892b0' }}>Not logged in</span>}
    </nav>
  );
}

function LoginForm() {
  const { login, isLoading, isAuthenticated } = useAuth();
  const [email, setEmail] = useState('');
  if (isAuthenticated) return null;

  return (
    <div style={{ background: '#1a1a2e', padding: '24px', borderRadius: '12px', border: '1px solid #333', maxWidth: '400px', margin: '0 auto' }}>
      <h3 style={{ color: '#64ffda', marginTop: 0 }}>Login</h3>
      <input value={email} onChange={e => setEmail(e.target.value)} placeholder="Email" style={{ width: '100%', padding: '10px', borderRadius: '6px', background: '#0f0f23', color: '#fff', border: '1px solid #333', marginBottom: '12px', boxSizing: 'border-box' }} />
      <button onClick={() => login(email)} disabled={isLoading} style={{ width: '100%', padding: '10px', borderRadius: '6px', background: '#64ffda', color: '#0f0f23', border: 'none', cursor: 'pointer', fontWeight: 'bold' }}>
        {isLoading ? 'Logging in...' : 'Log in'}
      </button>
      <div style={{ marginTop: '12px', fontSize: '12px', color: '#8892b0' }}>
        {Object.keys(mockUsers).map(e => (
          <button key={e} onClick={() => { setEmail(e); login(e); }} style={{ display: 'block', background: 'none', border: 'none', color: '#64ffda', cursor: 'pointer', padding: '2px 0', fontSize: '12px' }}>{e}</button>
        ))}
      </div>
    </div>
  );
}

function ProtectedContent() {
  const { isAuthenticated, user } = useAuth();
  if (!isAuthenticated) return <p style={{ textAlign: 'center', color: '#555' }}>Log in</p>;
  return (
    <div style={{ background: '#1a1a2e', padding: '24px', borderRadius: '12px', border: '1px solid #10b981', marginTop: '20px' }}>
      <h3 style={{ color: '#10b981', marginTop: 0 }}>Protected content</h3>
      <p>Welcome, {user?.name}! Role: {user?.role}</p>
      {user?.role === 'admin' && (
        <div style={{ padding: '12px', background: '#ef444420', borderRadius: '8px', border: '1px solid #ef4444', marginTop: '12px' }}>
          <strong style={{ color: '#ef4444' }}>Admin Panel</strong>
          <p style={{ fontSize: '14px', margin: '4px 0 0' }}>Visible only to admins</p>
        </div>
      )}
    </div>
  );
}

function App() {
  return (
    <AuthProvider>
      <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
        <h1 style={{ color: '#64ffda', marginBottom: '20px' }}>Auth Context Provider</h1>
        <Navbar />
        <LoginForm />
        <ProtectedContent />
        <div style={{ marginTop: '24px', background: '#1a1a2e', padding: '16px', borderRadius: '8px', border: '1px solid #333' }}>
          <h4 style={{ color: '#f59e0b', margin: '0 0 8px' }}>Structure:</h4>
          <pre style={{ fontSize: '12px', color: '#8892b0', margin: 0 }}>{'<AuthProvider>\n  <Navbar />       // useAuth() -> user, logout\n  <LoginForm />    // useAuth() -> login\n  <Protected />    // useAuth() -> isAuthenticated\n</AuthProvider>'}</pre>
        </div>
      </div>
    </AuthProvider>
  );
}

export default App;

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. Why do you create a separate AuthProvider as a Client Component wrapping the application in Next.js?

  1. QuestionContext Provider for Authentication

Useful articles