AgendaViva can already tell whether a webhook really comes from who it claims, because it checks a signature. For people, it has nothing of the sort: HTTP doesn't remember, and every request arrives with no connection to the previous one. Every booking belongs to usr-01 because the code says so, not because anyone has proved it.
This module fixes that, and it starts with the piece everything else depends on: the session, the mechanism that lets a request say "I'm the same person who came in a while ago" without being asked for anything again. You'll see what the alternatives are, what each cookie attribute protects, how to store a session so that stealing the database doesn't let anyone impersonate anybody, and how to read it from a Server Component without losing the shell. The sign-in forms come in the next lesson; here we'll open sessions by hand.
The code in this module is correct for learning and reasonable to start with, but authentication is one of the parts of a system where a mistake costs the most. Before putting something like this into production, ask a security professional to review it, and check with whoever handles regulatory compliance which data you can store and for how long.
- Three different questions
| Question | When it's answered | In AgendaViva | |
|---|---|---|---|
| Authentication | Who are you? | Once, when signing in | 08-02 and 08-03 |
| Session | Are you still you? | On every request | This lesson |
| Authorization | Can you do this, with this data? | On every operation | 08-04 |
They get mixed up because all three show up together, but they fail in different ways. You can authenticate very well and authorize very badly: that's what happens when anyone with an account can edit someone else's event by changing an identifier. And you can authorize carefully on top of a session that can be stolen with one line of JavaScript.
- Stateful or stateless
A session always travels in a cookie. The difference lies in what it carries inside.
- Stateless. The cookie contains the data (
userId,role, expiry), signed or encrypted with a server secret. Reading it means checking the signature. A JWT is the best-known format. - Stateful. The cookie contains a meaningless random number. The data lives in a table, and reading it means looking up the row.
| Stateless (signed JWT) | Stateful (database) | |
|---|---|---|
| Cost per request | A computation | A primary key lookup |
| Really ending the session | Impossible without a revocation list, which is already state | Delete the row |
| Changing someone's role | Takes effect when the token expires | On the next request |
| "Sign out of other sessions" | No | Yes |
| Knowing who has an open session | No | Yes |
| If the secret leaks | Anyone can be impersonated | There's no secret |
| If the database leaks | Sessions aren't affected | Not affected, if the hash is stored (section 4) |
The argument for the first is saving the query. In AgendaViva nothing is saved: whoever has a session is asking for their bookings or their dashboard, which already query PostgreSQL. In exchange, we'd lose what matters most when something goes wrong: being able to kick someone out now. An organizer who stops working with you, a stolen laptop or a role assigned by mistake can't wait for a token to expire. We choose the database.
Stateless sessions have their place: services that don't share a database, minutes-long tokens between machines, applications without their own store. If you need them, don't implement them by hand: iron-session (encrypted cookies) and jose (JWT) are the ones the Next.js documentation lists. And be wary of a "hybrid" scheme where the JWT states the role and the database is checked now and then: it ends up with the drawbacks of both.
- The cookie
The session token is as good as the password for as long as it lasts: whoever holds it is that person. Each cookie attribute closes one way it could get out.
// lib/session-cookie.ts — neutral: the proxy will use it too
const IN_PRODUCTION = process.env.NODE_ENV === 'production'
export const SESSION_COOKIE = IN_PRODUCTION
? '__Host-agendaviva-session'
: 'agendaviva-session'
export const SESSION_DURATION = 30 * 24 * 60 * 60 // Seconds
export const SESSION_OPTIONS = {
httpOnly: true,
secure: IN_PRODUCTION,
sameSite: 'lax',
path: '/',
} as const| Attribute | What it prevents | What it doesn't prevent |
|---|---|---|
HttpOnly |
JavaScript reading it: an injected script can't copy it | That script acting from the page with the session open |
Secure |
It traveling over unencrypted HTTP | Nothing else: it's still readable on the machine itself |
SameSite=Lax |
It being sent with a POST, a fetch or an <iframe> launched from another site |
It being sent when following a link from another site |
Path=/ |
Nothing: it only delimits. It isn't a security boundary | Another path on the same origin using it |
No Domain |
It being sent to subdomains | |
Max-Age |
The browser keeping it forever | Someone with a copy using it: that's why it also expires on the server |
Lax, not Strict. With Strict, someone arriving at /my-bookings from a link in an email would land without a session on that first page, and would have it after reloading. Besides, the return from an external provider (08-03) is a navigation coming from another site. Lax allows those GETs and blocks cross-site POSTs, which are the ones that change something. Hence a rule you already know, which is now a security rule: a GET doesn't write. If canceling a booking were a link, it would be enough for someone to click it on another website.
__Host- is a name prefix that means something to the browser: it only accepts the cookie if it comes with Secure, with Path=/ and without Domain. Without it, a compromised subdomain could write a cookie for the whole domain and plant a session chosen by the attacker in someone else's browser. With it, it can't. In development there's no HTTPS, so the name changes. If you try npm run start on http://localhost, Chrome accepts Secure cookies because it's a local origin; other browsers may reject it, and you'll notice because the session isn't kept.
Writing the name and the options in a single place isn't just tidiness. To delete a __Host- cookie you have to send it expired with the same attributes: if Secure is missing, the browser ignores the instruction and the session stays there.
- The token and its hash
// lib/security/tokens.ts — no 'server-only': the scripts use it too
import { createHash, randomBytes } from 'node:crypto'
// 32 random bytes, as 43 characters safe for cookies and URLs
export function generateToken(): string {
return randomBytes(32).toString('base64url')
}
export function isPossibleToken(text: string): boolean {
return /^[A-Za-z0-9_-]{43}$/.test(text)
}
// What gets stored: it allows lookups, but not rebuilding the token
export function hashToken(token: string): string {
return createHash('sha256').update(token).digest('hex')
}- The randomness comes from
node:crypto.Math.randomis predictable: by observing a few values you can work out the next ones. A user identifier, a date or a counter are even worse. - 256 bits can't be guessed. That's why there's no need to limit attempts at guessing a token, unlike what will happen with passwords.
- Only the hash is in the database. A badly stored backup or a vulnerable query would expose hashes, and you can't build the cookie from a hash.
- An unsalted SHA-256 is enough here, and it would be a mistake with passwords. Passwords are chosen by people, there are lists of the most common ones, and that's why they're hashed slowly. A 256-bit token isn't on any list: being fast doesn't help anyone.
4.1. The table
// lib/db/schema.ts (added)
export const sessions = pgTable(
'sessions',
{
id: text('id').primaryKey(), // The token hash
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
lastUsedAt: timestamp('last_used_at', { withTimezone: true }).notNull().defaultNow(),
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
},
(table) => [index('sessions_user_idx').on(table.userId)],
)onDelete: 'cascade' means that deleting a user ends their sessions without anyone having to remember; seeding, which deletes users, keeps working unchanged. We don't store the browser or the IP: they'd be useful for a "your devices" screen, but they're personal data and we don't need them today.
- The session data
There are two expiries, because they address different risks. The absolute one (30 days) limits how long a stolen session can live even if it's used every day. The inactivity one (7 days) ends the one left behind on a shared computer. Both are checked in the query:
// lib/data/sessions.ts
import 'server-only'
import { and, eq, gt, lte, ne } from 'drizzle-orm'
import { getDb } from '@/lib/db/client'
import { sessions, users } from '@/lib/db/schema'
import type { SessionUser } from '@/lib/types'
const MAX_INACTIVITY = 7 * 24 * 60 * 60 * 1000
export interface StoredSession {
lastUsedAt: Date
user: SessionUser
}
export async function insertSession(id: string, userId: string, expiresAt: Date) {
const db = await getDb()
await db.insert(sessions).values({ id, userId, expiresAt })
}
export async function findSession(id: string): Promise<StoredSession | null> {
const db = await getDb()
const now = new Date()
const [session] = await db
.select({
lastUsedAt: sessions.lastUsedAt,
user: { id: users.id, name: users.name, role: users.role },
})
.from(sessions)
.innerJoin(users, eq(sessions.userId, users.id))
.where(
and(
eq(sessions.id, id),
gt(sessions.expiresAt, now),
gt(sessions.lastUsedAt, new Date(now.getTime() - MAX_INACTIVITY)),
),
)
.limit(1)
return session ?? null
}
export async function recordUse(id: string): Promise<void> {
const db = await getDb()
await db.update(sessions).set({ lastUsedAt: new Date() }).where(eq(sessions.id, id))
}
export async function deleteSession(id: string): Promise<void> {
const db = await getDb()
await db.delete(sessions).where(eq(sessions.id, id))
}
// All of a person's sessions, except the given one
export async function deleteUserSessions(userId: string, except?: string) {
const db = await getDb()
await db
.delete(sessions)
.where(and(eq(sessions.userId, userId), except ? ne(sessions.id, except) : undefined))
}
export async function deleteExpiredSessions(): Promise<number> {
const db = await getDb()
const deleted = await db
.delete(sessions)
.where(lte(sessions.expiresAt, new Date()))
.returning({ id: sessions.id })
return deleted.length
}- The user is read in the same query. The role is always the current one, and a session whose user no longer exists finds no row.
- Three columns are selected.
userswill soon have a password, and aselect()with no arguments would bring it along (04-02). - The secret comparison is done by the index, by looking up the hash. Even if the lookup time revealed something, it would reveal bits of the hash of a value the attacker doesn't control byte by byte. There's no need for
timingSafeEqual.
- lib/session.ts
// lib/session.ts
import 'server-only'
import { cache } from 'react'
import { cookies } from 'next/headers'
import {
deleteSession, deleteUserSessions, findSession, insertSession, recordUse,
} from '@/lib/data/sessions'
import { generateToken, hashToken, isPossibleToken } from '@/lib/security/tokens'
import { SESSION_COOKIE, SESSION_DURATION, SESSION_OPTIONS } from '@/lib/session-cookie'
import { afterResponse } from '@/lib/tasks/after-response'
import type { SessionUser } from '@/lib/types'
const ONE_DAY = 24 * 60 * 60 * 1000
async function readSessionId(): Promise<string | null> {
const token = (await cookies()).get(SESSION_COOKIE)?.value
return token && isPossibleToken(token) ? hashToken(token) : null
}
export const getCurrentUser = cache(async (): Promise<SessionUser | null> => {
const id = await readSessionId()
if (!id) return null
const session = await findSession(id)
if (!session) return null
if (Date.now() - session.lastUsedAt.getTime() > ONE_DAY) {
afterResponse('record session use', () => recordUse(id))
}
return session.user
})
// Only from Server Actions and Route Handlers: they write the cookie
export async function createSession(userId: string): Promise<void> {
const previous = await readSessionId()
if (previous) await deleteSession(previous)
const token = generateToken()
const expiresAt = new Date(Date.now() + SESSION_DURATION * 1000)
await insertSession(hashToken(token), userId, expiresAt)
const cookieStore = await cookies()
cookieStore.set(SESSION_COOKIE, token, { ...SESSION_OPTIONS, maxAge: SESSION_DURATION })
}
export async function endSession(): Promise<void> {
const id = await readSessionId()
const cookieStore = await cookies()
cookieStore.set(SESSION_COOKIE, '', { ...SESSION_OPTIONS, maxAge: 0 })
if (id) await deleteSession(id)
}
export async function endOtherSessions(userId: string): Promise<void> {
const id = await readSessionId()
await deleteUserSessions(userId, id ?? undefined)
}6.1. Reading with React.cache
The header, the booking and the list on a single screen will all ask who the person is. cache makes that one query per render (04-03), and no component has to pass the user to another. It's the documentation's first recommendation, and it has a security advantage: what isn't passed from hand to hand doesn't end up in a Client Component by accident.
In a Server Action or a Route Handler there's no render and cache doesn't remember anything: every call queries. That's what you want. After createSession, the screen rendered in the same response already reads the new cookie.
The function returns null if there's no session; it doesn't redirect or throw. Some screens, like the event page, look the same with or without one. The variants that require a session are built on top.
6.2. Rotation and revocation
createSession never reuses whatever token there was. If it did, an attacker could get the victim to use a known token and wait for them to sign in with it: that's session fixation. For the same reason, it's a good idea to issue a new session after any change in privileges. The rule is: if who you are or what you can do changes, the token changes.
Revoking means deleting rows. endSession deletes the current one; endOtherSessions, the rest. Changing the password must call deleteUserSessions: it's of little use if whoever stole it is still inside. Deleting just the cookie doesn't end the session: anyone with a copy would keep using it.
6.3. Renewing without writing the cookie
A Server Component can't write cookies, and rendering is reading (05-04). So how do you record that the session has been used? The cookie isn't touched: its lifetime is the absolute one, set when it was created. What moves is lastUsedAt, in the database and after responding, with after. If one update gets lost, nothing happens.
The one-day threshold avoids one write per visit: with seven days of margin, recording once a day is more than precise enough. And since cookies() has been read before, this line is only reached within a request: there's no risk of after running at build time.
- Who am I, in the header
// components/account-menu.tsx — in 08-02 it will get links and sign-out
import { getCurrentUser } from '@/lib/session'
export async function AccountMenu() {
const user = await getCurrentUser()
return <span>{user ? user.name : 'Not signed in'}</span>
}// components/header.tsx, at the end of the <nav>, and in the ManagementLayout bar
<Suspense fallback={<span aria-hidden className="inline-block w-28" />}>
<AccountMenu />
</Suspense>The <Suspense> is mandatory, because there's cookies(). And whatever stays outside it remains in the shell: the home page doesn't stop being static because one corner greets you by name. Notice what we haven't done: an await getCurrentUser() at the top of PublicLayout. It would have held up everything below it until the session was available, and the build would reject it.
Reserve the hole with the approximate width of the content, or the bar will jump when it arrives (10-01).
sequenceDiagram
participant N as Browser
participant S as Next.js
participant B as PostgreSQL
N->>S: GET / with the cookie (token)
S-->>N: shell: home page and header without a name
S->>S: SHA-256 of the token
S->>B: current session with that hash, and its user
B-->>S: id, name, role
S-->>N: header hole: "Test Visitor"
7.1. And with the cache
Nothing that depends on the session can be inside 'use cache': cookies() throws an error there, and that's lucky, because the alternative would be serving one person's screen to another. There's 'use cache: private' (05-02), which does allow reading cookies and whose result is only kept in the browser's memory. The documentation suggests it for reading the user so that the router can prefetch screens with a session.
We won't use it for identity: it means accepting, for a few minutes, a response computed earlier, and we chose database sessions so that a revocation takes effect immediately. Where prefetching pays off more than immediacy, it's a valid tool; 08-04 comes back to it.
- A session opened by hand
// scripts/open-session.ts — development only
import '../lib/db/load-env'
import { drizzle } from 'drizzle-orm/node-postgres'
import { Pool } from 'pg'
import { sessions } from '../lib/db/schema'
import { generateToken, hashToken } from '../lib/security/tokens'
async function open(userId: string): Promise<void> {
const url = process.env.DATABASE_URL
if (!url || !['localhost', '127.0.0.1'].includes(new URL(url).hostname)) {
throw new Error('Only allowed with a local database')
}
const pool = new Pool({ connectionString: url })
try {
const token = generateToken()
const expiresAt = new Date(Date.now() + 60 * 60 * 1000)
await drizzle({ client: pool })
.insert(sessions)
.values({ id: hashToken(token), userId, expiresAt })
console.log(token)
} finally {
await pool.end()
}
}
open(process.argv[2] ?? 'usr-01').catch((error: unknown) => {
console.error(error)
process.exitCode = 1
})# package.json: "session:open": "tsx scripts/open-session.ts"
TOKEN=$(npm run -s session:open -- usr-01)
curl -s -H "Cookie: agendaviva-session=$TOKEN" localhost:3000 | grep -o 'Test Visitor'
# In the browser console, with the token the script prints:
# document.cookie = 'agendaviva-session=THE_TOKEN; path=/'Reload and the header greets you. Delete the row with npm run db:studio, reload again and it doesn't: the cookie is still in the browser, but it's worth nothing. That's exactly what you couldn't do with a JWT. Notice too that you were able to write it from JavaScript: HttpOnly prevents reading the one the server set, and in development there's no prefix protecting the name.
- Cleanup
Expired sessions don't show up in any query, but they pile up. The nightly task follows the model from 07-04:
// lib/tasks/clean-auth.ts
import 'server-only'
import { deleteExpiredSessions } from '@/lib/data/sessions'
export async function cleanAuth(): Promise<{ sessions: number }> {
return { sessions: await deleteExpiredSessions() }
}
// app/api/tasks/clean-auth/route.ts
import { guarded, errorResponse } from '@/lib/api/responses'
import { readEnv } from '@/lib/env'
import { hasBearerKey } from '@/lib/security/bearer-key'
import { cleanAuth } from '@/lib/tasks/clean-auth'
export async function POST(request: Request) {
return guarded(async () => {
if (!hasBearerKey(request, readEnv().tasksKey)) {
return errorResponse('unauthorized', 'Invalid key.')
}
return Response.json(await cleanAuth())
})
}Common Mistakes and Tips
- Storing the token as is in the database, or writing it to a log.
- Generating it with
Math.random, with the date or with the user's identifier. - Storing the session in
localStorage. Any script on the page can read it; there's noHttpOnlyfor it. - Trusting a cookie with
userId=usr-01without a signature or a lookup. Anyone can edit it. - Putting the role in the cookie and never checking it again.
- Deleting the cookie but not the row when signing out.
- Deleting a
__Host-cookie withoutSecureorPath=/: the browser doesn't delete it. - Keeping the same token before and after signing in.
SameSite=Noneto get by. It sends the cookie back with every cross-site request.- Reading the session at the top of a layout and blocking the whole page.
- Relying only on
Max-Age. The real expiry lives on the server. - Trying to renew the cookie in a Server Component. You can't write while rendering.
Exercises
Exercise 1: reading a header
An application responds with this header. Point out the problems and what attack each one enables.
Solution
- The value is predictable: a user and a date. Anyone can write
usr-04.…and be an administrator. There's no need to even steal anything. HttpOnlyis missing: an injected script reads it and sends it elsewhere.Domain=example.comsends it to every subdomain, including an old blog's or a contracted service's; and it lets any of them write it.SameSite=Nonesends it with requests launched from any website: cross-site request forgery (CSRF) is back.- There's no expiry: it's a browser session cookie, which many browsers restore when reopened. The date in the value is controlled by whoever writes it.
- The name doesn't have
__Host-, which would have rejected point 3.
Exercise 2: shorter sessions for administrators
The administration account publishes content, so its session must last at most 12 hours, and 1 hour without activity. Do it without adding columns. Where's the tricky part?
Solution
// lib/data/sessions.ts — practice only
const HOUR = 60 * 60 * 1000
const ADMIN_LIMITS = { total: 12 * HOUR, inactivity: 1 * HOUR }
// In findSession: add createdAt: sessions.createdAt to the select and, after the query
if (!session) return null
if (session.user.role === 'admin') {
const age = now.getTime() - session.createdAt.getTime()
const idle = now.getTime() - session.lastUsedAt.getTime()
if (age > ADMIN_LIMITS.total || idle > ADMIN_LIMITS.inactivity) return null
}
return sessionThe limit is applied when reading and depends on the current role, so it also reaches sessions opened before that person became an administrator. The tricky part is recordUse: with a one-day threshold, an administration session in continuous use would look inactive after an hour. The threshold must be lower than the allowed inactivity: for example, ten minutes for admin. It's a good example of two distant constants that depend on each other; write them together.
Exercise 3: reviewing an implementation
Find the problems in this code.
'use server'
const sessions = new Map<string, User>()
export async function start(userId: string) {
const cookieStore = await cookies()
const token = cookieStore.get('sid')?.value ?? crypto.randomUUID()
sessions.set(token, await readUser(userId))
cookieStore.set('sid', token, { maxAge: 60 * 60 * 24 * 365 * 10 })
}
export async function currentUser() {
const token = (await cookies()).get('sid')?.value
return token ? (sessions.get(token) ?? null) : null
}Solution
'use server'makes both functions public. Anyone can callstart('usr-04')and be an administrator, without a password. It's the most serious flaw: they must live in aserver-onlymodule.- It reuses the incoming token: session fixation. It also accepts any text the visitor puts in the cookie.
- The
Maplives in one process: it's lost on restart, doesn't exist in the other instances and grows without limit. - It stores the whole user, and an old copy at that: a role change is never seen. And
currentUser, being public, sends it in full to the browser. - No
httpOnly,secureorsameSite, and a ten-year lifetime that nobody checks on the server. - The token is stored unhashed. With a
Mapit matters less; once moved to a table, it would matter.
Conclusion
A session is a random number in a cookie and a row that says whose it is. The number is stored hashed, the cookie carries HttpOnly, Secure, SameSite=Lax and the __Host- prefix, and expiry is checked on the server by age and by inactivity. Signing in always creates a new token; signing out deletes the row. With getCurrentUser, remembered by React.cache, any Server Component can ask who the person is inside its <Suspense>, without the shell ceasing to be static.
For now, sessions are opened by a script. What's missing is for them to be opened by whoever proves who they are, and for that you need to store passwords without knowing them, answer errors without giving clues and slow down whoever tries thousands. That's the content of Sign-Up and Sign-In.
