🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Securing Route Handlers: Auth, Rate Limits, Validation

Next.js SecurityđŸŸĸ Free Lesson

Securing Route Handlers: Auth, Rate Limits, Validation

A route handler is a public endpoint the moment it ships. It has a URL, it accepts arbitrary bytes, and unless you say otherwise it will cheerfully process whatever a script sends at three in the morning. The reassuring fact about app/api/*/route.js is that there is nothing exotic about it — it is a function that returns a Response, so every security control you would write in any other framework applies directly. The dangerous fact is that nothing in the framework forces you to write those controls, and the default handler you sketched during development runs unchanged in production.

This lesson walks through the four controls that matter for handlers — authentication, authorization, rate limiting, and input validation — plus the header configuration that decides who may call them at all.

Prerequisites

  • !Route handlers and the Request and Response objects
  • !How sessions or JWTs are stored in your app
  • !Basic SQL or ORM query knowledge

What You'll Learn

  • 1Decide where authentication belongs: middleware or handler
  • 2Implement a rate limiter with correct status codes and headers
  • 3Validate request bodies, query strings and headers with a schema
  • 4Configure CORS, allowed methods and caching headers deliberately

Where authentication actually belongs

Middleware runs at the edge, before the request reaches your handler, which makes it attractive for a blanket check — redirect unauthenticated users away from /dashboard, for instance. But middleware cannot see what a handler does with the request, and it runs against a runtime that may not have access to your database or secret store. The reliable pattern is a defence in depth: middleware handles coarse redirects for pages, and each handler verifies the credential itself before touching data.

// lib/require-auth.js
import { NextResponse } from 'next/server';
import { verifySessionToken } from '@/lib/session';

export async function requireAuth(request) {
  const header = request.headers.get('authorization') || '';
  const token = header.startsWith('Bearer ') ? header.slice(7) : null;

  if (!token) {
    return { error: NextResponse.json({ error: 'Authentication required' }, { status: 401 }) };
  }

  try {
    const session = await verifySessionToken(token);
    return { session };
  } catch {
    // Deliberately identical for missing, expired and malformed tokens.
    return { error: NextResponse.json({ error: 'Authentication required' }, { status: 401 }) };
  }
}

// app/api/documents/route.js
import { requireAuth } from '@/lib/require-auth';
import { db } from '@/lib/db';

export async function GET(request) {
  const { session, error } = await requireAuth(request);
  if (error) return error;

  const documents = await db.document.findMany({
    where: { ownerId: session.sub },
    select: { id: true, title: true, updatedAt: true },
  });

  return NextResponse.json({ documents });
}

The ownerId filter is the authorization half, and it belongs in the query rather than in a conditional after it. Checking ownership in JavaScript after fetching rows means the day you forget the check, the endpoint silently returns everyone's data; scoping the query means a forgotten filter returns nothing instead of everything.

Rate limiting that survives a restart

An in-memory Map keyed by IP is a fine starting point and a poor final answer: it resets whenever the process restarts, it is wrong behind a load balancer where each instance sees only some traffic, and it trusts a client-controlled header if you read the address from x-forwarded-for without care. The behaviour to aim for is a fixed-window or sliding-window counter in a shared store, with honest responses.

// lib/rate-limit.js
const WINDOW_MS = 60_000;

export async function rateLimit(key, limit, windowMs = WINDOW_MS, store = redis) {
  const now = Date.now();
  const bucket = `rl:${key}`;

  // A sorted set of timestamps gives a true sliding window.
  await store.zremrangebyscore(bucket, 0, now - windowMs);
  const count = await store.zadd(bucket, { score: now, value: `${now}` }, { NX: true });

  if (count > limit) {
    const oldest = await store.zrange(bucket, 0, 0, { WITHSCORES: true });
    const retryAfter = Math.max(
      1,
      Math.ceil((Number(oldest[1]) + windowMs - now) / 1000)
    );
    return { ok: false, retryAfter, remaining: 0 };
  }

  return { ok: true, remaining: Math.max(0, limit - count), retryAfter: 0 };
}

Return 429 Too Many Requests with a Retry-After header when the window is exhausted, and always emit X-RateLimit-Remaining so a well-behaved client can back off before it is told to. Give stricter limits to expensive or guessable endpoints — password reset, one-time code verification, search — than to reads, and key on the session where one exists so a shared office IP cannot exhaust another user's allowance.

Endpoint typeSuggested limitKey onResponse when exceeded
Authentication attempt5 per 5 minutesIP plus account429 with Retry-After
One-time code verify3 per 10 minutesAccount429, generic message
Expensive read60 per minuteSession429 with headers
Ordinary read300 per minuteSession429 with headers
Webhook receiverProvider-specificSignature400 if signature invalid

Validate every input with a schema

Client-side validation is a courtesy to your users; server-side validation is the security control. Anything the browser sends — body, query parameters, route params, headers — is attacker-controlled, and the shape you expect in your editor is not the shape that arrives.

// app/api/posts/route.js
import { z } from 'zod';

const createPost = z.object({
  title: z.string().trim().min(1).max(200),
  body: z.string().min(1).max(20_000),
  tags: z.array(z.string().trim().min(1).max(30)).max(5).default([]),
  publishedAt: z.coerce.date().optional(),
});

export async function POST(request) {
  const { session, error } = await requireAuth(request);
  if (error) return error;

  let payload;
  try {
    payload = await request.json();
  } catch {
    return NextResponse.json({ error: 'Body must be valid JSON' }, { status: 400 });
  }

  const parsed = createPost.safeParse(payload);
  if (!parsed.success) {
    return NextResponse.json(
      { errors: parsed.error.flatten().fieldErrors },
      { status: 400 }
    );
  }

  // Only parsed.data reaches the database layer.
  const post = await db.post.create({
    data: { ...parsed.data, authorId: session.sub },
  });

  return NextResponse.json({ post }, { status: 201 });
}

Note what the schema does beyond type checking: trim and length caps run before the query, z.coerce.date rejects nonsense rather than passing it to the driver, and .default() removes the need for defensive code downstream. The rule that keeps this honest is that the database call receives only parsed.data — spreading the raw body "just this once" is how a length limit ends up existing in three files and none of them.

Validation also prevents the class of bugs where a filter object comes from the request: never let a client supply a column name, an operator, or a sort direction that is not on an allow list.

CORS, methods, and the headers around a response

CORS is enforced by the browser, not by your server, and the failure mode is confusing: a handler works perfectly from Postman and refuses in the browser. If your API is only ever called from your own pages, the simplest correct configuration is to deny cross-origin reads entirely. When another origin legitimately needs access, respond with an explicit origin, credentials policy, and method list rather than echoing whatever Origin header arrived.

import { NextResponse } from 'next/server';

export async function POST(request) {
  const origin = request.headers.get('origin');
  const allowed = new Set(process.env.ALLOWED_ORIGINS.split(','));

  if (origin && !allowed.has(origin)) {
    return new NextResponse(null, { status: 403 });
  }

  const response = NextResponse.json({ ok: true });
  if (origin) {
    response.headers.set('Access-Control-Allow-Origin', origin);
    response.headers.set('Access-Control-Allow-Credentials', 'true');
    response.headers.set('Vary', 'Origin');
  }
  response.headers.set('X-Content-Type-Options', 'nosniff');
  response.headers.set('Cache-Control', 'no-store');
  return response;
}

Vary: Origin is easy to forget and expensive to miss: without it, a shared cache can serve one origin's CORS-approved response to another. no-store belongs on anything authenticated, because a CDN that caches a personalised response will eventually hand it to the wrong person. And nosniff costs nothing while removing a family of content-type confusion attacks.

What your error messages and timings reveal

Two endpoints that behave identically for valid and invalid input are much harder to attack than one that distinguishes them. A sign-in that returns "no account with this email" tells an attacker which addresses are worth targeting; a password-reset endpoint that returns success for unknown users and a code for known ones is an enumeration oracle wearing a helpful face. The rule is to make the response for "does not exist" indistinguishable from the response for "exists but did not match", and to return that same response for the password case.

Timing is the quieter channel. If the handler hashes a password only when the account exists, a valid account answers noticeably slower than an invalid one, and a script can separate the two with a few hundred samples. The standard mitigation is to do equivalent work in both branches — hash a dummy secret when the lookup misses — so the two paths cost the same. It feels theatrical until you see a credential-stuffing script that would otherwise have been told exactly which of your users' emails appear in some other company's breach dump.

Log these attempts with the outcome and the reason, but keep the reason out of the response. Your security log wants to know that five lookups for one address came from one IP; your user should only ever see a sentence that helps them proceed.

One wrapper so no handler forgets

Security controls that live in a checklist eventually get skipped; controls that live in a wrapper get used. Composing the three checks — authenticate, rate limit, validate — into a single helper means a new endpoint inherits the defaults and the developer opts out deliberately rather than by omission.

// lib/handler.js — the path every mutating endpoint takes
export function secureHandler({ schema, limit = 60, scope = 'session' }) {
  return async function handler(request, context) {
    const { session, error } = await requireAuth(request);
    if (error) return error;

    const key = scope === 'session' ? session.sub : requestIp(request);
    const verdict = await rateLimit(`${scope}:${key}`, limit);
    if (!verdict.ok) {
      return new NextResponse(JSON.stringify({ error: 'Too many requests' }), {
        status: 429,
        headers: { 'Retry-After': String(verdict.retryAfter) },
      });
    }

    const payload = await readJson(request);
    const parsed = schema.safeParse(payload);
    if (!parsed.success) {
      return NextResponse.json(
        { errors: parsed.error.flatten().fieldErrors },
        { status: 400 }
      );
    }

    // The endpoint body receives a verified session and validated data.
    return handle(parsed.data, session, context);
  };
}

The payoff is visible in review: an endpoint's diff shows its schema and its limit, and nothing else. What the wrapper cannot decide for you is authorization — which user may touch which record — because that lives in the domain query. Keep that decision where the data is, and let the wrapper handle the parts that are identical everywhere.

Common Mistakes

Trusting authentication performed only in middleware

Fix: Verify the session inside the handler too; middleware guards navigation, handlers guard data.

Filtering for ownership after fetching rows

Fix: Put the owner condition in the query so an omitted check returns nothing instead of everything.

Validating only in the client

Fix: Re-validate on the server with a schema, and pass only parsed data to your data layer.

Rate limiting with an in-memory Map in a multi-instance deployment

Fix: Use a shared store and key on the session where possible, and always return 429 with Retry-After.

Returning detailed validation or auth errors

Fix: Keep failure messages generic for credentials, specific only for field-level input the user is editing.

Best Practices

  • Centralise auth, rate limiting and validation in small helpers each handler calls first
  • Apply the principle of least data: select only the columns the response needs
  • Set no-store on authenticated responses and Vary whenever the response depends on a header
  • Log rejected requests with a reason code — they are your earliest intrusion signal

Key Takeaways

  • Middleware redirects pages; route handlers must authenticate themselves before touching data.
  • Authorization belongs inside the query so a missing filter fails closed.
  • Rate limits need a shared store, honest 429 responses, and stricter budgets for guessable endpoints.
  • Schema-validate body, query and params on the server, and pass only the parsed object onward.
  • CORS, Vary, no-store and nosniff are a handful of headers that remove whole vulnerability classes.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement