Skip to main content

MIDDLEWARE

middleware.ts

Auth, request logging, rate limiting.

Stark avatarStark

WHAT THIS PATTERN TEACHES

How to compose middleware that authenticates, logs, and rate-limits requests with structured context.

WHEN TO USE THIS

Route protection, request logging, rate limiting, and any cross-cutting concerns.

AT A GLANCE

export function withAuth(handler: Handler) {
  return async (req: NextRequest) => {
    const session = await getSession(req)
    if (!session) return unauthorized()
    return handler(req, session)
  }
}

FRAMEWORK IMPLEMENTATIONS

TypeScript
import { NextRequest, NextResponse } from "next/server";

const RATE_LIMIT_WINDOW = 60_000; // 1 minute
const RATE_LIMIT_MAX = 60;
const hits = new Map<string, { count: number; reset: number }>();

export function middleware(req: NextRequest) {
  const requestId = crypto.randomUUID();
  const ip = req.headers.get("x-forwarded-for") ?? "unknown";

  // Rate limiting
  const now = Date.now();
  const entry = hits.get(ip);
  if (entry && now < entry.reset) {
    entry.count++;
    if (entry.count > RATE_LIMIT_MAX) {
      return NextResponse.json(
        { error: "Too many requests" },
        { status: 429 }
      );
← All Patterns