Next.js Course
Next.js
/
Advanced

Authentication Middleware

Definition

Using Middleware as a centralized gatekeeper to verify JWTs or session tokens before granting access to protected routes.

Explain Like I'm New

Instead of checking 'Is Logged In' on 50 different pages, you do it once in the Middleware. If the token is fake or missing, they get bounced instantly.

Real World Example

Verifying a JSON Web Token (JWT) at the Edge using the `jose` library (since standard Node.js crypto libraries don't work in the Edge runtime).

Common Use Cases

  • •Global route protection
  • •Enterprise application security

Interactive Example

import { NextResponse } from 'next/server';
import { verifyJwtToken } from '@/lib/auth'; // A fictional Edge-compatible function

export async function middleware(request) {
  const token = request.cookies.get('token')?.value;

  // Only protect the /dashboard route
  if (request.nextUrl.pathname.startsWith('/dashboard')) {
    
    if (!token) {
      return NextResponse.redirect(new URL('/login', request.url));
    }

    try {
      // Verify the token cryptographically
      const validPayload = await verifyJwtToken(token);
      return NextResponse.next();
    } catch (err) {
      // Token is fake or expired! Kick them out.
      const response = NextResponse.redirect(new URL('/login', request.url));
      // Delete the bad cookie so they don't get stuck in a redirect loop
      response.cookies.delete('token');
      return response;
    }
  }
}

Interview Questions

basic

  • Why do you sometimes have to use lightweight libraries like `jose` instead of `jsonwebtoken` in Next.js Middleware?

intermediate

  • If Middleware blocks a request, does the `page.tsx` file for that route ever execute?

Flash Cards

Question

Why jose?

Click to reveal answer
Answer

Middleware runs on the Edge Runtime, not standard Node.js. It does not have access to heavy Node native modules like `crypto` or `fs`. You must use Edge-compatible libraries.

Question

Does page execute?

Click to reveal answer
Answer

No. Middleware executes BEFORE routing. If it returns a redirect or an error, the request stops immediately, saving server resources.