Next.jsMedium

How do you protect API routes with authentication?

Verify the user inside every Route Handler (or Server Function) before doing any work: read the session cookie or Authorization header, validate it, check permissions for the specific resource, and return 401 or 403 on failure. Proxy can do optimistic redirects, but it must not be the only check.

Steps in a handler

  1. Authenticate: get the session token from a cookie or a Bearer token, then verify it (signature and expiry for a JWT, a lookup for database sessions).
  2. Authorize: check the user's role or ownership of the resource (post.authorId === user.id).
  3. Validate input, then perform the operation.
  4. Return minimal data.

Centralize the logic

Create a Data Access Layer (lib/dal.ts) with verifySession() and permission helpers, marked import "server-only" and wrapped in React.cache so repeated calls in one request are cheap. Call it from handlers, Server Functions and Server Components.

Where Proxy fits

proxy.ts can read the session cookie and redirect anonymous users away from /dashboard or reject /api/admin/* early. But matchers are easy to misconfigure, and a refactor can move a route outside the matcher. The docs explicitly say to verify auth inside each Server Function and handler rather than relying on Proxy alone.

Other protections

  • API keys for machine clients, compared in constant time.
  • Webhook signatures (HMAC) for third-party callbacks.
  • Rate limiting on login and expensive endpoints.
  • CORS to restrict which browser origins can call the API; CORS is not authentication.

Code example

tsx
1// lib/dal.ts
2import "server-only";
3import { cache } from "react";
4import { cookies } from "next/headers";
5import { decrypt } from "@/lib/session";
6
7export const verifySession = cache(async () => {
8 const token = (await cookies()).get("session")?.value;
9 const session = token ? await decrypt(token) : null; // verifies signature + expiry
10 return session?.userId ? { userId: session.userId as string, role: session.role as string } : null;
11});
12
13// app/api/projects/[id]/route.ts
14import { db } from "@/lib/db";
15
16export async function DELETE(_req: Request, ctx: RouteContext<"/api/projects/[id]">) {
17 const session = await verifySession();
18 if (!session) return Response.json({ error: "Unauthorized" }, { status: 401 });
19
20 const { id } = await ctx.params;
21 const project = await db.project.findUnique({ where: { id } });
22 if (!project) return Response.json({ error: "Not found" }, { status: 404 });
23 if (project.ownerId !== session.userId && session.role !== "admin") {
24 return Response.json({ error: "Forbidden" }, { status: 403 });
25 }
26
27 await db.project.delete({ where: { id } });
28 return new Response(null, { status: 204 });
29}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app