Centralizing Authorization with a Service Layer
Refactor scattered permission checks into a centralized service layer, add Next.js middleware guards, and build a defense-in-depth authorization architecture.
In Post 101, we diagnosed the root problems with scattered permission checks: inconsistent logic, security gaps, and maintenance overhead. The first fix is the service layer pattern: all authorization logic moves into a single layer between your application code and the database.
Next.js middleware for route protection and guards at several levels build on top of that layer. Together they form a defense-in-depth architecture: permission rules live in one layer and are enforced on every path to the data.
The Root Cause of Scattered Checks#
Post 101 showed three code examples built around one question: “can this user access this resource?” A page component, a server action, and an API route each answered it differently, and each carried a different bug. The symptoms were inconsistency, missing checks, and over-permission.
The root cause is architectural: there is no chokepoint through which all data access must pass. Pages, server actions, and API routes all access the database directly. Permission checks are optional additions to each entry point. Developers must remember to add them, and “remember” is not a security strategy.
The fix is to create that chokepoint. Instead of placing security guards at every door and hoping none are absent, funnel all traffic through a single checkpoint.
The Service Layer Pattern#
Definition#
Martin Fowler defines a Service Layer as a boundary that “establishes a set of available operations and coordinates the application’s response in each operation.” In authorization context, the service layer is the single place where permission decisions are made and enforced.
This maps directly to Next.js’s recommended Data Access Layer (DAL) pattern from the official documentation. The core idea is the same: create a server-only layer that combines three responsibilities:
- Authentication verification: is the user who they claim to be?
- Authorization checks: is this user allowed to perform this action on this resource?
- Data access and transformation: fetch the data and return only what the user should see.
Single Responsibility Principle#
A common misconception is that SRP means “one function does one thing.” It means “one module has one reason to change.” The service layer’s reason to change is when permission rules or data access patterns change. Pages change for UI reasons. Server actions change for form handling reasons. Neither should carry authorization logic.
Architecture Overview#
Key technical details:
- The
server-onlypackage prevents service layer code from being bundled into client components. Importing it in a file that gets imported by a Client Component will cause a build error. - React’s
cache()function memoizes the session verification within a single render pass. Multiple Server Components callingverifySession()share one cookie decryption and one user lookup. Outside a render, in Server Actions and Route Handlers,cache()does not deduplicate, so each call decrypts the cookie and queries the user again.
Refactoring: From Scattered Checks to Centralized Service#
Step 1: Session Verification#
The foundation is a memoized session verification utility. Every service method calls this first.
// lib/auth.ts
import 'server-only';
import { cache } from 'react';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
import { db } from '@/lib/db';
export interface SessionUser {
userId: string;
role: 'admin' | 'member'; // global role, read from the users table
}
// Memoized within a single render pass
export const verifySession = cache(async (): Promise<SessionUser | null> => {
const cookieStore = await cookies();
const token = cookieStore.get('session')?.value;
if (!token) {
return null;
}
let userId: string;
try {
const payload = await decryptAndValidate(token);
userId = payload.userId;
} catch {
return null; // Fail closed: invalid token means no session
}
// The token proves identity; the role comes from the database
const user = await db.user.findUnique({
where: { id: userId },
select: { id: true, role: true },
});
if (!user) {
return null; // Fail closed: deleted account means no session
}
return { userId: user.id, role: user.role };
});
// Convenience wrapper that redirects unauthenticated users
export const requireSession = cache(async () => {
const session = await verifySession();
if (!session) {
redirect('/login');
}
return session;
});
Two functions, two purposes. verifySession() returns null for unauthenticated requests, which suits components that render differently for logged-in and anonymous users. requireSession() redirects immediately, which suits protected pages and service methods.
Treat the cookie as proof of identity. A role stored in the token stays valid until the cookie expires, so an admin whose rights were removed would keep them for the rest of the session. Reading the role from the users table makes a role change or a deleted account take effect on the next request. Middleware may still read a role claim from the token for an early redirect, but every decision that grants access uses the database value. The cost is one extra query per request; the OWASP Authorization Cheat Sheet (opens in new tab) names the same trade-off of loading roles from the user ID on every request.
Ending the session itself early (sign out on every device, a lost laptop) needs database sessions: the browser holds only an encrypted session ID, and deleting the row ends the session. The Next.js authentication guide (opens in new tab) describes both session models.
Step 2: Custom Error Classes#
Before building services, define structured error types. These replace generic throw new Error('Unauthorized') calls with specific, catchable errors.
// lib/errors.ts
export class UnauthorizedError extends Error {
constructor(message = 'Authentication required') {
super(message);
this.name = 'UnauthorizedError';
}
}
export class ForbiddenError extends Error {
constructor(message = 'Access denied') {
super(message);
this.name = 'ForbiddenError';
}
}
export class NotFoundError extends Error {
// Use generic message to prevent resource enumeration
constructor(message = 'Resource not found or access denied') {
super(message);
this.name = 'NotFoundError';
}
}
Tip
A different message is not enough on its own. If a missing document produces a 404 and a hidden one produces a 403, the status code still tells an attacker which IDs exist. The services below throw NotFoundError in both cases. ForbiddenError is reserved for a user who can already see the resource but may not change it, so it reveals nothing new.
Step 3: DocumentService#
This is the core refactoring. Compare the scattered checks from Post 101 to the centralized service.
Before: authorization scattered in a server action (from Post 101):
// BEFORE: Permission check scattered in server action
'use server';
export async function updateDocument(
documentId: string,
content: string
) {
const session = await getSession();
const document = await db.document.findUnique({
where: { id: documentId },
});
if (document.authorId !== session.userId) {
// Bug: forgot editors can edit too
throw new Error('Unauthorized');
}
// Bug: no project membership check
await db.document.update({
where: { id: documentId },
data: { content },
});
}
After: centralized in the service layer.
The examples assume a Prisma schema with four models: users (with a global role), projects (with an owner and a visibility), project memberships (with a project role) and documents (with a status and an author). Both services need to know what role a user has inside a project, so that decision lives in one small module:
// lib/services/project-access.ts
import 'server-only';
import type { Prisma } from '@prisma/client';
import type { SessionUser } from '@/lib/auth';
export type ProjectWithMembers = Prisma.ProjectGetPayload<{
include: { members: true };
}>;
export type ProjectRole = 'owner' | 'editor' | 'author' | 'viewer';
// The one place that decides a user's role inside a project
export function projectRoleOf(
session: SessionUser,
project: ProjectWithMembers
): ProjectRole | null {
if (project.ownerId === session.userId) return 'owner';
const membership = project.members.find(
(m) => m.userId === session.userId
);
return membership?.role ?? null; // Fail closed
}
export function canAccessProject(
session: SessionUser,
project: ProjectWithMembers
): boolean {
if (session.role === 'admin') return true;
if (project.visibility === 'public') return true;
return projectRoleOf(session, project) !== null;
}
Two kinds of role are in play here. The global role (admin or member) sits on the user record and covers the whole application, such as access to the admin area. The project role (owner, editor, author, viewer) exists per project: ownership comes from project.ownerId, everything else from the membership row. A user can be an editor in one project and a viewer in the next. Document rules therefore read the global role only for the admin bypass and take everything else from projectRoleOf(). Without that split, a project owner who has no membership row could open the project but not edit its documents.
The document service builds on it:
// lib/services/document-service.ts
import 'server-only';
import { requireSession } from '@/lib/auth';
import { db } from '@/lib/db';
import { ForbiddenError, NotFoundError } from '@/lib/errors';
import { canAccessProject } from '@/lib/services/project-access';
const withProject = { project: { include: { members: true } } };
export async function getDocumentById(documentId: string) {
const session = await requireSession();
const document = await db.document.findUnique({
where: { id: documentId },
include: withProject,
});
// Missing and not allowed look the same to the caller
if (!document || !canAccessDocument(session, document)) {
throw new NotFoundError();
}
return toDocumentDTO(document, session);
}
export async function updateDocument(
documentId: string,
content: string
) {
const session = await requireSession();
const document = await db.document.findUnique({
where: { id: documentId },
include: withProject,
});
if (!document || !canAccessDocument(session, document)) {
throw new NotFoundError();
}
// The user can already see this document, so 403 leaks nothing
if (!canEditDocument(session, document)) {
throw new ForbiddenError();
}
const updated = await db.document.update({
where: { id: documentId },
data: { content },
include: withProject,
});
return toDocumentDTO(updated, session);
}
export async function listDocumentsByProject(
projectId: string,
page = { take: 20, skip: 0 }
) {
const session = await requireSession();
const project = await db.project.findUnique({
where: { id: projectId },
include: { members: true },
});
if (!project || !canAccessProject(session, project)) {
throw new NotFoundError();
}
// The database applies the rule, so take, skip and count stay correct
const where = documentAccessWhere(session, project);
const [documents, total] = await Promise.all([
db.document.findMany({
where,
orderBy: { id: 'asc' },
take: page.take,
skip: page.skip,
}),
db.document.count({ where }),
]);
return {
items: documents.map((doc) =>
toDocumentDTO({ ...doc, project }, session)
),
total,
};
}
The list method does not load every document and filter it with canAccessDocument() afterwards. That approach breaks pagination: a page of 20 rows can come back with 3, and a total taken from the unfiltered query tells the user how many hidden documents exist. It also pulls the whole project into memory. The read rule goes into the where clause instead, so the database returns only rows the user may see.
The permission logic, extracted into focused helper functions:
// Permission helpers within document-service.ts
import type { Prisma } from '@prisma/client';
import type { SessionUser } from '@/lib/auth';
import {
projectRoleOf,
type ProjectWithMembers,
} from '@/lib/services/project-access';
type DocumentWithProject = Prisma.DocumentGetPayload<{
include: { project: { include: { members: true } } };
}>;
function canAccessDocument(
session: SessionUser,
document: DocumentWithProject
): boolean {
if (session.role === 'admin') return true;
const project = document.project;
const role = projectRoleOf(session, project);
// Published documents: any project role, or anyone on a public project
if (document.status === 'published') {
return role !== null || project.visibility === 'public';
}
// Drafts: owners and editors see all of them
if (role === 'owner' || role === 'editor') return true;
// Other members see only their own drafts
return role !== null && document.authorId === session.userId;
}
function canEditDocument(
session: SessionUser,
document: DocumentWithProject
): boolean {
if (session.role === 'admin') return true;
const role = projectRoleOf(session, document.project);
// Owners and editors can edit any document in the project
if (role === 'owner' || role === 'editor') return true;
// Authors can edit their own documents
return role === 'author' && document.authorId === session.userId;
}
// The same read rule as canAccessDocument, written as a Prisma filter
function documentAccessWhere(
session: SessionUser,
project: ProjectWithMembers
): Prisma.DocumentWhereInput {
const inProject = { projectId: project.id };
if (session.role === 'admin') return inProject;
const role = projectRoleOf(session, project);
if (role === 'owner' || role === 'editor') return inProject;
if (role !== null) {
return {
...inProject,
OR: [{ status: 'published' }, { authorId: session.userId }],
};
}
if (project.visibility === 'public') {
return { ...inProject, status: 'published' };
}
return { id: { in: [] } }; // Fail closed: matches no rows
}
documentAccessWhere() states the read rule a second time. canAccessDocument() judges one row in memory; documentAccessWhere() asks the database for every row that passes. Both call projectRoleOf(), so ownership and membership are decided once. The draft and publish conditions, however, now exist in two places. If a change reaches only one of them, a list shows documents the detail page refuses, or hides documents the user can open. Keep the two functions next to each other and run them against the same test fixtures. Post 105 removes this duplication by deriving the query filter from the same condition definition.
Notice the pattern. Every service method follows the same structure:
- Verify the session
- Fetch the resource with related data
- Check authorization (for lists, inside the query itself)
- Return a filtered DTO
Step 4: ProjectService#
The same pattern applies to projects. One service file per resource type keeps the codebase organized.
// lib/services/project-service.ts
import 'server-only';
import { requireSession } from '@/lib/auth';
import { db } from '@/lib/db';
import { NotFoundError } from '@/lib/errors';
import { canAccessProject } from '@/lib/services/project-access';
export async function getProjectById(projectId: string) {
const session = await requireSession();
const project = await db.project.findUnique({
where: { id: projectId },
include: { members: true },
});
if (!project || !canAccessProject(session, project)) {
throw new NotFoundError();
}
return toProjectDTO(project, session);
}
export async function listProjectsForUser() {
const session = await requireSession();
if (session.role === 'admin') {
const projects = await db.project.findMany({
include: { members: true },
});
return projects.map((p) => toProjectDTO(p, session));
}
const projects = await db.project.findMany({
where: {
OR: [
{ visibility: 'public' },
{ members: { some: { userId: session.userId } } },
{ ownerId: session.userId },
],
},
include: { members: true },
});
return projects.map((p) => toProjectDTO(p, session));
}
listProjectsForUser() already filters in the where clause. Its OR list mirrors canAccessProject() (public, member, owner), so it carries the same drift risk as the document filter.
Step 5: DTO Pattern for Safe Data Transfer#
Raw database objects contain fields that should not reach the client. Internal IDs, timestamps, soft-delete flags, and metadata intended for other roles all leak when you return the database model directly.
The DTO (Data Transfer Object) pattern solves this. Each service method returns a filtered object based on the user’s role.
// lib/services/document-service.ts
interface DocumentDTO {
id: string;
title: string;
content: string;
status: string;
projectId: string;
authorId: string;
viewerRole: ProjectRole | null; // the reader's own project role
reviewComments?: string[];
}
function toDocumentDTO(
document: DocumentWithProject,
session: SessionUser
): DocumentDTO {
const role = projectRoleOf(session, document.project);
const base: DocumentDTO = {
id: document.id,
title: document.title,
content: document.content,
status: document.status,
projectId: document.projectId,
authorId: document.authorId,
viewerRole: role,
};
// Admins, owners and editors see review metadata
if (
session.role === 'admin' ||
role === 'owner' ||
role === 'editor'
) {
return {
...base,
reviewComments: document.reviewComments,
};
}
return base;
}
This solves the over-permission problem from Post 101. A viewer gets title and content. An editor or the project owner also gets review comments. The same resource, different views, all controlled in one place. The viewerRole field tells the UI which project role the reader holds, which the component guard below relies on.
Step 6: Thin Server Actions#
With the service layer in place, server actions become thin wrappers. They handle form data, call the service, and do nothing else.
// app/actions/documents.ts
'use server';
import { updateDocument } from '@/lib/services/document-service';
export async function updateDocumentAction(
documentId: string,
content: string
) {
// All authorization happens inside the service
return updateDocument(documentId, content);
}
Compare this to the buggy server action from Post 101. The action contains no permission logic; every decision happens in the service layer. Its arguments are still untrusted. An exported server action can be called with a direct POST request, so the action guard further down adds schema validation in front of the service call.
Next.js Middleware for Route Protection#
Note
In Next.js 16, middleware.ts has been renamed to proxy.ts and the exported function to proxy. The patterns and concepts in this section apply to both. If you are on Next.js 15 or earlier, use middleware.ts.
What Middleware Should Do#
Middleware runs before every matched request. It is fast and has access to cookies and headers. This makes it suited for one job: optimistic authentication checks.
- Check if a session cookie exists
- Redirect unauthenticated users away from protected routes
- Check coarse-grained role claims from the session token (like “is this user an admin?”)
- Act as the first layer of defense, ahead of the definitive check in the service layer
What Middleware Should NOT Do#
- Be the sole authorization mechanism (CVE-2025-29927 demonstrated why)
- Query the database for permission checks (a performance concern, since it runs on every request)
- Perform resource-level authorization (middleware has no resource context: it does not know which document the user is trying to access)
Implementation#
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { decrypt } from '@/lib/session';
const publicRoutes = ['/', '/login', '/signup'];
const adminRoutes = ['/admin'];
export async function middleware(request: NextRequest) {
const path = request.nextUrl.pathname;
// Allow public routes without authentication
if (publicRoutes.some((route) => path === route)) {
return NextResponse.next();
}
// Check session cookie (optimistic, no DB call)
const cookie = request.cookies.get('session')?.value;
const session = await decrypt(cookie);
if (!session?.userId) {
return NextResponse.redirect(
new URL('/login', request.url)
);
}
// Admin routes: check role from session token
if (adminRoutes.some((route) => path.startsWith(route))) {
if (session.role !== 'admin') {
return NextResponse.redirect(
new URL('/', request.url)
);
}
}
return NextResponse.next();
}
export const config = {
matcher: [
'/((?!api|_next/static|_next/image|.*\\.png$).*)',
],
};
This middleware is intentionally simple: it checks cookie presence and session validity, without querying the database or performing resource-level authorization. Those responsibilities belong to the service layer. The role claim it reads can be stale, as Step 1 explains, so the admin redirect only spares a round trip for most non-admins. The admin pages still call the service layer, which reads the role from the database.
API Routes and the Matcher#
The matcher is the one from the Next.js authentication guide (opens in new tab), and it excludes every path that starts with api. Excluding API paths keeps each response right for its client: a redirect to /login suits a browser page, but an API client expects a 401 status. The consequence is that Route Handlers get no Layer 1 check at all, so each one checks the session itself and maps service errors to status codes:
// app/api/projects/[id]/route.ts
import { verifySession } from '@/lib/auth';
import { NotFoundError } from '@/lib/errors';
import { getProjectById } from '@/lib/services/project-service';
export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
// The matcher skips /api: answer 401 here instead of a login redirect
if (!(await verifySession())) {
return new Response(null, { status: 401 });
}
const { id } = await params;
try {
return Response.json(await getProjectById(id));
} catch (error) {
if (error instanceof NotFoundError) {
return new Response(null, { status: 404 });
}
throw error;
}
}
The other option is to keep /api in the matcher and return a 401 response for those paths inside the middleware. The same guide recommends running the proxy on all routes for auth. Either way, the Route Handler still calls the service layer, which makes the final decision.
Defense in Depth#
No single layer is sufficient. Each layer covers for potential failures in the others.
- Layer 1 (Middleware): Fast rejection of obviously unauthenticated page and server action requests. Optimistic check based on session cookies. API routes fall outside the matcher and check the session themselves.
- Layer 2 (Service Layer): Definitive authorization with full resource context. Checks user identity, role, project membership, and document ownership.
- Layer 3 (Database): Constraints like foreign keys and row-level security policies (the BOLA post covers PostgreSQL RLS in practice) provide a final safety net.
If middleware is bypassed (as in CVE-2025-29927), the service layer still blocks unauthorized access. If a service layer bug grants access to the wrong resource, database constraints can catch the inconsistency. Each layer independently provides protection.
Guard Patterns#
Route-Level Guards (Middleware)#
Already covered above. Middleware redirects unauthenticated users before the page renders. This is coarse-grained: “Is the user logged in?” and “Is this a protected route?”
Page-Level Guards (Server Components)#
Page components call service methods directly. The service handles authentication, authorization, and data access in one call. A small helper turns the service errors into the matching Next.js error pages:
// lib/page-errors.ts
import 'server-only';
import { forbidden, notFound } from 'next/navigation';
import { ForbiddenError, NotFoundError } from '@/lib/errors';
// Turns service errors into Next.js 404 and 403 pages
export async function orErrorPage<T>(promise: Promise<T>): Promise<T> {
try {
return await promise;
} catch (error) {
if (error instanceof NotFoundError) notFound();
if (error instanceof ForbiddenError) forbidden();
throw error; // Includes the redirect thrown by requireSession()
}
}
notFound() renders the nearest not-found file, with a 404 status when it runs before the response starts streaming. forbidden() does the same with the forbidden file and a 403, but it is experimental (added in Next.js 15.1) and needs experimental.authInterrupts: true in next.config.ts. Without that flag, drop the forbidden() line and let error.tsx handle ForbiddenError. Every other error is rethrown, which matters because redirect() also works by throwing.
// app/projects/[id]/page.tsx
import { orErrorPage } from '@/lib/page-errors';
import { getProjectById } from '@/lib/services/project-service';
export default async function ProjectPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
// Service handles: session + authorization + data access
const project = await orErrorPage(getProjectById(id));
return <ProjectView project={project} />;
}
Compare this to Post 101’s version, where the page component contained all the permission logic inline. The page is now thin: it calls the service and renders the result. If the user cannot access this project, the service throws NotFoundError and the visitor sees the same 404 page as for a project that does not exist.
Component-Level Guards (Conditional Rendering)#
Server Components can call verifySession() and conditionally render based on role. This serves UI/UX purposes only. The security boundary stays in the service layer.
// components/document-actions.tsx
import { verifySession } from '@/lib/auth';
export async function DocumentActions({
document,
}: {
document: DocumentDTO;
}) {
const session = await verifySession();
if (!session) return null;
// Global role only for the admin bypass, project role for the rest
const canEdit =
session.role === 'admin' ||
document.viewerRole === 'owner' ||
document.viewerRole === 'editor' ||
(document.viewerRole === 'author' &&
document.authorId === session.userId);
return (
<div>
{canEdit && <EditButton documentId={document.id} />}
{session.role === 'admin' && (
<DeleteButton documentId={document.id} />
)}
</div>
);
}
Warning
This component-level check copies the rule from canEditDocument(). If the edit permission rule changes in the service, it must also change here. This duplication is a known limitation of the current approach. Post 103 (RBAC) solves this by making permission rules queryable from a single source.
Server Action Guards (Higher-Order Wrapper)#
A withAuth higher-order function wraps server actions with authentication and input validation. Every action verifies the session and parses its input before the body runs. The examples use Zod 4 (import * as z from 'zod', as in the Next.js authentication guide).
// lib/action-guard.ts
import 'server-only';
import * as z from 'zod';
import { requireSession, type SessionUser } from '@/lib/auth';
export function withAuth<TSchema extends z.ZodType, TOutput>(
schema: TSchema,
action: (
session: SessionUser,
input: z.infer<TSchema>
) => Promise<TOutput>
) {
// The argument comes from an HTTP request: treat it as unknown
return async (input: unknown): Promise<TOutput> => {
const session = await requireSession();
const parsed = schema.parse(input); // Throws a ZodError on bad input
return action(session, parsed);
};
}
Usage in a server action:
// app/actions/documents.ts
'use server';
import * as z from 'zod';
import { withAuth } from '@/lib/action-guard';
import { updateDocument } from '@/lib/services/document-service';
const UpdateDocumentInput = z.object({
documentId: z.uuid(),
content: z.string().max(100_000),
});
export const updateDocumentAction = withAuth(
UpdateDocumentInput,
async (_session, input) => {
return updateDocument(input.documentId, input.content);
}
);
The Next.js data security guide (opens in new tab) states that an exported Server Action is reachable via a direct POST request, not only through the UI. TypeScript types do not exist at runtime, so a documentId: string signature stops nothing: a caller can send a number, an object or a very large string. The schema rejects those before the service runs. The limits here (UUID primary keys, 100,000 characters of content) are examples; use the formats and sizes of your own data. The session check runs first, so an anonymous caller is redirected before the schema runs. parse() throws on invalid input; for form feedback, use safeParse() and return the field errors, as the Next.js authentication guide does.
The withAuth wrapper guarantees the session exists and the input has the expected shape before the action body runs. Combined with authorization inside the service method, this provides two layers of protection for every server action.
Testability#
One of the biggest wins of the service layer is testability. Permission logic is isolated from rendering, routing, and request handling. Tests have clear inputs and outputs.
// __tests__/services/document-service.test.ts
import {
getDocumentById,
updateDocument,
} from '@/lib/services/document-service';
import { ForbiddenError, NotFoundError } from '@/lib/errors';
const mockRequireSession = jest.fn();
const mockFindUnique = jest.fn();
const mockUpdate = jest.fn();
jest.mock('server-only', () => ({}));
jest.mock('@/lib/auth', () => ({
requireSession: () => mockRequireSession(),
}));
jest.mock('@/lib/db', () => ({
db: {
document: {
findUnique: (args: unknown) => mockFindUnique(args),
update: (args: unknown) => mockUpdate(args),
},
},
}));
type Member = { userId: string; role: 'editor' | 'author' | 'viewer' };
function mockSession(userId: string, role: 'admin' | 'member' = 'member') {
mockRequireSession.mockResolvedValue({ userId, role });
}
function mockDocument(doc: {
status: 'draft' | 'published';
authorId?: string;
ownerId?: string;
members?: Member[];
}) {
const row = {
id: 'doc-1',
title: 'Spec',
content: 'Body',
reviewComments: [],
projectId: 'project-a',
status: doc.status,
authorId: doc.authorId ?? 'author-1',
project: {
id: 'project-a',
ownerId: doc.ownerId ?? 'owner-1',
visibility: 'private',
members: doc.members ?? [],
},
};
mockFindUnique.mockResolvedValue(row);
mockUpdate.mockResolvedValue(row);
}
describe('getDocumentById', () => {
it('allows admin to read a draft without membership', async () => {
mockSession('admin-1', 'admin');
mockDocument({ status: 'draft' });
const result = await getDocumentById('doc-1');
expect(result.id).toBe('doc-1');
});
it('lets a viewer member read a published document', async () => {
mockSession('viewer-1');
mockDocument({
status: 'published',
members: [{ userId: 'viewer-1', role: 'viewer' }],
});
const result = await getDocumentById('doc-1');
expect(result.id).toBe('doc-1');
});
it('hides a draft from a viewer member', async () => {
mockSession('viewer-1');
mockDocument({
status: 'draft',
members: [{ userId: 'viewer-1', role: 'viewer' }],
});
await expect(
getDocumentById('doc-1')
).rejects.toThrow(NotFoundError);
});
it('allows an author to read their own draft', async () => {
mockSession('author-1');
mockDocument({
status: 'draft',
authorId: 'author-1',
members: [{ userId: 'author-1', role: 'author' }],
});
const result = await getDocumentById('doc-1');
expect(result.id).toBe('doc-1');
});
it('hides a document from a user with no role in its project', async () => {
mockSession('editor-b');
mockDocument({
status: 'published',
members: [{ userId: 'editor-a', role: 'editor' }],
});
await expect(
getDocumentById('doc-1')
).rejects.toThrow(NotFoundError);
});
});
describe('updateDocument', () => {
it('lets the project owner edit without a membership row', async () => {
mockSession('owner-1');
mockDocument({ status: 'draft', ownerId: 'owner-1' });
const result = await updateDocument('doc-1', 'New body');
expect(result.id).toBe('doc-1');
});
it('rejects a viewer who can read the document', async () => {
mockSession('viewer-1');
mockDocument({
status: 'published',
members: [{ userId: 'viewer-1', role: 'viewer' }],
});
await expect(
updateDocument('doc-1', 'New body')
).rejects.toThrow(ForbiddenError);
});
});
The helpers are plain functions over jest.fn() mocks: mockSession() sets what requireSession() returns, and mockDocument() sets the row the Prisma client returns. server-only is mocked because the real package throws when it is imported outside a Server Component build, which includes Jest.
Each test sets the project membership explicitly, so it fails for the rule in its name. The two viewer tests differ only in the document status. If the draft rule broke, the draft test would stop throwing; without the membership row, it would pass even with a broken draft rule, because a non-member is rejected anyway. The owner test covers an owner with no membership row, and the no-role test puts another user in the project as editor and checks that a user without a row in this project gets nothing. A role held in another project never reaches projectRoleOf(), because it only reads this project’s members.
Each test answers one question: “Given user X with project role Y accessing document Z, expect allow or deny.” No page rendering, request context or form handling is involved.
Compare this to testing scattered checks. You would need to render pages, call server actions with full request contexts, and set up authentication middleware. The service layer makes the most critical logic, permissions, the easiest to test.
Benefits and Limitations#
What the Service Layer Solves#
| Post 101 Problem | Service Layer Solution |
|---|---|
| Scattered checks in 3+ locations | Single location per resource operation |
| Inconsistent logic across layers | One implementation, called everywhere |
| Missing checks on new endpoints | New endpoints must call service methods |
| Over-permission (returning too much data) | DTO pattern filters data by role |
| Difficult to test permission logic | Service methods are independently testable |
| No single source of truth | Service layer IS the source of truth |
What Remains Unsolved#
The service layer solves where permission checks happen. But the permission rules themselves are still hardcoded if/else statements. This creates several limitations:
- Hardcoded role checks: Permission logic is
if (role === 'admin')inside service methods. Adding a new role requires modifying every relevant service method. - No permission matrix: There is no declarative, inspectable list of “role X can do action Y on resource Z.” Permission rules are embedded in code logic.
- Duplicated rule copies: UI guard checks and the list query filter restate the service layer’s rules. Keeping them in sync is manual and error-prone.
- Role changes require code changes: Adding a “moderator” role that can publish but not delete requires touching multiple service methods.
- No audit trail: The service layer enforces permissions but does not log who accessed what and when.
These limitations point directly to the next step: replacing hardcoded if/else with a structured permission system.
Common Pitfalls#
-
“Just this once” database bypass: Every direct database access outside the service layer is a potential authorization gap. Enforce the pattern through code review and consider a custom ESLint rule that flags direct database imports outside service files.
-
Forgetting
server-only: Without this import, service layer code could be imported by a Client Component. This exposes internal logic and database access patterns to the client bundle. -
Skipping
cache()for session verification:verifySession()decrypts the cookie and queries theuserstable. Without memoization, a page and three child Server Components that each call it repeat that work four times in one render. The result is unnecessary repeated work; what the user can see does not change. -
Returning raw database objects: Always return DTOs from service methods. Raw objects may contain timestamps, soft-delete flags, or internal fields that should not reach the client.
-
Error responses that leak resource existence: a 404 for a missing document and a 403 for a hidden one tell an attacker which IDs exist, whatever the message says. Throw the same
NotFoundErrorfor both, and keepForbiddenErrorfor users who can already see the resource.
What’s Next#
In Post 103, we introduce Role-Based Access Control (RBAC). Instead of hardcoded conditionals, permission rules become data: a structured matrix that both the service layer and UI can query.
// Preview: full implementation in Post 103
// Instead of:
if (role === 'admin' || role === 'editor') {
// allow edit
}
// We'll use the role this user holds in this project:
const role = effectiveRole(session, project);
if (role !== null && can(role, 'document', 'update')) {
// allow edit
}
The service layer remains; only the internals of the permission checks change.
References#
- Martin Fowler - Service Layer (opens in new tab) - The foundational definition of the Service Layer pattern from Patterns of Enterprise Application Architecture
- Next.js Authentication Guide (Official) (opens in new tab) - Official Next.js documentation covering the Data Access Layer pattern,
verifySession()withcache(), and DTO recommendations - Next.js Data Security Guide (Official) (opens in new tab) - Official documentation on
server-only, DTO patterns, React Taint APIs, and the three data fetching approaches - How to Think About Security in Next.js (Official Blog) (opens in new tab) - Next.js team guidance on the security model for Server Components and Server Actions
- CVE-2025-29927: Next.js Middleware Authorization Bypass (opens in new tab) - Technical analysis of the CVSS 9.1 vulnerability demonstrating why middleware must not be the sole authorization layer
- OWASP Authorization Cheat Sheet (opens in new tab) - Best practices for centralized authorization logic and defense-in-depth
- OWASP Fail Securely (opens in new tab) - Why security methods should return false on exception and the fail-closed principle
- Defense in Depth (Cloudflare) (opens in new tab) - Explanation of the layered security model behind the middleware, service, and database split
- Authorization in Next.js - Robin Wieruch (opens in new tab) - Comprehensive guide to layered authorization in Next.js App Router
- Next.js Server Actions Security - MakerKit (opens in new tab) - Guide covering Server Action vulnerabilities and the
next-safe-actionmiddleware composition pattern - Understanding the Data Access Layer in Next.js (opens in new tab) - Practical breakdown of the DAL pattern including
server-onlyusage andcache()for request deduplication
Permission Systems that Scale
Part 2 of 6A comprehensive guide to building scalable permission systems in TypeScript and Next.js, progressing from naive checks through RBAC and ABAC to production-grade multi-tenant authorization.
All posts in this series
Related posts
Authentication vs authorization, common permission pitfalls, the fail-closed principle, and the goals every permission system should meet.
typescript · nextjs · authorization +2
Build a type-safe RBAC system in TypeScript, create a unified can() function, sync permissions across UI and backend, and learn when RBAC reaches its limits.
typescript · nextjs · authorization +2
Build an ABAC policy engine in TypeScript with the builder pattern, conditional permissions, and type-safe policy evaluation that replaces RBAC's limitations.
typescript · nextjs · authorization +2
Extend ABAC with environment-based rules, field-level read and write permissions, and automatic database query filtering that eliminates duplicate permission logic.
typescript · nextjs · authorization +2
Add multi-tenant isolation to your permission system, evaluate CASL as a library alternative, and use decision frameworks to choose the right authorization architecture.
typescript · nextjs · authorization +3