Authentication in Next.js

📘 Next.js 👁 37 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Authentication in Next.js is used to verify user identity and protect routes, APIs, and data. Next.js supports multiple authentication approaches, from custom logic to fully managed libraries.


1. Authentication Approaches in Next.js

Common Methods

  • Custom authentication (JWT, sessions)

  • NextAuth.js (Auth.js) – most popular

  • OAuth providers (Google, GitHub, Facebook)

  • Email & password authentication

  • Token-based authentication


2. Using NextAuth.js (Recommended)

NextAuth.js (now called Auth.js) is the easiest and most secure way to handle authentication in Next.js.

Installation

npm install next-auth

Basic Setup (App Router)

Folder Structure

app/ └── api/ └── auth/ └── [...nextauth]/ └── route.js

Configuration Example

import NextAuth from 'next-auth'; import GoogleProvider from 'next-auth/providers/google'; export const authOptions = { providers: [ GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }), ], session: { strategy: 'jwt', }, }; const handler = NextAuth(authOptions); export { handler as GET, handler as POST };

3. Environment Variables

Add credentials in .env.local:

GOOGLE_CLIENT_ID=your_id GOOGLE_CLIENT_SECRET=your_secret NEXTAUTH_SECRET=your_secret_key NEXTAUTH_URL=http://localhost:3000

4. Using Session in Components

Server Component

import { getServerSession } from 'next-auth'; const session = await getServerSession(authOptions);

Client Component

'use client'; import { useSession, signIn, signOut } from 'next-auth/react'; export default function AuthButton() { const { data: session } = useSession(); if (session) { return <button onClick={() => signOut()}>Logout</button>; } return <button onClick={() => signIn()}>Login</button>; }

5. Protecting Pages with Middleware

import { getToken } from 'next-auth/jwt'; import { NextResponse } from 'next/server'; export async function middleware(request) { const token = await getToken({ req: request }); if (!token) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); } export const config = { matcher: ['/dashboard/:path*'], };

6. Custom Authentication (JWT Example)

import jwt from 'jsonwebtoken'; const token = jwt.sign({ userId: 1 }, process.env.JWT_SECRET, { expiresIn: '1d', });

Used for:

  • Custom login systems

  • Mobile APIs

  • External services


7. Authentication in API Routes

export async function GET(request) { const token = request.headers.get('authorization'); if (!token) { return Response.json({ error: 'Unauthorized' }, { status: 401 }); } }

Best Practices

  • Use environment variables

  • Prefer server-side session checks

  • Protect sensitive routes with middleware

  • Avoid storing secrets on the client

  • Use HTTPS in production


Conclusion

Authentication in Next.js is flexible and powerful. For most applications, NextAuth.js (Auth.js) is the recommended solution due to its security, ease of use, and wide provider support.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes