How do you implement role-based access control in Next.js?

AdvancedNext.js interview questionBy , updated 21 November 2026

Short answer

Check roles in layers. Store the user's role in a signed session or look it up on the server, use proxy.ts (the file Next.js 16 renamed from middleware.ts) for fast, optimistic redirects, and then enforce the role again on the server wherever data is read or changed: in pages, Server Actions and Route Handlers. Hiding buttons in the UI is a convenience, never the protection.

Where the role comes from

The server must be able to trust the role, so it cannot come from anything the client can edit, such as localStorage or a plain cookie value.

  • In a signed or encrypted session. A stateless session (a JWT or an encrypted cookie) can carry the user ID and role. It is fast to check, but a role change only takes effect when the session is refreshed, so keep lifetimes short or check sensitive actions against the database.
  • Looked up on the server. Store a session ID in the cookie and read the user and role from the database. Role changes take effect immediately, at the cost of a lookup.

The Next.js docs suggest keeping the session payload minimal: the user ID and role, not personal data. The trade-offs between the two models are in session cookies vs JWT, and the vocabulary in authentication vs authorization.

Layer 1: optimistic redirects in proxy.ts

// proxy.ts
import { NextResponse, type NextRequest } from "next/server";
import { decrypt } from "@/lib/session";

export async function proxy(request: NextRequest) {
  const session = await decrypt(request.cookies.get("session")?.value);
  const path = request.nextUrl.pathname;

  if (!session?.userId) {
    return NextResponse.redirect(new URL("/login", request.url));
  }
  if (path.startsWith("/admin") && session.role !== "admin") {
    return NextResponse.redirect(new URL("/", request.url));
  }
  return NextResponse.next();
}

export const config = { matcher: ["/dashboard/:path*", "/admin/:path*"] };

This gives a good experience: a signed-out user never sees a flash of the admin page. The docs call these checks optimistic and say Proxy should not be your only line of defence, for three reasons:

  • It should only read the cookie. Proxy runs on prefetches too, so database lookups there are discouraged.
  • Coverage is fragile. A matcher that misses a path, or a Server Action that moves to another page, silently loses protection. Server Actions are POST requests to the page that uses them, so they are only covered if that page is.
  • It runs in front of the app, not where data is read. A bug or a bypass at that layer exposes everything behind it.

One case where Proxy is the right place: static pages shared between users, such as paywalled content, which are not rendered per request. More on the file itself in middleware, now called Proxy.

Layer 2: a data access layer that checks the role

Put the real check in one server-only module and call it from everything that touches protected data:

// lib/dal.ts
import "server-only";
import { cache } from "react";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { decrypt } from "@/lib/session";

export const getSession = cache(async () => {
  const session = await decrypt((await cookies()).get("session")?.value);
  if (!session?.userId) redirect("/login");
  return session; // { userId, role }
});

export async function requireRole(...roles: Role[]) {
  const session = await getSession();
  if (!roles.includes(session.role)) throw new Error("Forbidden");
  return session;
}

server-only makes the build fail if a Client Component imports this file. React's cache deduplicates the session lookup within one render pass, but not across Server Actions or Route Handlers, which are not part of a render.

Layer 3: enforce everywhere data is read or changed

Pages and components. Call the check in the page, or inside the data function, rather than only in a layout:

// app/admin/users/page.tsx
export default async function UsersPage() {
  await requireRole("admin");
  const users = await listUsers();
  return <UserTable users={users} />;
}

The docs warn about relying on layouts. A layout does not rerender on client navigation, so its check does not run on every route change. And a layout that hides children does not stop the child page from running or from appearing in the RSC payload. Put the check next to the data.

Server Actions. Treat each one as a public endpoint, since anyone can call it with a crafted POST:

"use server";
export async function deleteUser(id: string) {
  await requireRole("admin");
  await db.user.delete({ where: { id } });
}

Route Handlers. Same rule, with status codes: 401 when there is no session, 403 when the role is wrong.

export async function GET() {
  const session = await getOptionalSession(); // like getSession, but returns null instead of redirecting
  if (!session) return new Response(null, { status: 401 });
  if (session.role !== "admin") return new Response(null, { status: 403 });
  return Response.json(await listUsers());
}

forbidden() and unauthorized() from next/navigation can render a forbidden.tsx or unauthorized.tsx page, but they are experimental and need experimental.authInterrupts.

Layer 4: hide the UI

Once the server enforces access, pass the role, or better a list of permissions, to Client Components so they hide what the user cannot do. This prevents confusion, not attacks. Return only the fields the client needs (a data transfer object) so a hidden part of the UI does not still receive sensitive data.

Roles or permissions?

Check permissions (users:delete), not role names, in your code, and map roles to permissions in one place. Adding a "support" role then means editing that map, not every if. For multi-tenant apps, the check also needs the resource: "admin of which organisation?". See designing an admin console's auth and a multi-tenant dashboard with RBAC.

Common follow-up questions

Is middleware.ts still used?

It still works but is deprecated. Next.js 16 renamed it proxy.ts, exporting a function named proxy or a default export, and Proxy runs on the Node.js runtime.

Can I check roles in a Client Component?

Only for display. Client code can be changed by the user, so a client-side check protects nothing.

Should Proxy query the database for the role?

The docs advise against it, because Proxy runs on every matched request, including prefetches. Read the signed cookie there and do the database check in the data access layer.

Mistakes to avoid

  • Treating a Proxy redirect as the only authorisation check

  • Checking the role in a layout and assuming every child page is protected

  • Forgetting the check in Server Actions and Route Handlers

  • Trusting a role stored in localStorage or an unsigned cookie

  • Sending sensitive fields to the client and only hiding them in the UI

  • Scattering role-name comparisons across the codebase instead of one permission map

Practise it in code

Interviewers rarely stop at the definition. These questions open in an editor with tests.

  1. Design authentication and authorization for an internal admin consoleHard45 min
  2. Design a multi-tenant SaaS admin dashboard: RBAC, tenant isolation, white-labelling, audit logs and entitlementsHard60 min
  3. Design a CMS dashboard: real-time updates, role-based access, virtualised lists and offline edits with conflictsHard55 min
  4. Build a recursive navigation menu from config: permission filtering, disclosure groups and arrow keysMedium40 min
  5. Build login, register and a protected dashboard without a router library: AuthProvider, useAuth and redirectsMedium50 min