|
| 1 | +--- |
| 2 | +id: authentication-server-primitives |
| 3 | +title: Authentication Server Primitives |
| 4 | +--- |
| 5 | + |
| 6 | +This guide covers the **server-side primitives** for building authentication in TanStack Start: session cookies, session lookup, OAuth, password-reset hardening, CSRF, and rate limiting. It pairs with the [routing-side guide](../../../../router/guide/authenticated-routes.md) (`_authenticated` layout, `beforeLoad`, redirects, RBAC). |
| 7 | + |
| 8 | +If you can use a managed solution like [Clerk](https://go.clerk.com/wOwHtuJ) or [WorkOS](https://workos.com/), prefer that — they handle most of what this guide describes. Read on if you're rolling your own. |
| 9 | + |
| 10 | +## The Two Halves of Auth |
| 11 | + |
| 12 | +Authentication has a routing half and a server half. They both need to be implemented; either one alone is incomplete. |
| 13 | + |
| 14 | +- **Routing half** (`router-core/auth-and-guards`): redirect unauthenticated users away from protected pages, gate UI on roles/permissions, surface a login form. |
| 15 | +- **Server half** (this guide): issue and verify session cookies, exchange OAuth codes, hash and verify passwords, rate-limit credential endpoints, defeat user enumeration. |
| 16 | + |
| 17 | +> **A route guard does NOT protect a `createServerFn` on that route.** Server functions are RPC endpoints — they're reachable via direct POST regardless of which route renders them. Auth must be enforced on the handler (or via middleware), not on the calling route. |
| 18 | +
|
| 19 | +## Session Cookies |
| 20 | + |
| 21 | +The default session storage is an HTTP-only cookie. The cookie can hold: |
| 22 | + |
| 23 | +- An **opaque session ID** that the server looks up in a database (recommended — easy to revoke). |
| 24 | +- A **signed/encrypted token** that carries the session payload itself (stateless, but revocation is harder). |
| 25 | + |
| 26 | +Whichever you choose, the cookie flags matter: |
| 27 | + |
| 28 | +```ts |
| 29 | +// src/server/session.ts |
| 30 | +import { |
| 31 | + getRequestHeader, |
| 32 | + setResponseHeader, |
| 33 | +} from '@tanstack/react-start/server' |
| 34 | + |
| 35 | +const SESSION_COOKIE = '__Host-session' |
| 36 | +const ONE_DAY = 60 * 60 * 24 |
| 37 | + |
| 38 | +export function setSessionCookie(token: string) { |
| 39 | + setResponseHeader( |
| 40 | + 'Set-Cookie', |
| 41 | + [ |
| 42 | + `${SESSION_COOKIE}=${token}`, |
| 43 | + `HttpOnly`, |
| 44 | + `Secure`, |
| 45 | + `SameSite=Lax`, |
| 46 | + `Path=/`, |
| 47 | + `Max-Age=${ONE_DAY}`, |
| 48 | + ].join('; '), |
| 49 | + ) |
| 50 | +} |
| 51 | + |
| 52 | +export function clearSessionCookie() { |
| 53 | + setResponseHeader( |
| 54 | + 'Set-Cookie', |
| 55 | + `${SESSION_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`, |
| 56 | + ) |
| 57 | +} |
| 58 | + |
| 59 | +export function readSessionToken(): string | null { |
| 60 | + const header = getRequestHeader('cookie') |
| 61 | + if (!header) return null |
| 62 | + for (const part of header.split(/;\s*/)) { |
| 63 | + // Split only on the FIRST '=' — signed/base64 values often contain '='. |
| 64 | + const eq = part.indexOf('=') |
| 65 | + if (eq === -1) continue |
| 66 | + if (part.slice(0, eq) === SESSION_COOKIE) return part.slice(eq + 1) |
| 67 | + } |
| 68 | + return null |
| 69 | +} |
| 70 | +``` |
| 71 | + |
| 72 | +| Flag | Why | |
| 73 | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | |
| 74 | +| `HttpOnly` | JavaScript can't read the cookie. An XSS bug can't exfiltrate the session. | |
| 75 | +| `Secure` | HTTPS only. Required when using the `__Host-` prefix. | |
| 76 | +| `SameSite=Lax` | Sent on top-level navigations; blocks most cross-site CSRF on POST. Use `Strict` for higher-risk apps where loss of cross-site GET navigation is acceptable. | |
| 77 | +| `__Host-` prefix | Binds the cookie to the exact origin. No `Domain` attribute, `Path=/`, `Secure` required. Defeats subdomain-takeover session fixation. | |
| 78 | +| `Path=/` | Required by `__Host-`. | |
| 79 | +| `Max-Age` | Bounded lifetime. Pair with server-side rotation. | |
| 80 | + |
| 81 | +## Session Lookup as Middleware |
| 82 | + |
| 83 | +Centralize session loading in middleware so every protected handler sees a typed session: |
| 84 | + |
| 85 | +```ts |
| 86 | +// src/server/auth-middleware.ts |
| 87 | +import { createMiddleware } from '@tanstack/react-start' |
| 88 | +import { readSessionToken } from './session' |
| 89 | + |
| 90 | +export const authMiddleware = createMiddleware({ type: 'function' }).server( |
| 91 | + async ({ next }) => { |
| 92 | + const token = readSessionToken() |
| 93 | + const session = token ? await db.sessions.findValid(token) : null |
| 94 | + if (!session) throw new Error('Unauthorized') |
| 95 | + return next({ context: { session } }) |
| 96 | + }, |
| 97 | +) |
| 98 | +``` |
| 99 | + |
| 100 | +Attach to every protected server function: |
| 101 | + |
| 102 | +```ts |
| 103 | +import { createServerFn } from '@tanstack/react-start' |
| 104 | +import { authMiddleware } from '~/server/auth-middleware' |
| 105 | + |
| 106 | +export const getMyOrders = createServerFn({ method: 'GET' }) |
| 107 | + .middleware([authMiddleware]) |
| 108 | + .handler(async ({ context }) => { |
| 109 | + return db.orders.findMany({ where: { userId: context.session.userId } }) |
| 110 | + }) |
| 111 | +``` |
| 112 | + |
| 113 | +## Login |
| 114 | + |
| 115 | +```ts |
| 116 | +// src/server/login.functions.ts |
| 117 | +import { createServerFn } from '@tanstack/react-start' |
| 118 | +import { z } from 'zod' |
| 119 | +import { setSessionCookie } from './session' |
| 120 | + |
| 121 | +export const login = createServerFn({ method: 'POST' }) |
| 122 | + .inputValidator(z.object({ email: z.string().email(), password: z.string() })) |
| 123 | + .handler(async ({ data }) => { |
| 124 | + const user = await db.users.findByEmail(data.email) |
| 125 | + // Always run verifyPasswordHash — even when the user doesn't exist — |
| 126 | + // so the user-not-found branch takes the same time as wrong-password. |
| 127 | + // DUMMY_PASSWORD_HASH is a hash of any throwaway password computed once |
| 128 | + // at startup with the same algorithm/cost as real password hashes. |
| 129 | + const hashToCheck = user?.passwordHash ?? DUMMY_PASSWORD_HASH |
| 130 | + const passwordMatches = await verifyPasswordHash(hashToCheck, data.password) |
| 131 | + const ok = user != null && passwordMatches |
| 132 | + if (!ok) throw new Error('Invalid email or password') |
| 133 | + |
| 134 | + // Rotate: destroy any existing session, then issue fresh. |
| 135 | + await db.sessions.revokeAllForUser(user.id) |
| 136 | + const token = await db.sessions.create({ userId: user.id }) |
| 137 | + setSessionCookie(token) |
| 138 | + return { ok: true } |
| 139 | + }) |
| 140 | +``` |
| 141 | + |
| 142 | +The `Invalid email or password` message is identical for "user not found" and "wrong password". The dummy-hash technique above also makes the timing identical: without it, the no-user branch returns instantly while the wrong-password branch spends ~100ms on the hash compare, leaking account existence over the wire. |
| 143 | + |
| 144 | +## Logout |
| 145 | + |
| 146 | +```ts |
| 147 | +import { createServerFn } from '@tanstack/react-start' |
| 148 | +import { authMiddleware } from '~/server/auth-middleware' |
| 149 | +import { clearSessionCookie } from '~/server/session' |
| 150 | + |
| 151 | +export const logout = createServerFn({ method: 'POST' }) |
| 152 | + .middleware([authMiddleware]) |
| 153 | + .handler(async ({ context }) => { |
| 154 | + await db.sessions.revoke(context.session.id) |
| 155 | + clearSessionCookie() |
| 156 | + return { ok: true } |
| 157 | + }) |
| 158 | +``` |
| 159 | + |
| 160 | +## OAuth: state + PKCE |
| 161 | + |
| 162 | +For OAuth authorization-code flow: |
| 163 | + |
| 164 | +- Generate a one-time random `state` parameter — prevents CSRF on the callback. |
| 165 | +- Generate a PKCE `code_verifier`/`code_challenge` pair — defends against authorization-code interception. |
| 166 | +- Store both in a short-lived signed cookie keyed to this exact attempt. |
| 167 | + |
| 168 | +```ts |
| 169 | +// src/server/oauth.functions.ts |
| 170 | +import { createServerFn } from '@tanstack/react-start' |
| 171 | +import { redirect } from '@tanstack/react-router' |
| 172 | +import { setResponseHeader } from '@tanstack/react-start/server' |
| 173 | +import crypto from 'node:crypto' |
| 174 | + |
| 175 | +const OAUTH_STATE_COOKIE = '__Host-oauth' |
| 176 | + |
| 177 | +function base64url(buf: Buffer) { |
| 178 | + return buf |
| 179 | + .toString('base64') |
| 180 | + .replace(/=/g, '') |
| 181 | + .replace(/\+/g, '-') |
| 182 | + .replace(/\//g, '_') |
| 183 | +} |
| 184 | + |
| 185 | +export const startOAuth = createServerFn({ method: 'GET' }).handler( |
| 186 | + async () => { |
| 187 | + const state = base64url(crypto.randomBytes(32)) |
| 188 | + const verifier = base64url(crypto.randomBytes(32)) |
| 189 | + const challenge = base64url( |
| 190 | + crypto.createHash('sha256').update(verifier).digest(), |
| 191 | + ) |
| 192 | + |
| 193 | + setResponseHeader( |
| 194 | + 'Set-Cookie', |
| 195 | + `${OAUTH_STATE_COOKIE}=${signed({ state, verifier })}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=600`, |
| 196 | + ) |
| 197 | + |
| 198 | + throw redirect({ |
| 199 | + href: |
| 200 | + `https://provider.example/authorize` + |
| 201 | + `?response_type=code` + |
| 202 | + `&client_id=${process.env.OAUTH_CLIENT_ID}` + |
| 203 | + `&redirect_uri=${encodeURIComponent(process.env.OAUTH_REDIRECT_URI!)}` + |
| 204 | + `&state=${state}` + |
| 205 | + `&code_challenge=${challenge}` + |
| 206 | + `&code_challenge_method=S256`, |
| 207 | + }) |
| 208 | + }, |
| 209 | +) |
| 210 | +``` |
| 211 | + |
| 212 | +In the callback handler: |
| 213 | + |
| 214 | +1. Read the cookie, verify its signature, and extract `state` + `verifier`. |
| 215 | +2. Compare cookie-state to the `state` query param. If they don't match, abort. |
| 216 | +3. Exchange the authorization code for an access token, sending `code_verifier` along with it. |
| 217 | +4. Fetch the user profile, find/create the local user record, issue a session. |
| 218 | +5. Clear the OAuth cookie. |
| 219 | + |
| 220 | +If any of those checks fail, the request did not originate from your `startOAuth` and must be rejected. |
| 221 | + |
| 222 | +## Password Reset: defeat user enumeration |
| 223 | + |
| 224 | +The reset endpoint must NOT tell the caller whether a given email is registered. Returning 200 vs 404 — or even different copy — leaks user existence to anyone who can hit the endpoint. |
| 225 | + |
| 226 | +```ts |
| 227 | +import { createServerFn } from '@tanstack/react-start' |
| 228 | +import { z } from 'zod' |
| 229 | + |
| 230 | +export const requestPasswordReset = createServerFn({ method: 'POST' }) |
| 231 | + .inputValidator(z.object({ email: z.string().email() })) |
| 232 | + .handler(async ({ data }) => { |
| 233 | + const user = await db.users.findByEmail(data.email) |
| 234 | + if (user) { |
| 235 | + const token = await db.passwordResets.issue(user.id) |
| 236 | + await sendResetEmail(user.email, token) |
| 237 | + } |
| 238 | + // Same response, same body, regardless of existence. |
| 239 | + return { ok: true } |
| 240 | + }) |
| 241 | +``` |
| 242 | + |
| 243 | +Do NOT: |
| 244 | + |
| 245 | +- Return 200 if exists, 404 if not. |
| 246 | +- Vary the message ("we sent you a link" vs "no account found"). |
| 247 | +- Skip the work when the user doesn't exist (timing leak — measurable from the wire). |
| 248 | + |
| 249 | +## CSRF for non-GET RPCs |
| 250 | + |
| 251 | +`SameSite=Lax` on the session cookie blocks most cross-site CSRF for POST/PUT/DELETE. Two cases need explicit defense: |
| 252 | + |
| 253 | +1. **GET-that-mutates** — never. Use POST/PUT/DELETE for any mutation. |
| 254 | +2. **POST from a sibling subdomain** — `SameSite=Lax` does not block this; verify the `Origin` header matches your app. |
| 255 | + |
| 256 | +```ts |
| 257 | +import { createMiddleware } from '@tanstack/react-start' |
| 258 | +import { getRequest } from '@tanstack/react-start/server' |
| 259 | + |
| 260 | +export const csrfMiddleware = createMiddleware().server(async ({ next }) => { |
| 261 | + const request = getRequest() |
| 262 | + if (request.method !== 'GET' && request.method !== 'HEAD') { |
| 263 | + const origin = request.headers.get('origin') |
| 264 | + // Compare the FULL origin (scheme + host + port) — host alone lets |
| 265 | + // http://example.com pass a check meant for https://example.com. |
| 266 | + if (!origin || new URL(origin).origin !== process.env.APP_ORIGIN) { |
| 267 | + throw new Error('Origin check failed') |
| 268 | + } |
| 269 | + } |
| 270 | + return next() |
| 271 | +}) |
| 272 | +``` |
| 273 | + |
| 274 | +Attach this in `src/start.ts` global `requestMiddleware` so it runs on every non-GET request, including server routes and SSR. |
| 275 | + |
| 276 | +## Rate Limiting Auth Endpoints |
| 277 | + |
| 278 | +A login endpoint without rate limiting is a credential-stuffing target. Limit per IP (and per-account if you can identify the user) with a sliding window or token bucket. |
| 279 | + |
| 280 | +```ts |
| 281 | +import { createMiddleware } from '@tanstack/react-start' |
| 282 | +import { getRequest } from '@tanstack/react-start/server' |
| 283 | + |
| 284 | +function rateLimitMiddleware(opts: { |
| 285 | + key: string |
| 286 | + max: number |
| 287 | + windowMs: number |
| 288 | +}) { |
| 289 | + return createMiddleware().server(async ({ next }) => { |
| 290 | + const request = getRequest() |
| 291 | + const ip = |
| 292 | + request.headers.get('cf-connecting-ip') ?? |
| 293 | + request.headers.get('x-forwarded-for')?.split(',')[0] ?? |
| 294 | + 'unknown' |
| 295 | + const allowed = await rateLimiter.consume( |
| 296 | + `rl:${opts.key}:${ip}`, |
| 297 | + opts.max, |
| 298 | + opts.windowMs, |
| 299 | + ) |
| 300 | + if (!allowed) throw new Error('Too many requests') |
| 301 | + return next() |
| 302 | + }) |
| 303 | +} |
| 304 | + |
| 305 | +export const login = createServerFn({ method: 'POST' }).middleware([ |
| 306 | + rateLimitMiddleware({ key: 'login', max: 5, windowMs: 60_000 }), |
| 307 | +]) |
| 308 | +// ... |
| 309 | +``` |
| 310 | + |
| 311 | +## Session Rotation |
| 312 | + |
| 313 | +Whenever the user's privileges change — login, logout, password change, role grant — destroy the old session and issue a new one. This neutralizes session-fixation attacks where an attacker plants their own session ID in the victim's browser before the privilege change. |
| 314 | + |
| 315 | +```ts |
| 316 | +// On login: revoke any pre-login session, create fresh. |
| 317 | +await db.sessions.revokeAllForUser(user.id) |
| 318 | +const token = await db.sessions.create({ userId: user.id }) |
| 319 | +setSessionCookie(token) |
| 320 | + |
| 321 | +// On password change / role grant: |
| 322 | +await db.sessions.revokeAllForUser(user.id) |
| 323 | +const token = await db.sessions.create({ userId: user.id }) |
| 324 | +setSessionCookie(token) |
| 325 | +``` |
| 326 | + |
| 327 | +## Read Cookies and Env Per Request, Not at Module Scope |
| 328 | + |
| 329 | +Module-scope reads are wrong on two axes: |
| 330 | + |
| 331 | +- **Security:** they can be inlined into the client bundle. |
| 332 | +- **Correctness on edge runtimes:** Cloudflare Workers (and others) inject env at request time. Module-level reads run before any request exists and evaluate to `undefined` even on the server. |
| 333 | + |
| 334 | +```ts |
| 335 | +// ❌ Wrong |
| 336 | +const SESSION_SECRET = process.env.SESSION_SECRET |
| 337 | +export function signSession(payload) { |
| 338 | + return sign(payload, SESSION_SECRET) |
| 339 | +} |
| 340 | + |
| 341 | +// ✅ Right |
| 342 | +export function signSession(payload) { |
| 343 | + return sign(payload, process.env.SESSION_SECRET) |
| 344 | +} |
| 345 | +``` |
| 346 | + |
| 347 | +See [Execution Model: Module-Level `process.env` Reads](./execution-model.md#module-level-processenv-reads) for the full rule. |
| 348 | + |
| 349 | +## See Also |
| 350 | + |
| 351 | +- [Authentication Overview](./authentication-overview.md) — choosing between partner solutions, OSS libraries, and DIY. |
| 352 | +- [Authenticated Routes (Router)](../../../../router/guide/authenticated-routes.md) — the routing-side guide. |
| 353 | +- [Server Functions](./server-functions.md) — the RPC primitive that auth lives inside. |
| 354 | +- [Middleware](./middleware.md) — composing `authMiddleware`. |
| 355 | +- [OWASP Cheat Sheets — Authentication](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html), [Session Management](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html), [CSRF](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html). |
| 356 | +- [MDN — Set-Cookie](https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie). |
0 commit comments