Next.js JWT Authentication Middleware

Implement JWT-based authentication in Next.js using middleware for route protection, cookie-based token storage, and edge-compatible jose library for token.

TypescriptNextAuth Jwt

Code

snippet
import { jwtVerify } from 'jose';
import { NextResponse } from 'next/server';

const secret = new TextEncoder().encode(process.env.JWT_SECRET);

export async function middleware(request: Request) {
  const token = request.cookies.get('token')?.value;
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  try {
    const { payload } = await jwtVerify(token, secret);
    const response = NextResponse.next();
    response.headers.set('x-user-id', String(payload.sub));
    return response;
  } catch {
    return NextResponse.redirect(new URL('/login', request.url));
  }
}

How the snippet works

The working surface is the function middleware — everything else is wiring.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Everything borrowed from jose is visible in one line: jwtVerify, NextResponse.

Configuration comes from the environment — it reads JWT_SECRET, so the same code switches behavior between environments without edits.

Points of care

  • Dependency check: jose and next/server — not built-in, must be present in the project.
  • The guard !token short-circuits the flow with an early return when its condition holds.

Applying it

The primary signature is export async function middleware(request: Request)

Import middleware from the file and call it — the rest of the code is implementation detail.

Statements that matter

return NextResponse.redirect(new URL('/login', request.url));
const { payload } = await jwtVerify(token, secret);
const token = request.cookies.get('token')?.value;

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `jose` and `next/server` must be present in the project or the import fails at load time.