Handling Authentication and Protected Routes in Next.js
Optimistic checks in proxy, real checks next to the data: a layered approach to protecting routes.
- next.js
- authentication
- security
- cookies
On this page · 15 sections
Protecting routes in Next.js is easy to do in a way that looks secure and isn't. A redirect in the wrong place, a check that only lives in a layout, or a Server Action with no verification can all leave data exposed even though the UI "hides" it. This guide builds a layered approach: optimistic redirects in proxy.ts, real verification in a data access layer, and checks inside Server Actions and Route Handlers.
The examples use a signed, stateless session cookie with the jose library. The same structure applies if you use database sessions or a provider such as an identity platform.
The principle: check where the data is
Authentication answers "who are you?". Authorization answers "what may you do?". In the App Router there are several places code can run, and each needs its own answer to those questions.
| Layer | Purpose | Reliability |
|---|---|---|
proxy.ts | Fast, optimistic redirect before rendering | Convenience only |
| Page / Server Component | Decide what to render | Good, but check per page |
| Data access layer | Decide what data may be read | The one that must never be skipped |
| Server Action / Route Handler | Decide what may be changed | Required for every endpoint |
If the data layer enforces the rules, a mistake in any UI layer cannot leak data.
Step 1: Create and verify sessions
Install the dependencies:
npm install jose zodnpm install server-onlyGenerate a secret and keep it in the environment, never in the repository:
openssl rand -base64 32SESSION_SECRET=<paste the value here>// lib/session.tsimport "server-only";import { SignJWT, jwtVerify } from "jose";import { cookies } from "next/headers";const secret = process.env.SESSION_SECRET;if (!secret) throw new Error("SESSION_SECRET is not set");const key = new TextEncoder().encode(secret);export interface SessionPayload { userId: string; role: "user" | "admin";}export async function encrypt(payload: SessionPayload) { return new SignJWT({ ...payload }) .setProtectedHeader({ alg: "HS256" }) .setIssuedAt() .setExpirationTime("7d") .sign(key);}export async function decrypt(token: string | undefined): Promise<SessionPayload | null> { if (!token) return null; try { const { payload } = await jwtVerify(token, key, { algorithms: ["HS256"] }); return { userId: String(payload.userId), role: payload.role as SessionPayload["role"] }; } catch { return null; // expired, tampered or malformed }}export async function createSession(payload: SessionPayload) { const token = await encrypt(payload); (await cookies()).set("session", token, { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: "lax", path: "/", maxAge: 60 * 60 * 24 * 7, });}export async function deleteSession() { (await cookies()).delete("session");}The cookie is httpOnly so JavaScript cannot read it, secure in production so it only travels over HTTPS, and sameSite: "lax" to reduce cross-site request risk. The algorithms option pins the verification algorithm.
Step 2: Log in with a Server Action
Validate input on the server, check credentials, create the session, redirect:
// app/login/actions.ts"use server";import { redirect } from "next/navigation";import { z } from "zod";import { createSession } from "@/lib/session";import { verifyPassword, findUserByEmail } from "@/lib/users";const schema = z.object({ email: z.string().email(), password: z.string().min(8),});export async function login(_prev: { error?: string } | undefined, formData: FormData) { const parsed = schema.safeParse(Object.fromEntries(formData)); if (!parsed.success) return { error: "Enter a valid email and password." }; const user = await findUserByEmail(parsed.data.email); // Same message whether the email or the password is wrong. if (!user || !(await verifyPassword(user.passwordHash, parsed.data.password))) { return { error: "Invalid email or password." }; } await createSession({ userId: user.id, role: user.role }); redirect("/dashboard");}export async function logout() { const { deleteSession } = await import("@/lib/session"); await deleteSession(); redirect("/login");}Step 3: Optimistic checks in proxy.ts
Proxy runs before routes render, so it is the cheapest place to bounce visitors who obviously have no session. Keep it fast: read the cookie, verify the signature, never query the database.
// proxy.ts (project root, or src/)import { NextResponse, type NextRequest } from "next/server";import { decrypt } from "@/lib/session";const protectedPrefixes = ["/dashboard", "/settings"];const authPages = ["/login", "/signup"];export async function proxy(req: NextRequest) { const { pathname } = req.nextUrl; const session = await decrypt(req.cookies.get("session")?.value); const isProtected = protectedPrefixes.some((p) => pathname.startsWith(p)); if (isProtected && !session) { const url = new URL("/login", req.nextUrl); url.searchParams.set("next", pathname); return NextResponse.redirect(url); } if (authPages.includes(pathname) && session) { return NextResponse.redirect(new URL("/dashboard", req.nextUrl)); } return NextResponse.next();}export const config = { // Skip API routes, static files and image optimization matcher: ["/((?!api|_next/static|_next/image|.*\\.(?:png|jpg|svg|ico)$).*)"],};Because proxy also runs on prefetch requests, it must stay lightweight and must only read the cookie. When you honor the next parameter after login, validate that it is a relative path before redirecting, to avoid open-redirect bugs.
middleware.tsis the deprecated name for this file. If you are upgrading an older project, rename the file and the exported function toproxy.
Step 4: The data access layer (the check that matters)
Centralize "who is the current user?" in one place and call it from every data function. The cache function from React deduplicates calls within a single request, so verifying in many places costs one lookup.
// lib/dal.tsimport "server-only";import { cache } from "react";import { cookies } from "next/headers";import { redirect } from "next/navigation";import { decrypt } from "@/lib/session";import { db } from "@/lib/db";export const verifySession = cache(async () => { const token = (await cookies()).get("session")?.value; const session = await decrypt(token); if (!session) redirect("/login"); return session;});// Return only what the UI needs (a data transfer object), never the raw record.export const getCurrentUser = cache(async () => { const { userId } = await verifySession(); const user = await db.user.findUnique({ where: { id: userId }, select: { id: true, name: true, email: true }, }); if (!user) redirect("/login"); return user;});export async function getAllUsers() { const { role } = await verifySession(); if (role !== "admin") return null; // or throw, depending on your UX return db.user.findMany({ select: { id: true, name: true, email: true } });}Notice two habits: every function calls verifySession() itself, and it selects only the fields it needs. Returning a trimmed object prevents accidentally sending password hashes or internal flags to the client.
Step 5: Protect pages (and stream the dynamic part)
Reading cookies is request-time work, so with Cache Components the component that calls the data access layer should sit inside a <Suspense> boundary. That keeps the shell (navigation, headings) fast while the personalized part streams.
// app/dashboard/page.tsximport { Suspense } from "react";import { getCurrentUser } from "@/lib/dal";export default function DashboardPage() { return ( <> <h1>Dashboard</h1> <Suspense fallback={<p>Loading your account…</p>}> <Account /> </Suspense> </> );}async function Account() { const user = await getCurrentUser(); // redirects to /login when there is no valid session return <p>Signed in as {user.email}</p>;}Why layouts are not enough
A layout is not re-rendered on every client-side navigation between its child routes. If your only check is in the layout, a user whose session expired can navigate to a sibling page without that check running again. Do the check in each page, or, better, in the data functions those pages call.
Step 6: Protect Server Actions
A Server Action compiles to an HTTP endpoint. Anyone can call it directly, regardless of which buttons your UI shows. Verify inside the action:
// app/admin/actions.ts"use server";import { revalidatePath } from "next/cache";import { z } from "zod";import { verifySession } from "@/lib/dal";import { db } from "@/lib/db";const schema = z.object({ userId: z.string().uuid() });export async function deleteUser(formData: FormData) { const session = await verifySession(); if (session.role !== "admin") throw new Error("Forbidden"); const { userId } = schema.parse({ userId: formData.get("userId") }); await db.user.delete({ where: { id: userId } }); revalidatePath("/admin/users");}Step 7: Protect Route Handlers
Return explicit status codes instead of redirects. APIs are consumed by code, not browsers:
// app/api/me/route.tsimport { cookies } from "next/headers";import { NextResponse } from "next/server";import { decrypt } from "@/lib/session";export async function GET() { const session = await decrypt((await cookies()).get("session")?.value); if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); return NextResponse.json({ userId: session.userId, role: session.role });}Use 401 when there is no valid identity and 403 when the identity is valid but not allowed.
Common mistakes
- Relying on proxy alone. Optimistic checks are a convenience, not a security boundary.
- Checking only in the layout. Partial rendering means it may not run on every navigation.
- Unprotected Server Actions. The button is hidden, the endpoint is not.
- Trusting client state. Never decide permissions from something the client sends, like a role in a form field.
- Returning whole database rows. Use DTOs.
- Putting secrets in
NEXT_PUBLIC_variables. Those are exposed to the browser. - Open redirects from an unvalidated
nextparameter. - Long sessions with no way to revoke them. Consider database sessions, or a short-lived token plus refresh, when you need revocation.
Security considerations
- Keep
httpOnly,secureandsameSiteon the session cookie. - Rotate
SESSION_SECRETperiodically, and plan for re-login when you do. - Rate limit the login action and add lockouts or delays for repeated failures.
- Hash passwords with Argon2id or bcrypt; never store them in plain text.
- Add CSRF protection for any state-changing requests that are not Server Actions. Server Actions include built-in origin checks.
- Log authentication events, but never log secrets or tokens.
Testing
Test the layers separately so a failure points at the right one:
- Unit test
encrypt/decrypt: valid tokens round-trip, expired and tampered tokens returnnull. - Unit test DAL functions with and without a session, and with each role.
- End-to-end test (for example with Playwright): an unauthenticated visit to
/dashboardredirects to/login; a logged-in user reaches it; a non-admin cannot trigger the admin action. - Direct endpoint test: call a Server Action's route or a Route Handler without a cookie and assert the response is rejected.
Production considerations
Serve over HTTPS only, enable HSTS, set a strict Content Security Policy, and decide on a session lifetime that fits your risk. If you need instant logout across devices or admin-forced sign-out, store sessions in a database or cache and check them in verifySession instead of relying only on a stateless token.
Best practices
- Verify close to the data, and make the data access layer the single source of truth.
- Use proxy for convenience redirects only.
- Validate all inputs with a schema, including Server Action form data.
- Return minimal DTOs.
- Prefer a maintained auth library or provider as requirements grow.
Conclusion
Secure routing in Next.js is less about one clever mechanism and more about layering: a cheap optimistic check in proxy, a trusted session lookup in a data access layer, and explicit verification in every action and handler. If every path to your data goes through the same verified function, forgetting a check in the UI stops being a security problem.
Frequently asked questions
+Is checking authentication in proxy.ts enough to protect a page?
No. Proxy is good for fast, optimistic redirects based on the session cookie, but it should not be your only check. Verify the session again next to the data (in a data access layer, Server Component or Server Action), because proxy can be bypassed by misconfigured matchers and does not protect Server Actions or Route Handlers on its own.
+What happened to middleware.ts?
In current Next.js versions the middleware file convention is deprecated and renamed to proxy. The idea is the same (code that runs before a request completes) but the file is proxy.ts and the exported function is called proxy.
+Should I put auth checks in a layout?
Not as the only check. Layouts do not re-render on every navigation due to partial rendering, so a layout check can be skipped when moving between child routes. Check authorization in each page and, more importantly, in the data fetching functions.
+Where should the session cookie be stored and with which flags?
In an httpOnly cookie with Secure in production, SameSite=Lax (or Strict), and a path of /. HttpOnly keeps the token away from client-side JavaScript, which limits the impact of XSS.
+Do I need to protect Server Actions separately?
Yes. A Server Action is a public HTTP endpoint that can be called directly. Always verify the session and permissions inside the action itself, and validate its input.
+Should I build authentication myself or use a library?
For anything beyond simple needs, use an established library or hosted provider. Session management, password reset, MFA and social login have many edge cases. Understanding the building blocks, as shown here, still helps you evaluate and integrate them safely.
+How do I protect API route handlers?
Verify the session at the start of the handler, return 401 for no session and 403 for insufficient permissions, and use the same data access layer your pages use so rules live in one place.