Back to Resources

Next.js Authentication Flow

Complete authentication system with NextAuth.js, including social logins and role-based access control

Resource Information

Resource Type

Authentication System

Technology

Next.js, NextAuth.js, JWT

Last Updated

March 20, 2024

Overview

The Next.js Authentication Flow provides a complete, production-ready authentication system for your Next.js applications. Built on NextAuth.js, this solution offers a seamless authentication experience with support for multiple authentication methods including social logins, email/password, and more.

This resource includes everything you need to implement secure, scalable authentication in your Next.js projects, with role-based access control, protected routes, and user profile management. The system is designed to be flexible and customizable, allowing you to adapt it to your specific requirements.

Key Features

Multiple Auth Providers

Support for OAuth providers (Google, GitHub, Twitter, etc.), email/password authentication, and magic links, giving your users flexible login options.

JWT Authentication

Secure JSON Web Token (JWT) implementation for stateless authentication, with automatic token refresh and secure storage.

Role-Based Access Control

Comprehensive role and permission system to control access to different parts of your application based on user roles.

Customizable UI Components

Pre-built, responsive UI components for login, registration, password reset, and profile management that you can customize to match your brand.

Implementation Guide

Basic Setup

// 1. Install required packages
npm install next-auth@latest

// 2. Create auth configuration
// app/api/auth/[...nextauth]/route.ts
import NextAuth from 'next-auth';
import { authConfig } from '@/auth.config';

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

// 3. Create auth.config.ts in the root
import type { NextAuthConfig } from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import CredentialsProvider from 'next-auth/providers/credentials';

export const authConfig: NextAuthConfig = {
  providers: [
    GoogleProvider({
      clientId: process.env.YOUR_GOOGLE_CLIENT_ID,
      clientSecret: process.env.YOUR_GOOGLE_CLIENT_SECRET,
    }),
    CredentialsProvider({
      name: 'Credentials',
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials) {
        // Add your own logic here for validating credentials
        // This is just a simple example
        if (credentials?.email === 'user@example.com' && 
            credentials?.password === 'password') {
          return { 
            id: '1', 
            name: 'User', 
            email: 'user@example.com',
            role: 'user'
          };
        }
        return null;
      }
    }),
  ],
  pages: {
    signIn: '/auth/login',
    error: '/auth/error',
  },
  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;
      }
      return session;
    },
  },
};

Protected Route Example

// 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 });
  
  // Check if user is authenticated
  if (!token) {
    return NextResponse.redirect(new URL('/auth/login', request.url));
  }
  
  // Check for role-based access
  if (request.nextUrl.pathname.startsWith('/admin') && 
      token.role !== 'admin') {
    return NextResponse.redirect(new URL('/unauthorized', request.url));
  }
  
  return NextResponse.next();
}

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

Use Cases

SaaS Applications

Implement secure user authentication and subscription management for SaaS products.

E-commerce Platforms

Secure customer accounts, order history, and payment information for online stores.

Content Management

Control access to content creation and management based on user roles and permissions.

Ready to Implement Secure Authentication?

Get started with the Next.js Authentication Flow today and add secure, flexible authentication to your application.