# Protect Routes and Server Actions in Next.js 16

Lock down a Next.js 16 app in two layers: a quick cookie check in `proxy.ts` that redirects signed-out visitors, and a real session check in a Data Access Layer that every page, Server Action and Route Handler calls.

*Intermediate · 20 min · Updated Nov 18, 2026*

## What you'll build

- A `proxy.ts` that sends signed-out visitors to `/login`
- A Data Access Layer with `getCurrentUser()` and `requireUser()`
- Pages, layouts, Server Actions and Route Handlers that each check the session
- Queries scoped to the signed-in user, so nobody can read or change someone else's rows

## Before you start

- A Next.js 16 app with sign-in and an HTTP-only session cookie. [Add Email/Password and Google Login to Next.js](https://cloudhike.dev/guides/nextjs-authentication-email-google) builds exactly that.
- A CloudHike.dev project with Auth deployed
- Optional: Postgres with Drizzle for the data examples ([setup guide](https://cloudhike.dev/guides/postgres-nextjs-drizzle))

## Why proxy.ts alone is not enough

In Next.js 16, `middleware.ts` is renamed to `proxy.ts`. It runs before a route renders, which makes it a great place to redirect signed-out visitors. It is a bad place to be your only check, for three reasons:

- **Server Actions skip it.** An action is a `POST` to whatever page it was called from. Your matcher may cover `/dashboard`, but the same action can be posted to `/` or any other path the matcher leaves out. Treat every Server Action like a public API endpoint.
- **It should stay fast.** Proxy runs on every matched request, including link prefetches. The Next.js docs recommend reading only the cookie there and skipping network or database calls. So proxy knows a cookie exists, not that it is valid.
- **One layer can fail.** In 2025 a Next.js bug (CVE-2025-29927) let a crafted header skip middleware entirely. Apps that also checked the session next to their data were not exposed.

| Layer | What it checks | Job |
| --- | --- | --- |
| `proxy.ts` | Is there a session cookie? | Fast redirect to `/login`. Good UX, not security. |
| Data Access Layer | Is the session valid? Who is the user? | The real check, next to the data. |
| Your queries | Does this row belong to this user? | Stops one user from touching another's data. |

## Step 1: Add an optimistic check in proxy.ts

Create `proxy.ts` at the project root, next to `app/` (or inside `src/` if you use it). It checks only whether the cookie is there. If not, it redirects to `/login` and remembers where the visitor was going.

*proxy.ts*

```ts
import { NextResponse, type NextRequest } from "next/server";

// Must match SESSION_COOKIE in lib/auth.ts.
const SESSION_COOKIE = "session";

export function proxy(request: NextRequest) {
  if (request.cookies.has(SESSION_COOKIE)) return NextResponse.next();

  const login = new URL("/login", request.url);
  login.searchParams.set("next", request.nextUrl.pathname + request.nextUrl.search);
  return NextResponse.redirect(login);
}

export const config = {
  // Only the areas that need a signed-in user.
  matcher: ["/dashboard/:path*", "/settings/:path*", "/api/private/:path*"],
};
```

The matcher keeps proxy off your public pages, static files and images. Matcher values must be constants, because Next.js reads them at build time.

> **Warning:** Don't also redirect signed-in users away from `/login` in proxy. If a cookie is present but the session has expired, proxy would send them to `/dashboard`, the real check would send them back to `/login`, and the browser would loop. Let the login page do that check instead (Step 3).

Coming from an older version? Rename `middleware.ts` to `proxy.ts` and the exported `middleware` function to `proxy`. Proxy runs on the Node.js runtime, and setting a `runtime` option in it throws an error.

## Step 2: Build a Data Access Layer

The Data Access Layer (DAL) is one server-only file that answers "who is signed in?" by calling CloudHike's `get-session` endpoint with the cookie's token. It builds on `getSession()` and `SESSION_COOKIE` from `lib/auth.ts` in the [login guide](https://cloudhike.dev/guides/nextjs-authentication-email-google).

*lib/dal.ts*

```ts
import "server-only";
import { cache } from "react";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { getSession, SESSION_COOKIE } from "@/lib/auth";

export type CurrentUser = { id: string; email: string; name: string };

// cache() runs this once per request, however many components call it.
export const getCurrentUser = cache(async (): Promise<CurrentUser | null> => {
  const token = (await cookies()).get(SESSION_COOKIE)?.value;
  const session = await getSession(token); // GET {AUTH_URL}/get-session
  if (!session) return null;

  // Return only what the app needs, not the whole session object.
  const { id, email, name } = session.user;
  return { id, email, name };
});

// For pages and actions that only make sense signed in.
export async function requireUser(): Promise<CurrentUser> {
  const user = await getCurrentUser();
  if (!user) redirect("/login");
  return user;
}
```

React's `cache()` matters here. A layout, a page and three components can all call `getCurrentUser()`, and the Auth API is still called only once for that request. The cache is per request, so one user's session never leaks into another's.

> **Note:** `getSession()` returns `null` for a missing or rejected token, and throws when the Auth API itself is unavailable. That way an outage shows your error page instead of quietly signing everyone out.

## Step 3: Check the session in pages and layouts

Call `requireUser()` wherever user data is loaded. Put it in the component that needs the user, wrapped in `<Suspense>`, so the static parts of the page stream first.

*app/dashboard/page.tsx*

```tsx
import { Suspense } from "react";
import { requireUser } from "@/lib/dal";

async function Overview() {
  const user = await requireUser();
  return <p>Welcome back, {user.name}.</p>;
}

export default function DashboardPage() {
  return (
    <main className="p-8">
      <h1>Dashboard</h1>
      <Suspense fallback={<p>Loading…</p>}>
        <Overview />
      </Suspense>
    </main>
  );
}
```

A layout is a good place to **show** the user, not to **protect** routes. Layouts don't re-render on every navigation, and the pages and actions under them can still be reached on their own. So the layout reads the user for the nav, and each page still does its own check.

*app/dashboard/layout.tsx*

```tsx
import { Suspense } from "react";
import { getCurrentUser } from "@/lib/dal";

async function UserMenu() {
  const user = await getCurrentUser();
  return user ? <span>{user.email}</span> : null;
}

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  return (
    <>
      <header className="flex justify-between p-4">
        <strong>My App</strong>
        <Suspense fallback={null}>
          <UserMenu />
        </Suspense>
      </header>
      {children}
    </>
  );
}
```

The login page sends signed-in users on, and honors the `next` link proxy added. Only accept paths on your own site, or `?next=https://evil.example` turns your login page into an open redirect.

*app/(auth)/login/page.tsx*

```tsx
import { Suspense } from "react";
import { redirect } from "next/navigation";
import { getCurrentUser } from "@/lib/dal";
import { LoginForm } from "./login-form";

// Only same-site paths like "/dashboard", never "//evil.example" or a full URL.
const safeNext = (next: unknown) =>
  typeof next === "string" && next.startsWith("/") && !next.startsWith("//") ? next : "/dashboard";

async function LoginGate({ searchParams }: { searchParams: PageProps<"/login">["searchParams"] }) {
  const next = safeNext((await searchParams).next);
  if (await getCurrentUser()) redirect(next);
  return <LoginForm next={next} />;
}

export default function LoginPage({ searchParams }: PageProps<"/login">) {
  return (
    <main className="mx-auto grid max-w-sm gap-4 p-8">
      <h1>Sign in</h1>
      <Suspense fallback={null}>
        <LoginGate searchParams={searchParams} />
      </Suspense>
    </main>
  );
}
```

`PageProps` is a global helper type Next.js generates for each route, and `searchParams` is a promise in Next.js 16. Await it inside `<Suspense>`, like cookies, so the page shell still streams. In `LoginForm`, add `<input type="hidden" name="next" value={next} />`. In your sign-in action, run it through the same `safeNext()` and `redirect()` there instead of to a fixed path.

## Step 4: Protect every Server Action

Every action that reads or changes private data starts with `requireUser()`. Then it scopes the query to that user. Checking that someone is signed in is not enough: you also have to check that the row is theirs.

*app/dashboard/actions.ts*

```ts
"use server";

import { and, eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { db } from "@/db";
import { todos } from "@/db/schema";
import { requireUser } from "@/lib/dal";

export async function deleteTodo(id: number) {
  const user = await requireUser();

  if (!Number.isInteger(id)) throw new Error("Invalid id");

  // The userId filter is the authorization check. Without it,
  // any signed-in user could delete any todo by guessing ids.
  const deleted = await db
    .delete(todos)
    .where(and(eq(todos.id, id), eq(todos.userId, user.id)))
    .returning({ id: todos.id });

  if (deleted.length === 0) throw new Error("Todo not found");
  revalidatePath("/dashboard");
}
```

This assumes your table stores the CloudHike Auth user id. Add a `userId: text("user_id").notNull()` column to the `todos` table from the [Drizzle guide](https://cloudhike.dev/guides/postgres-nextjs-drizzle), and set it from `requireUser()` on insert, never from form data.

> **Warning:** Never trust a user id, role or price that comes in as an action argument or form field. The browser controls those. Always take identity from `requireUser()` on the server.

## Step 5: Protect Route Handlers

Route Handlers are called by `fetch`, not by page navigation, so a redirect to `/login` isn't useful there. Use `getCurrentUser()` and answer `401` instead.

*app/api/private/todos/route.ts*

```ts
import { desc, eq } from "drizzle-orm";
import { db } from "@/db";
import { todos } from "@/db/schema";
import { getCurrentUser } from "@/lib/dal";

export async function GET() {
  try {
    const user = await getCurrentUser();
    if (!user) return Response.json({ message: "Not signed in" }, { status: 401 });

    const rows = await db
      .select({ id: todos.id, title: todos.title, done: todos.done })
      .from(todos)
      .where(eq(todos.userId, user.id))
      .orderBy(desc(todos.createdAt));

    return Response.json(rows);
  } catch (err) {
    console.error(err);
    return Response.json({ message: "Something went wrong" }, { status: 500 });
  }
}
```

If a mobile app or another server calls this endpoint, it can send `authorization: Bearer <token>` instead of a cookie. Read that header and pass the token to the same `getSession()` helper.

## Production checklist

- Search your code for `"use server"` and confirm every exported action calls `requireUser()` or is meant to be public.
- Check that every query on private data filters by `user.id` from the DAL.
- Keep `lib/dal.ts` and `lib/auth.ts` behind `import "server-only"`, so a Client Component can never import them.
- Pass Client Components only the fields they need (like `name` and `email`), never the token or the full session.
- Keep the proxy matcher narrow and free of network calls. Put role or plan checks in the DAL, where you can call the API or database.
- Watch the Auth card for errors. A `503` from `get-session` means Auth is briefly unavailable, not that the user signed out. See [Endpoints](https://cloudhike.dev/docs/auth#endpoints).

## FAQ

### What happened to middleware.ts in Next.js 16?

It was renamed to proxy.ts, and the exported function is now called proxy. It works the same way: it runs before a route renders and can redirect, rewrite or set headers. It runs on the Node.js runtime.

### Is it safe to protect routes only in proxy.ts?

No. Proxy should only do a quick cookie check, Server Actions can be posted to paths your matcher skips, and a framework bug can bypass it. Always check the session again next to your data, in a Data Access Layer.

### Do Server Actions need their own auth check?

Yes. A Server Action is a public POST endpoint that anyone can call with any arguments. Check the session at the start of every action, and check that the user owns the data it changes.

### Can I check auth in a Next.js layout?

You can read the user in a layout to show a name or avatar, but don't rely on it for protection. Layouts don't re-run on every navigation, and the pages and actions under them can be reached directly. Check in each page, action and Route Handler.

### Does calling getCurrentUser in many components make many API calls?

No. It is wrapped in React's cache, so it runs once per request and every caller gets the same result.
