Sign in to AgendaViva as [email protected] and type /dashboard in the address bar. You can create events. The application knows perfectly well who you are and hasn't asked itself whether you should.
It's the most common flaw in web applications, and in one with Server Components it has more ways to slip in: a layout that looks like it protects and doesn't, a parallel slot that renders even if it isn't shown, a Server Action nobody remembers is public. The solution isn't to put checks in more places, but in the place everything goes through: the functions that read and write data. In this lesson you'll turn lib/data/ into a layer that can't be misused by accident, you'll decide what each screen does when permission is missing and you'll build the administrator's event review.
- The rules
Before the code, the table. If it can't be written down, it can't be checked:
| Operation | No session | visitor | organizer | admin |
|---|---|---|---|---|
| View published and canceled events | Yes | Yes | Yes | Yes |
| Book, and view and cancel their own bookings | No | Yes | Yes | Yes |
| Create events | No | No | Yes | No |
| View and edit their own drafts and events in review | No | No | Yes | No |
| View everyone's events in review | No | No | No | Yes |
| Publish them or send them back | No | No | No | Yes |
There are two kinds of condition. The role depends only on the person. Ownership depends on the person and the data: "their" bookings, "their" events. The first is the one everybody checks; the second, the one that gets forgotten. When it's missing, changing an identifier is enough to touch someone else's data: it's called Insecure Direct Object Reference (IDOR).
The administration doesn't have permission for everything. Publishing means reviewing someone else's work, and whoever reviews doesn't edit: if the event is wrong, they send it back. Giving a role every permission "just in case" turns its account into the only target that matters.
- Where checking isn't enough
| Place | Why it isn't enough |
|---|---|
| Hiding the button | The action is still an endpoint (06-01) |
| The layout | It isn't rendered again when navigating between its pages, and it doesn't decide whether the page runs: the two are rendered separately and the output travels in the payload |
| The conditional parallel slot | They're all rendered, whether shown or not (02-05) |
| The page | Its Server Actions are independent entry points: checking when rendering the form doesn't check when receiving it |
| The proxy | It doesn't know whose event it is; an action that changes page no longer goes through it; and there have already been ways to bypass it (07-02) |
| The client | It runs on the attacker's machine |
Each one has its role in showing things. None of them is a barrier. The barrier sits next to the query: whatever happens further up, whoever isn't allowed doesn't get the data or change it.
- One question, three ways to answer
There's a single check. What changes is what's best to do when it fails: in a page, send the person elsewhere; in an action, reply without losing what was typed; in the data layer, stop.
// lib/authorization.ts
import 'server-only'
import { notFound, redirect } from 'next/navigation'
import { signInPath } from '@/lib/destination'
import { getCurrentUser } from '@/lib/session'
import { ROLES, type Role, type SessionUser } from '@/lib/types'
export type DenialReason = 'no-session' | 'no-permission'
export const DENIAL_MESSAGES: Record<DenialReason, string> = {
'no-session': 'Your session has ended. Sign in in another tab and submit again.',
'no-permission': "You don't have permission to do this.",
}
export type Permission =
| { granted: true; user: SessionUser }
| { granted: false; reason: DenialReason }
// For Server Actions and Route Handlers: reports
export async function checkRole(...roles: Role[]): Promise<Permission> {
const user = await getCurrentUser()
if (!user) return { granted: false, reason: 'no-session' }
if (!roles.includes(user.role)) return { granted: false, reason: 'no-permission' }
return { granted: true, user }
}
// For the data layer: stops
export class AccessError extends Error {
constructor(readonly reason: DenialReason) {
super(`Access denied: ${reason}`)
this.name = 'AccessError'
}
}
export async function ensureRole(...roles: Role[]): Promise<SessionUser> {
const permission = await checkRole(...roles)
if (!permission.granted) throw new AccessError(permission.reason)
return permission.user
}
export function ensureUser(): Promise<SessionUser> {
return ensureRole(...ROLES)
}
// For pages: redirects or responds "not found"
export async function requireRole(returnTo: string, ...roles: Role[]): Promise<SessionUser> {
const permission = await checkRole(...roles)
if (permission.granted) return permission.user
if (permission.reason === 'no-session') redirect(signInPath(returnTo))
notFound()
}- The role is read from the database on every request, because that's what
getCurrentUserdoes. Taking someone's role away takes effect on their next click. - With a session and no permission,
notFound. Redirecting to/sign-inwould create a loop: that page sees there's a session and sends the person back to where they wanted to go. And a 404 doesn't confirm that a dashboard exists. - With no arguments, nobody.
checkRole()with an empty list denies. Usage mistakes should fail on the safe side. redirectandnotFounddon't go in the data layer. They're screen decisions, and in an action atry/catchwould swallow them.
requireUser, from 08-02, stays for pages that accept any role.
3.1. What about unauthorized and forbidden?
Next.js has two sibling functions of notFound: unauthorized() (401) and forbidden() (403), with their unauthorized.tsx and forbidden.tsx files. They express the intent better, but they're still experimental, they require experimental.authInterrupts and the documentation doesn't recommend them in production. Besides, with Cache Components the check happens after the shell and the status is already 200, just like with notFound (02-04). If they're ever stabilized, two lines of requireRole will change.
- The data access layer
The documentation calls a set of modules that meet three conditions a Data Access Layer (DAL): they only run on the server, they check permission and they return minimal objects. lib/data/ has met the first since 03-05. The second requires a change in the signatures.
Until now, the dashboard functions received the identifier of whoever was asking: listDashboardEvents(organizerId). It's an invitation to error: it works with any text, and a page can pass it whatever comes from the URL. From today, the function finds out for itself who's asking. The parameter disappears, and with it the possibility of getting it wrong.
// lib/data/dashboard.ts
import 'server-only'
import { and, asc, eq, inArray, sql } from 'drizzle-orm'
import { ensureRole } from '@/lib/authorization'
import { getDb } from '@/lib/db/client'
import { events } from '@/lib/db/schema'
import { EDITABLE_STATUSES, type EventData, type EditableStatus, type AgendaEvent } from '@/lib/types'
export type DashboardEvent = Pick<
AgendaEvent,
'id' | 'title' | 'startsAt' | 'status' | 'capacity' | 'spotsLeft'
>
export async function listDashboardEvents(): Promise<DashboardEvent[]> {
const organizer = await ensureRole('organizer')
const db = await getDb()
return db
.select({
id: events.id,
title: events.title,
startsAt: events.startsAt,
status: events.status,
capacity: events.capacity,
spotsLeft: events.spotsLeft,
})
.from(events)
.where(eq(events.organizerId, organizer.id))
.orderBy(asc(events.startsAt), asc(events.id))
}
// isEditableBy(organizerId, id) stays the same, not exported
export async function getEditableEvent(id: string): Promise<AgendaEvent | null> {
const organizer = await ensureRole('organizer')
const db = await getDb()
const [event] = await db
.select()
.from(events)
.where(isEditableBy(organizer.id, id))
.limit(1)
return event ?? null
}
export async function updateEvent(
id: string,
data: EventData,
status: EditableStatus,
): Promise<boolean> {
const organizer = await ensureRole('organizer')
const db = await getDb()
const updated = await db
.update(events)
.set({ ...data, status, spotsLeft: data.capacity })
.where(isEditableBy(organizer.id, id))
.returning({ id: events.id })
return updated.length > 0
}Make the same change in the rest:
| Before | Now |
|---|---|
getOccupancy(organizerId) |
getOccupancy() |
insertEvent(organizerId, data, status) |
insertEvent(data, status) |
changeImage(organizerId, eventId, key) |
changeImage(eventId, key) |
getBooking(userId, eventId) |
getMyBooking(eventId) |
createBooking(userId, eventId, spots) |
createBooking(eventId, spots) |
listUserBookings(userId) |
listMyBookings() |
cancelBooking(userId, bookingId) |
cancelBooking(bookingId) |
The booking ones use ensureUser. Names with "my" say in the call what an argument used to say.
- Ownership goes in the
where, not in anifafterwards.read → compare owner → writeleaves a gap between the steps; with the condition inside theUPDATE, someone else's data doesn't exist for that statement. Zero rows means "it doesn't exist or it isn't yours", without telling them apart: that's what we want to say to the outside. - Permission first, database second. Data isn't loaded only to decide afterwards whether to show it (04-03).
- Repeating it costs nothing. While rendering,
cacheleaves a single session query per screen. In an action it's two or three primary key lookups. - Don't export the variant with an identifier "in case it's needed". If a task without a session needs it, like
getBookingForNotification, say so in its name and in a comment: it's a different door, and it has to be easy to find.
4.1. Minimal objects
DashboardEvent is a DTO, a data transfer object: the columns the screen uses. We've already made three, with VenueSummary, with toPublicEvent and with SessionUser. What in 03-03 was efficiency is now a rule:
- What isn't read can't leak. A
selectwith columns is better than trimming afterwards. - The type doesn't trim. Declaring
Pickover a fullselect()leaves the other fields in the object, and they cross the boundary as props (03-03). - A DTO depends on who's looking. The email of whoever booked is seen by the organizer, not by the other attendees: they're two functions.
React also offers some experimental APIs (taint, in 03-05) that make rendering fail if a marked object reaches the client. They're a safety net, not the structure.
- Pages and actions
// app/(dashboard)/dashboard/events/page.tsx
export default async function DashboardEventsPage() {
await requireRole('/dashboard/events', 'organizer')
const events = await listDashboardEvents()
// … the same
}
// app/(dashboard)/dashboard/events/[id]/edit/page.tsx
const { id } = await params
await requireRole(`/dashboard/events/${id}/edit`, 'organizer')
const [event, venues] = await Promise.all([getEditableEvent(id), listVenueSummaries()])
if (!event) notFound()requireRole is in every private page.tsx, including the @upcoming and @occupancy slots, which are pages and render on their own. Its job is the experience: sending the person to sign in instead of showing an error. If you forget it in one, the data function throws AccessError and you see the error.tsx. Ugly, and safe. That's the advantage of having the barrier at the bottom: omissions show up, they don't get exploited.
Pages without private data don't need it. DashboardPage only has a heading, which is in the shell and anyone can read.
// actions/events.ts, at the start of saveEvent
const values = readTextFields(formData, EVENT_FIELDS)
const permission = await checkRole('organizer')
if (!permission.granted) {
return { status: 'error', message: DENIAL_MESSAGES[permission.reason], errors: {}, values }
}
// The two actions
export async function createEvent(
_previous: EventFormState,
formData: FormData,
): Promise<EventFormState> {
return saveEvent(formData, insertEvent)
}
export async function editEvent(
eventId: string,
_previous: EventFormState,
formData: FormData,
): Promise<EventFormState> {
return saveEvent(formData, async (event, status, organizer) => {
if (!identifier.safeParse(eventId).success) return false
const saved = await updateEvent(eventId, event, status)
if (saved) {
const action = status === 'review' ? 'event.submitted' : 'event.saved'
audit(organizer.id, action, eventId)
}
return saved
})
}saveEvent passes permission.user as the third argument to write. Permission is checked before validating: someone who can't create events doesn't need to know whether the title is too short. The session-ended message keeps what was typed, because it returns values.
uploadImage and removeImage do the same. bookSpots already replied when there was no session; only the data calls change. BookingList stays the same.
The menus ask for the role to show what's appropriate: in AccountMenu, a link to /dashboard if user.role === 'organizer' and to /admin if it's 'admin'. It's a convenience; if it got it wrong, nothing would happen.
- The administrator's review
Events have been reaching review since 06-02 and nobody can publish them. The administrator needs to see them and decide:
// lib/data/admin.ts
import 'server-only'
import { and, asc, eq, gt } from 'drizzle-orm'
import { ensureRole } from '@/lib/authorization'
import { getDb } from '@/lib/db/client'
import { events, venues, users } from '@/lib/db/schema'
export const DECISIONS = ['published', 'draft'] as const
export type Decision = (typeof DECISIONS)[number]
export async function listEventsInReview() {
await ensureRole('admin')
const db = await getDb()
return db
.select({
id: events.id,
title: events.title,
description: events.description,
startsAt: events.startsAt,
venue: venues.name,
organizer: users.name, // No email: it isn't needed here
})
.from(events)
.innerJoin(venues, eq(events.venueId, venues.id))
.innerJoin(users, eq(events.organizerId, users.id))
.where(eq(events.status, 'review'))
.orderBy(asc(events.startsAt), asc(events.id))
}
// null if it's no longer in review, or if publishing something that has already started
export async function resolveReview(
eventId: string,
decision: Decision,
): Promise<{ slug: string } | null> {
await ensureRole('admin')
const db = await getDb()
const [event] = await db
.update(events)
.set({ status: decision })
.where(
and(
eq(events.id, eventId),
eq(events.status, 'review'),
decision === 'published' ? gt(events.startsAt, new Date()) : undefined,
),
)
.returning({ slug: events.slug })
return event ?? null
}The status transition is in the where: you can only leave review. If two people decide at once, the second finds no row and finds out. Nobody can publish a draft or bring a canceled event back to life by calling this function with another identifier.
// actions/admin.ts
'use server'
import { refresh } from 'next/cache'
import * as z from 'zod'
import { checkRole, DENIAL_MESSAGES } from '@/lib/authorization'
import { setFlash } from '@/lib/flash-server'
import { DECISIONS, resolveReview } from '@/lib/data/admin'
import { identifier } from '@/lib/schemas/common'
import type { FormState } from '@/lib/forms'
import { invalidateEvent } from '@/lib/revalidation'
import { audit } from '@/lib/tasks/audit'
export type ReviewState = FormState<never>
const schema = z.object({ eventId: identifier, decision: z.enum(DECISIONS) })
export async function reviewEvent(
eventId: string,
_previous: ReviewState,
formData: FormData,
): Promise<ReviewState> {
const reject = (message: string): ReviewState => ({
status: 'error',
message,
errors: {},
values: {},
})
const permission = await checkRole('admin')
if (!permission.granted) return reject(DENIAL_MESSAGES[permission.reason])
const input = schema.safeParse({ eventId, decision: formData.get('decision') })
if (!input.success) return reject('Invalid request.')
const { decision } = input.data
const event = await resolveReview(input.data.eventId, decision)
refresh()
if (!event) return reject("The event can no longer be resolved: it's already been resolved or has already started.")
if (decision === 'published') invalidateEvent(event.slug)
const action = decision === 'published' ? 'event.published' : 'event.returned'
audit(permission.user.id, action, input.data.eventId)
await setFlash(decision === 'published' ? 'event-published' : 'event-returned')
return { status: 'initial' }
}// app/(dashboard)/admin/page.tsx — with a loading.tsx that reuses ListSkeleton
export default async function AdminPage() {
await requireRole('/admin', 'admin')
const events = await listEventsInReview()
return (
<>
<h1 className="mb-6 text-2xl font-bold">Events in review</h1>
<Suspense fallback={null}>
<FlashNotice />
</Suspense>
{events.length === 0 && <p>Nothing pending.</p>}
<ul className="grid gap-6">
{events.map((event) => (
<li key={event.id} className="border p-4">
<h2 className="font-semibold">{event.title}</h2>
<p>
{formatDateTime(event.startsAt)}, {event.venue}. {event.organizer}
</p>
<p className="my-2 whitespace-pre-line">{event.description}</p>
<ReviewForm eventId={event.id} />
</li>
))}
</ul>
</>
)
}
// app/(dashboard)/admin/_components/review-form.tsx
'use client'
export function ReviewForm({ eventId }: { eventId: string }) {
const [state, formAction] = useActionState(reviewEvent.bind(null, eventId), INITIAL_STATE)
return (
<form action={formAction} className="flex gap-2">
<FormMessage state={state} />
<SubmitButton name="decision" value="published" pendingText="Publishing…">
Publish
</SubmitButton>
<SubmitButton name="decision" value="draft" pendingText="Sending back…">
Send back
</SubmitButton>
</form>
)
}The resolved event disappears from the list, and its form with it: a success message inside would never be seen. That's why the flash message from 06-04 is used, with two new keys in FLASH_MESSAGES. Also add event.published and event.returned to AuditedAction.
DECISIONS is imported in the action, not in the component: lib/data/admin.ts is server-only. invalidateEvent refreshes the event page, the listings and the negative answer the proxy might have obtained earlier (07-02). The description was written by someone else and is rendered as text, which React escapes; never as HTML (08-06).
Sign in as [email protected] and publish "Summer Choir". Then open /admin with the organizer account: a "not found". And test what matters, without the UI: copy the administrator's publish request from the browser's developer tools and repeat it with another account's cookie. It must reply "You don't have permission".
- The optimistic check in the proxy
With all of the above in place, the proxy is an improvement to the experience: without a session cookie, it isn't worth even starting to render the dashboard.
// proxy.ts (imports SESSION_COOKIE and signInPath), before the event page block
const PRIVATE_AREA = /^\/(?:dashboard|admin|my-bookings|account)(?:\/|$)/
// Inside proxy()
if (
request.method === 'GET' &&
PRIVATE_AREA.test(pathname) &&
!request.cookies.has(SESSION_COOKIE)
) {
return NextResponse.redirect(new URL(signInPath(pathname), request.url), 307)
}- It only checks whether the cookie exists. It doesn't query the database: that would be paid for on every request to the site. With stateless sessions the signature could be verified; with ours, there's nothing to verify without querying.
- Only with
GET. A Server Action is aPOSTto that page; redirecting it would lose the message the action knows how to give. - It's a 307, never permanent: the browser would remember that
/dashboardis/sign-in. - It gains something else: since it's decided before the shell, it's a true HTTP redirect, without the flash of an empty dashboard.
Compare the modules it imports: lib/session-cookie.ts and lib/destination.ts are neutral. If it imported lib/session.ts, it would drag in the database client. Check that the barrier is where it should be by removing the proxy condition and going to /dashboard without a cookie: it must still be protected. If removing the proxy opens something up, the barrier was in the wrong place.
- Authorization and Cache Components
| Rule | Why |
|---|---|
The session is read inside a <Suspense> (or under loading.tsx) |
It's request data |
Never inside 'use cache' |
cookies() throws; and cached content is shared |
To cache something for one person, the id is passed as an argument |
It's part of the key: each person gets their own entry |
| That function isn't exported | With it, anyone could request another id's data |
| Keys and tags don't contain personal data | They're stored as readable text |
// Example only: AgendaViva doesn't cache the dashboard
export async function getOccupancy(): Promise<Occupancy> {
const organizer = await ensureRole('organizer') // Outside the cache
return occupancyFor(organizer.id)
}
async function occupancyFor(organizerId: string): Promise<Occupancy> {
'use cache'
cacheLife('minutes')
cacheTag(`occupancy:${organizerId}`)
// … the query
}The exported one checks and the internal one computes. It's the shape the official authentication guide suggests with Cache Components, together with 'use cache: private' for what shouldn't be stored on the server: that result lives only in the browser and allows prefetching screens with a session. Its price is accepting, for a few minutes, what was computed earlier, so don't use it for the decision itself of whether to allow something.
One last warning: if a static page shows restricted content, for example for subscribers, no component protects it, because it's already generated. That's the case where the proxy really is the barrier, and that's why it's best avoided.
Common Mistakes and Tips
- Checking the role and forgetting ownership.
- Passing the
userIdas a parameter from the page or, worse, from the browser. - Protecting in the layout.
- Forgetting parallel slots and Server Actions.
- Reading first and comparing afterwards.
- Responding differently if it doesn't exist or if it isn't yours.
redirectinside atrythat catches everything.- Redirecting someone who already has a session to
/sign-in: a loop. - Role lists that deny (
role !== 'visitor') instead of allowing: a new role would get in on its own. - Querying the session in the proxy.
- Exporting a cached function that receives a person's identifier.
- Relying on hard-to-guess identifiers instead of checking.
Exercises
Exercise 1: attendee list
Create GET /dashboard/events/[id]/bookings.csv, with the name, email and spots of the people who booked one of your own events, for checking them in at the door. Decide the response codes and the headers.
Solution
// lib/api/responses.ts: add forbidden: 403 to HTTP_STATUSES
// lib/data/dashboard.ts
export async function listAttendees(eventId: string) {
const organizer = await ensureRole('organizer')
const db = await getDb()
const [event] = await db
.select({ slug: events.slug })
.from(events)
.where(and(eq(events.id, eventId), eq(events.organizerId, organizer.id)))
.limit(1)
if (!event) return null
const attendees = await db
.select({ name: users.name, email: users.email, spots: bookings.spots })
.from(bookings)
.innerJoin(users, eq(bookings.userId, users.id))
.where(eq(bookings.eventId, eventId))
.orderBy(asc(users.name))
return { slug: event.slug, attendees }
}
// app/(dashboard)/dashboard/events/[id]/bookings.csv/route.ts
export async function GET(
_request: Request,
{ params }: RouteContext<'/dashboard/events/[id]/bookings.csv'>,
) {
const { id } = await params
const permission = await checkRole('organizer')
if (!permission.granted) {
return permission.reason === 'no-session'
? errorResponse('unauthorized', 'Please sign in.')
: errorResponse('forbidden', "You don't have permission.")
}
return guarded(async () => {
const list = await listAttendees(id)
if (!list) return errorResponse('not-found', "The event doesn't exist.")
const rows = list.attendees.map(({ name, email, spots }) =>
[name, email, String(spots)].map(cell).join(','), // cell: 07-01
)
return new Response(['name,email,spots', ...rows].join('\r\n'), {
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': `attachment; filename="${list.slug}.csv"`,
'Cache-Control': 'private, no-store',
},
})
})
}401 and 403 are told apart; "doesn't exist" and "isn't yours" are the same 404. checkRole reads cookies, so it's outside guarded (07-01). no-store prevents an intermediary from storing personal data. The cell function neutralizes formulas: here the name was written by a stranger. It's a case where it's worth auditing the download and checking with compliance whether this purpose was disclosed at booking time.
Exercise 2: changing roles
Write changeRole(userId, role) in lib/data/admin.ts. Which two cases must be prevented? Do that person's sessions need to be ended?
Solution
// Practice only
export async function changeRole(userId: string, role: Role): Promise<boolean> {
const admin = await ensureRole('admin')
if (userId === admin.id) return false // You can't remove your own role
const db = await getDb()
return db.transaction(async (tx) => {
const admins = await tx
.select({ id: users.id })
.from(users)
.where(eq(users.role, 'admin'))
.for('update')
const anotherRemains = admins.some(({ id }) => id !== userId)
if (role !== 'admin' && !anotherRemains) return false // The last one
const changed = await tx
.update(users)
.set({ role })
.where(eq(users.id, userId))
.returning({ id: users.id })
return changed.length > 0
})
}It prevents changing your own role and leaving the system without administration; the lock stops two people from removing each other's role at the same time. There's no need to end sessions for it to take effect, because the role is read on every request; even so, when raising privileges it's a good idea to delete them: if someone had a stolen session, it has just inherited the new role. And it's an operation that calls for auditing inside the transaction (07-04).
Exercise 3: what was reviewed and what was published
An administrator reads an event in review; meanwhile, the organizer edits it (they can, it's still in review) and then the administrator clicks "Publish". What gets published? Propose a solution that doesn't lock anyone out.
Solution
// lib/db/schema.ts, in events (with its migration)
version: integer('version').notNull().default(1),
// updateEvent
.set({ ...data, status, spotsLeft: data.capacity, version: sql`${events.version} + 1` })
// resolveReview(eventId, version, decision): one more condition
eq(events.version, version),Something nobody has reviewed gets published. With a version counter, the /admin list includes the version that was read, the form sends it in a hidden field and the UPDATE only acts if it hasn't changed. If it has, the action replies "The event has been modified: review it again" and refresh brings in the new text. It's optimistic locking. The version comes from the browser and that's fine: a fake value only makes the update not happen. The counter should also be incremented when the image changes.
Conclusion
Authorization lives next to the data. Each function in lib/data/ finds out who's asking, checks the role and puts ownership in the where; it returns only what the screen needs. On top of that, pages turn a refusal into a redirect or a "not found", actions into a message that doesn't lose what was typed, and the proxy saves a round trip for anyone who doesn't even bring a cookie. Layouts and hidden buttons help the UI and protect nothing. The administration now publishes events, and at last everyone does only what's theirs.
So far we've decided what the server does. What's left is giving instructions to the browser: not to accept scripts from another site, not to let the page be framed, never to talk over HTTP. It's defense in depth, for the day something above fails: Security Headers and Content Security Policy.
