Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

authentication-server-primitives.md

356 lines14.4 KB

1---
2id: authentication-server-primitives
3title: Authentication Server Primitives
4---
5​
6This 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/latest/docs/framework/react/guide/authenticated-routes) (`_authenticated` layout, `beforeLoad`, redirects, RBAC).
7​
8If 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## Protect Data First
11​
12Authentication has a data/API boundary and a route/UI layer. The data boundary is the security boundary: every server function, server route, or API endpoint that reads or writes private data must authorize the request before returning data or mutating state.
13​
14- **Data/API boundary** (this guide): issue and verify session cookies, exchange OAuth codes, hash and verify passwords, rate-limit credential endpoints, defeat user enumeration, and authorize private data access.
15- **Route/UI layer** (`router-core/auth-and-guards`): redirect unauthenticated users away from screens they cannot use, gate UI on roles/permissions, surface a login form, and avoid triggering requests that would fail anyway.
16​
17> **A route guard is not a data authorization boundary.** Server functions and server routes are API endpoints; they are reachable independently of the route that calls them. Auth must be enforced in the handler or middleware for the endpoint that touches private data. `beforeLoad` is for route UX.
18​
19## Session Cookies
20​
21The 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​
26Whichever you choose, the cookie flags matter:
27​
28```ts
29// src/server/session.ts
30import {
31 getRequestHeader,
32 setResponseHeader,
33} from '@tanstack/react-start/server'
34​
35const SESSION_COOKIE = '__Host-session'
36const ONE_DAY = 60 * 60 * 24
37​
38export 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 )
51​
52export function clearSessionCookie() {
53 setResponseHeader(
54 'Set-Cookie',
55 `${SESSION_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`,
56 )
58​
59export 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
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​
83Centralize session loading in middleware so every protected handler sees a typed session:
84​
85```ts
86// src/server/auth-middleware.ts
87import { createMiddleware } from '@tanstack/react-start'
88import { readSessionToken } from './session'
89​
90export 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 },
98```
99​
100Attach to every protected server function:
101​
102```ts
103import { createServerFn } from '@tanstack/react-start'
104import { authMiddleware } from '~/server/auth-middleware'
105​
106export 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
117import { createServerFn } from '@tanstack/react-start'
118import { z } from 'zod'
119import { setSessionCookie } from './session'
120​
121export const login = createServerFn({ method: 'POST' })
122 .validator(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​
142The `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
147import { createServerFn } from '@tanstack/react-start'
148import { authMiddleware } from '~/server/auth-middleware'
149import { clearSessionCookie } from '~/server/session'
150​
151export 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​
162For 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
170import { createServerFn } from '@tanstack/react-start'
171import { redirect } from '@tanstack/react-router'
172import { setResponseHeader } from '@tanstack/react-start/server'
173import crypto from 'node:crypto'
174​
175const OAUTH_STATE_COOKIE = '__Host-oauth'
176​
177function base64url(buf: Buffer) {
178 return buf
179 .toString('base64')
180 .replace(/=/g, '')
181 .replace(/\+/g, '-')
182 .replace(/\//g, '_')
184​
185export 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 },
210```
211​
212In the callback handler:
213​
2141. Read the cookie, verify its signature, and extract `state` + `verifier`.
2152. Compare cookie-state to the `state` query param. If they don't match, abort.
2163. Exchange the authorization code for an access token, sending `code_verifier` along with it.
2174. Fetch the user profile, find/create the local user record, issue a session.
2185. Clear the OAuth cookie.
219​
220If 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​
224The 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
227import { createServerFn } from '@tanstack/react-start'
228import { z } from 'zod'
229​
230export const requestPasswordReset = createServerFn({ method: 'POST' })
231 .validator(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​
243Do 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​
2531. **GET-that-mutates** β€” never. Use POST/PUT/DELETE for any mutation.
2542. **POST from a sibling subdomain** β€” `SameSite=Lax` does not block this; verify the `Origin` header matches your app.
255​
256```ts
257import { createMiddleware } from '@tanstack/react-start'
258import { getRequest } from '@tanstack/react-start/server'
259​
260export 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​
274Attach 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​
278A 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
281import { createMiddleware } from '@tanstack/react-start'
282import { getRequest } from '@tanstack/react-start/server'
283​
284function 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 })
304​
305export const login = createServerFn({ method: 'POST' }).middleware([
306 rateLimitMiddleware({ key: 'login', max: 5, windowMs: 60_000 }),
307])
308// ...
309```
310​
311## Session Rotation
312​
313Whenever 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.
317await db.sessions.revokeAllForUser(user.id)
318const token = await db.sessions.create({ userId: user.id })
319setSessionCookie(token)
320​
321// On password change / role grant:
322await db.sessions.revokeAllForUser(user.id)
323const token = await db.sessions.create({ userId: user.id })
324setSessionCookie(token)
325```
326​
327## Read Cookies and Env Per Request, Not at Module Scope
328​
329Module-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
336const SESSION_SECRET = process.env.SESSION_SECRET
337export function signSession(payload) {
338 return sign(payload, SESSION_SECRET)
340​
341// βœ… Right
342export function signSession(payload) {
343 return sign(payload, process.env.SESSION_SECRET)
345```
346​
347See [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/latest/docs/framework/react/guide/authenticated-routes) β€” 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).