Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 72 ยท Middleware, Proxy and Auth

Authorization and Data Security

Learn why Next.js proxy checks are not enough: verify access in every Server Action, Route Handler and data function, use roles, ownership checks and DTOs.

Authentication tells you who is asking. Authorization decides what that person may do: read this order, edit that post, delete any user. A surprising number of real security bugs are not broken logins but missing authorization checks: someone is logged in, and the app simply forgets to ask whether this particular person may touch this particular record.

In Next.js the risk is higher than it looks, because there are many doors into your data: pages, layouts, Server Actions, Route Handlers and the proxy file. A common beginner design checks login in the proxy and assumes everything behind it is safe. This lesson shows why that is not enough, and teaches the pattern that is: check access in the code that touches the data, every time.

Next.js itself does not run on this site, so the Next.js code here is read-only. The runnable examples are plain Node.js programs that model the same layers (a proxy, pages, actions and a data layer) so you can watch a request get through, or get stopped.

Authentication versus authorization

Two different questions

Authentication Who are you?
Authorization What may you do with this?

Logged in does not mean allowed.

1 / 2

Why the proxy alone is not enough

The proxy file is a handy first filter. But there are several reasons it cannot be your only protection:

  1. It can be bypassed by a bug. In March 2025 a serious vulnerability (CVE-2025-29927) showed that in some self-hosted setups a crafted internal header could make Next.js skip middleware entirely. Apps whose only access check lived in middleware were wide open. It was fixed in patched releases (15.2.3, 14.2.25 and older lines), and hosted platforms were not affected, but the lesson outlived the bug: any single layer can have a flaw.
  2. Its matcher can miss routes. A pattern that excludes some paths, or a new route you forgot to list, is unprotected, with no error to tell you. The earlier example showed /apiary slipping through an "everything except api" pattern.
  3. It only sees cookies and URLs. It rarely knows which record is being requested, so it cannot tell whether order 102 belongs to this user.
  4. Server Actions are public endpoints. Every exported action is a URL that anyone can send a POST to, whether or not a page has a button for it. Hiding the button protects nothing.
  5. Layouts do not re-render on every navigation. When a visitor moves between pages that share a layout, the layout stays mounted, so a check inside a layout may not run again. A guard must live in each page or, better, in the data function.

The fix is not to remove the proxy, but to treat it as the optimistic layer: it sends logged-out visitors to the login page quickly, and the data layer is the layer that actually protects data.

The data access layer

Put every database read and write behind small server-only functions. Each function gets the session itself, checks permission, and returns only what the caller is allowed to see.

TypeScript
// lib/dal.ts
import 'server-only';
import { cache } from 'react';
import { redirect } from 'next/navigation';
import { readSession } from '@/lib/session';
import { db } from '@/lib/db';

export const verifySession = cache(async () => {
  const session = await readSession();
  if (!session) redirect('/login');
  return session;
});

export const getOrder = cache(async (orderId: string) => {
  const session = await verifySession();
  const order = await db.order.findUnique({ where: { id: orderId } });

  const isOwner = order?.userId === session.userId;
  if (!order || (!isOwner && session.role !== 'admin')) {
    return null; // same answer for "does not exist" and "not yours"
  }

  return { id: order.id, total: order.total, status: order.status }; // a DTO
});

Several ideas are packed in here:

  • verifySession runs in every function. React's cache makes it run only once per request, so it costs nothing to call it everywhere.
  • Ownership is checked against the record, not against anything the client claimed.
  • The function returns null whether the record is missing or forbidden, so an attacker cannot probe which ids exist. (Use notFound() in the page.)
  • A DTO (data transfer object) is a plain object with just the fields the caller needs. The raw row may contain a password hash, a card number or internal notes, and a Server Component that passes a whole row into a Client Component will serialize all of it to the browser (see Keeping Server Code on the Server).

Data Access Layers and ORMs covers how to structure these functions. The security rule is simple: pages and actions never call the database directly, they call the layer.

Checking access in actions and handlers

A Server Action receives data from the client, and that includes hidden form fields, which a user can edit. So an action must do three things, in this order: confirm who is calling, validate the input, and check that this person may do this to this record.

TypeScript
// app/posts/actions.ts
'use server';

import { revalidatePath } from 'next/cache';
import { verifySession } from '@/lib/dal';
import { can } from '@/lib/policy';
import { db } from '@/lib/db';

export async function deletePost(formData: FormData) {
  const session = await verifySession();               // 1. who?
  const id = String(formData.get('id') ?? '');         // 2. what, untrusted
  const post = await db.post.findUnique({ where: { id } });

  if (!post || !can(session, 'post:delete', post)) {   // 3. allowed?
    throw new Error('Not allowed');
  }

  await db.post.delete({ where: { id } });
  revalidatePath('/posts');
}

A Route Handler works the same way: read the session, check, then act, returning 401 when nobody is logged in and 403 (or 404) when they are not allowed.

TypeScript
// app/api/orders/[id]/route.ts
import { getOrder } from '@/lib/dal';

export async function GET(_request: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const order = await getOrder(id);
  if (!order) return Response.json({ error: 'Not found' }, { status: 404 });
  return Response.json(order);
}

Next.js helps with one more attack, cross-site request forgery. Server Actions can only be invoked with POST, and Next.js compares the Origin header with the host of your site and rejects mismatches. If your app is legitimately reached through a different host (some reverse proxies do this), you list the extra origins in next.config.ts (experimental.serverActions.allowedOrigins in current versions). Combined with SameSite=Lax cookies from Cookies and Headers, this covers the common cases. It does not replace the checks above: it only stops other websites from calling your actions on a user's behalf.

Seeing the difference

The first example models an app with a proxy and two pages: a normal notes list and an admin page that lists every note. Version A trusts the proxy. Version B also checks in the page's data function. The proxy has a deliberate bug that a header can switch it off, standing in for any bypass. Then three requests arrive.

Node.js A proxy-only app versus a layered app

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Run through the three cases. For the signed-out visitor, both apps are fine, because the proxy does its job. With the bypass header the proxy is skipped, and app A hands over every note, including Bo's, while app B still denies the request. The third case is the sneakiest: a signed-in normal user passes the proxy, which only asks "is there a session?", and app A shows them the admin page. The proxy knows who you are but has no idea what you may do. Only the check next to the data can answer that.

Roles and policies

For anything beyond "logged in or not", keep the rules in one place instead of scattering if (user.role === 'admin') through the codebase. A policy function takes the user, the action and the resource, and returns yes or no. When a rule changes, you change one file, and you can test it without a browser.

TypeScript
// lib/policy.ts
type Session = { userId: string; role: 'user' | 'admin' } | null;
type Post = { authorId: string; published: boolean };

export function can(session: Session, action: string, post: Post): boolean {
  const isAuthor = session?.userId === post.authorId;
  const isAdmin = session?.role === 'admin';
  switch (action) {
    case 'post:read':
      return post.published || isAuthor || isAdmin;
    case 'post:edit':
      return isAuthor || isAdmin;
    case 'post:delete':
      return isAdmin;
    default:
      return false; // deny by default
  }
}

The last line matters most. Deny by default: an action name nobody thought of is refused, not allowed. The next example runs a policy against four kinds of users and prints the full table, which is exactly how you would test it.

Node.js A policy table you can test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Insecure direct object references and DTOs

The most common authorization bug has a name: IDOR, an insecure direct object reference. The URL says /orders/102, the code loads order 102, and nobody asks whether it is yours. Changing 102 to 101 in the address bar then shows a stranger's order. The third example fixes it and also shapes the result into a DTO, so sensitive columns never leave the data layer.

Node.js IDOR and DTOs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The unsafe version leaks a full card number and an internal note to the wrong person. The safe version returns null for another user's order, exactly like a missing one, shows an admin the same masked data, and refuses anonymous callers. Note that even the admin gets a DTO: nobody needs a full card number in the browser.

A checklist you can reuse

  • Every Server Action and Route Handler starts by verifying the session.
  • Every data function checks ownership or role against the record, not against client input.
  • Treat all arguments as untrusted, including ids in hidden fields and bind-ed values.
  • Return DTOs from the data layer. Never serialize raw rows to the client.
  • Keep policy rules in one tested module, and deny by default.
  • Keep the proxy as a fast first filter only, and keep secrets in server-only modules.
  • Keep Next.js updated: security fixes ship in patch releases.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a Server Action considered a public endpoint?

    Hiding a button is cosmetic. The action is reachable directly, so it must verify the session and permissions itself.
  2. 2. A signed-in normal user opens /admin. The proxy only checks that a session cookie exists. What protects the admin data?

    Authentication is not authorization. The role check must happen where the data is read.
  3. 3. What is an IDOR bug?

    An insecure direct object reference lets a user change an id and see someone else's data because ownership was never checked.
  4. 4. What does 'deny by default' mean in a policy function?

    A final default branch that returns false means a forgotten action name fails closed instead of open.
  5. 5. Why return a DTO from the data layer instead of the database row?

    A DTO contains only the fields the caller needs, so sensitive columns never leave the server by accident.

Summary

  • Authentication says who you are; authorization says what you may do. A logged-in user is not automatically allowed.
  • The proxy is an optimistic filter. It can be bypassed or misconfigured, so it must never be the only check.
  • Server Actions and Route Handlers are public endpoints: verify the session, validate input and check permission in each.
  • Put access checks in a server-only data access layer, use React cache to share the session lookup, and return DTOs.
  • Check ownership against the record to prevent IDOR, and answer "missing" and "forbidden" the same way.
  • Keep rules in one policy module and deny by default.

Next: Auth.js, Better Auth and Clerk