Protecting routes and data
Where to put auth checks in Next.js 16: a proxy for fast optimistic redirects, a data access layer for real checks, and a check inside every Server Action.
Protecting routes and data
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- There are two kinds of check: optimistic (read the session from the cookie, fast, fine for redirects and showing or hiding UI) and secure (check against the database, for sensitive data and actions).
- A proxy is a good place for optimistic checks and for protecting static routes, but the docs say it should not be your only line of defense; do the real checks as close to the data as possible.
- A data access layer is one server-only module whose functions verify the session before touching data, so no caller can forget the check; return a narrow DTO, not whole database rows.
- Do not rely on a layout for auth: layouts do not re-render on navigation, and hiding children does not stop route segments or Server Actions from being reached.
- Treat Server Actions and route handlers like public API endpoints: verify the session and role inside each one, and return 401 for no session and 403 for no permission.
A session is not a permission
You can now tell who is making a request. The question left is what they may get. Authorization is easy to get wrong in Next.js for a structural reason: there are many ways into your data. A page render, a Server Action, a route handler, a prefetch, a nested route segment. A check on one door does not close the others.
The docs describe two kinds of check, and most of the confusion goes away once you separate them.
- Optimistic checks use the session data in the cookie. They are fast, and good for redirecting users or showing and hiding UI based on a role.
- Secure checks use session data from the database. They cost more and are used before sensitive data or actions.
Both are worth having. They just have different homes.
Layer one: the proxy, for optimistic redirects
The proxy sees every matched request before routing. That makes it a convenient place to pre-filter: logged-out users hitting /dashboard get sent to /login without any page code running. The docs also point out that it is the right tool for static routes that share data between users, such as paywalled content, because a data access layer only runs at request time and static data is fetched at build time.
// proxy.ts
import { NextRequest, NextResponse } from 'next/server'
import { decrypt } from '@/app/lib/session'
import { cookies } from 'next/headers'
const protectedRoutes = ['/dashboard']
const publicRoutes = ['/login', '/signup', '/']
export default async function proxy(req: NextRequest) {
const path = req.nextUrl.pathname
const isProtectedRoute = protectedRoutes.includes(path)
const isPublicRoute = publicRoutes.includes(path)
const cookie = (await cookies()).get('session')?.value
const session = await decrypt(cookie)
if (isProtectedRoute && !session?.userId) {
return NextResponse.redirect(new URL('/login', req.nextUrl))
}
if (
isPublicRoute &&
session?.userId &&
!req.nextUrl.pathname.startsWith('/dashboard')
) {
return NextResponse.redirect(new URL('/dashboard', req.nextUrl))
}
return NextResponse.next()
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
}
Two constraints from the docs. Because proxy runs on every route, including prefetched ones, only read the cookie there and avoid database checks. And proxy uses the Node.js runtime, so check that your session library works with it.
The docs then say the important thing plainly: while the proxy is useful for initial checks, it should not be your only line of defense. Most checks belong as close to the data source as possible. A cookie that decodes is not proof that the user is still allowed to do this particular thing.
Layer two: a data access layer
A data access layer, or DAL, is one module that every data read goes through, and its functions check the session first. If the check lives with the data, a developer adding a new page cannot forget it.
// app/lib/dal.ts
import 'server-only'
import { cache } from 'react'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { decrypt } from '@/app/lib/session'
export const verifySession = cache(async () => {
const cookie = (await cookies()).get('session')?.value
const session = await decrypt(cookie)
if (!session?.userId) {
redirect('/login')
}
return { isAuth: true, userId: session.userId }
})
server-only makes the build fail if client code imports this file. React’s cache memoizes the result during one render pass, so ten components calling verifySession() run it once. The docs add a caution: Server Actions and route handlers are not part of a render pass, so there the wrapper does nothing and every call runs.
Build data functions on top, and return only what the caller needs:
export const getUser = cache(async () => {
const session = await verifySession()
if (!session) return null
const data = await db.query.users.findMany({
where: eq(users.id, session.userId),
// Explicitly return the columns you need rather than the whole user object
columns: { id: true, name: true, email: true },
})
return data[0]
})
That is the idea behind a data transfer object (DTO): return the fields that are safe to expose, not a whole row that also carries a password hash or phone number. The docs’ longer example filters fields by who is asking.
For a secure check you compare the session ID with the database. The reading side of this is in querying a database directly.
Using it in pages and components
Call the DAL where the data is used.
// app/dashboard/page.tsx
import { verifySession } from '@/app/lib/dal'
export default async function DashboardPage() {
const session = await verifySession()
const user = await getUserData(session.userId)
return <h1>Welcome, {user.name}</h1>
}
A leaf component can check too, such as an AdminActions that returns null unless the role is admin. Client Components cannot import the DAL. Run verifySession() in a parent Server Component and pass the result down as props or through a context provider, and the docs point to React’s taintUniqueValue API to keep sensitive session fields from reaching the client. Passing server data into client components is covered in composing Server and Client Components.
Do not put the check in a layout
A shared layout looks like the obvious spot, since it wraps everything. The docs list two reasons not to.
First, partial rendering: layouts do not re-render on navigation, so the session is not checked on every route change. Second, a layout does not control whether the rest of the route renders. Route segments and parallel route slots are rendered by the router, so a layout that hides or swaps them does not stop them running or appearing in the RSC payload. The docs call the single-page-app habit of returning null from a layout when unauthorized not recommended, because Next.js has multiple entry points. Do the check close to the data.
A layout can still fetch the user for a nav bar. Fetch through getUser(), which checks inside the DAL. With streaming, a top-level await on cookies() or the DAL in a layout holds {children} behind it, so push the read into a nested Server Component wrapped in <Suspense>; see loading UI and streaming.
Server Actions and route handlers are public endpoints
The docs say to treat both with the same security considerations as public-facing API endpoints.
'use server'
import { verifySession } from '@/app/lib/dal'
export async function serverAction(formData: FormData) {
const session = await verifySession()
const userRole = session?.role
if (userRole !== 'admin') {
return null
}
// Proceed with the action for authorized users
}
// app/api/route.ts
export async function GET() {
const session = await verifySession()
if (!session) {
return new Response(null, { status: 401 })
}
if (session?.role !== 'admin') {
return new Response(null, { status: 403 })
}
// Continue for authorized users
}
401 means no valid identity, 403 means identity known and not allowed. The proxy lesson explains why an action cannot lean on a matcher: Server Actions are POST requests to the route where they are used, and are not covered separately. Hiding a button in the UI is a convenience, not a control.
forbidden and unauthorized
Next.js has forbidden() and unauthorized() functions and matching forbidden.tsx and unauthorized.tsx files, to render a 403 or 401 page from a Server Component or action. As of the docs we read, they are experimental, “not recommended for production”, and need experimental: { authInterrupts: true } in next.config. forbidden() cannot be called in the root layout, and it throws, so a surrounding try/catch swallows it. If you are not ready to depend on an experimental API, redirect('/login') and a plain 403 page do the job.
With Cache Components
Per the docs’ separate guide, a session read is request-time data, so authenticated UI sits behind <Suspense> and streams in, while public parts stay in the static shell. A plain use cache function cannot call cookies(); the guide shows use cache: private for the current-user read, and for cached per-user data it resolves the user first and passes only the id into the cached function, which stays unexported. Keep secrets and sensitive data out of cache keys and tags, which are stored in plain text.
What the video covers
Tobi Mey’s video, from February 2026 and about seven and a half minutes, is titled “Where to put AUTH in Next.js 16?”. By its title and the notes recorded when it was sourced, it contrasts optimistic proxy checks with a data access layer. We could not read a transcript, so any detail beyond that is from the docs above. It is short, from a small channel, and the best fit we found for 16. The longer runner-up from ByteGrad (October 2025, about 23 minutes) covers proxy against data access layer with pitfalls; its description discloses a Kinde sponsorship and Kinde is the example auth provider.
Where this fits
You have hand-rolled sessions and checks. Next: Auth.js and auth libraries, which package this work. After that, security headers and CSP.
Check yourself
What is the difference between an optimistic and a secure auth check?
An optimistic check reads the session from the cookie, so it is quick and good for redirects and showing or hiding UI. A secure check uses session data from the database, so it costs more but is what you need before returning sensitive data or performing a sensitive action.
Why should a proxy only read the cookie and not query a database?
Proxy runs on every matched request, including prefetched routes, so a database call there causes performance problems. That is why the docs limit it to optimistic checks.
A layout checks the session and returns null for logged-out users. Why is that not enough?
Layouts do not re-render on every navigation, so the check may not run for each route change, and Next.js apps have multiple entry points. Returning null in a layout does not stop nested route segments or Server Actions from being reached. Put the check next to the data.
What does `import 'server-only'` in a data access layer file protect against?
It makes the build fail if the module is imported into client code, so session and database logic cannot end up in the browser bundle.
A Server Action is only rendered inside a page that already redirects logged-out users. Does the action still need its own check?
Yes. Server Actions are reachable as POST requests, so the docs say to treat them like public endpoints and verify the session and role inside the action. A matcher or page check does not cover them.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.