Docs

Authentication

Configure authentication providers, protect routes, and manage user sessions in your Next.js 16 Starter Kit application.

Authentication

The Next.js 16 Starter Kit supports multiple authentication providers. This guide covers setup and configuration for each option.

Supported Providers

ProviderBest ForComplexity
Better AuthSelf-hosted, full controlMedium
ClerkProduction apps, fast setupLow
NextAuth.jsOAuth providers, flexibilityMedium

Better Auth is the default provider offering a self-hosted solution with email/password and OAuth support.

Configuration

# .env.local
AUTH_PROVIDER="better-auth"
AUTH_SECRET="your-random-secret-min-32-chars"
AUTH_URL="http://localhost:3000"

# OAuth Providers (optional)
GITHUB_CLIENT_ID="your-github-client-id"
GITHUB_CLIENT_SECRET="your-github-client-secret"
GOOGLE_CLIENT_ID="your-google-client-id"
GOOGLE_CLIENT_SECRET="your-google-client-secret"

Usage

// In your component or API route
import { auth } from '@repo/auth';

// Server-side authentication
const session = await auth.api.getSession({
  headers: request.headers
});

if (!session) {
  return new Response('Unauthorized', { status: 401 });
}

Clerk

Clerk provides a managed authentication service with pre-built UI components.

Installation

bun add @clerk/nextjs

Configuration

# .env.local
AUTH_PROVIDER="clerk"
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY="pk_test_..."
CLERK_SECRET_KEY="sk_test_..."
NEXT_PUBLIC_CLERK_SIGN_IN_URL="/sign-in"
NEXT_PUBLIC_CLERK_SIGN_UP_URL="/sign-up"

Protecting Routes

// middleware.ts
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server';

const isProtectedRoute = createRouteMatcher(['/dashboard(.*)']);

export default clerkMiddleware((auth, req) => {
  if (isProtectedRoute(req)) auth().protect();
});

NextAuth.js

NextAuth.js (Auth.js) is a flexible authentication library supporting many OAuth providers.

Configuration

# .env.local
AUTH_PROVIDER="next-auth"
AUTH_SECRET="your-secret"
AUTH_URL="http://localhost:3000"

# OAuth Providers
GITHUB_ID="your-github-id"
GITHUB_SECRET="your-github-secret"

Provider Setup

// src/lib/auth.ts
import NextAuth from 'next-auth';
import GitHub from 'next-auth/providers/github';

export const { handlers, auth } = NextAuth({
  providers: [GitHub],
  callbacks: {
    session({ session, user }) {
      session.user.id = user.id;
      return session;
    }
  }
});

Protecting API Routes

All authentication providers work with a unified pattern:

// src/app/api/protected/route.ts
import { auth } from '@repo/auth';

export async function GET(request: Request) {
  const session = await auth();
  
  if (!session) {
    return Response.json(
      { error: 'Unauthorized' },
      { status: 401 }
    );
  }
  
  return Response.json({ 
    message: 'Hello, authenticated user!',
    user: session.user 
  });
}

Protecting Pages

Server Component

// src/app/dashboard/page.tsx
import { auth } from '@repo/auth';
import { redirect } from 'next/navigation';

export default async function DashboardPage() {
  const session = await auth();
  
  if (!session) {
    redirect('/sign-in');
  }
  
  return <div>Welcome, {session.user.name}!</div>;
}

Client Component

'use client';

import { useSession } from '@repo/auth/client';

export function UserProfile() {
  const { data: session, status } = useSession();
  
  if (status === 'loading') return <div>Loading...</div>;
  if (status === 'unauthenticated') return <div>Please sign in</div>;
  
  return <div>Hello, {session?.user?.name}</div>;
}

Session Configuration

Configure session behavior in your auth setup:

{
  session: {
    strategy: 'jwt', // or 'database'
    maxAge: 30 * 24 * 60 * 60, // 30 days
  },
  cookies: {
    sessionToken: {
      name: 'auth-token',
      options: {
        httpOnly: true,
        sameSite: 'lax',
        secure: process.env.NODE_ENV === 'production'
      }
    }
  }
}

Switching Providers

To switch authentication providers:

  1. Update AUTH_PROVIDER in .env.local
  2. Install any required dependencies
  3. Update your environment variables
  4. Restart the development server

:::warning When switching providers, existing sessions will be invalidated. Users will need to sign in again. :::

Next Steps

On this page