Open History to see the last commit
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 deleteCookie,
32 getCookie,
33 setCookie,
34} from '@tanstack/react-start/server'
35β
36const SESSION_COOKIE = '__Host-session'
37const ONE_DAY = 60 * 60 * 24
38β
39const sessionCookieOptions = {
40 httpOnly: true,
41 secure: true,
42 sameSite: 'lax',
43 path: '/',
44} as const
45β
46export function setSessionCookie(token: string) {
47 setCookie(SESSION_COOKIE, token, {
48 ...sessionCookieOptions,
49 maxAge: ONE_DAY,
50 })
51}
52β
53export function clearSessionCookie() {
54 deleteCookie(SESSION_COOKIE, sessionCookieOptions)
55}
56β
57export function readSessionToken(): string | null {
58 return getCookie(SESSION_COOKIE) ?? null
59}
60```
61β
62Write cookies with `setCookie` (or `appendResponseHeader('set-cookie', serialized)` for a cookie that a library already serialized). Do not use `setResponseHeader('Set-Cookie', ...)` for this: it replaces every cookie on the outgoing response, including cookies set by other middleware or returned by a handler.
63β
64| Flag | Why |
65| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
66| `HttpOnly` | JavaScript can't read the cookie. An XSS bug can't exfiltrate the session. |
67| `Secure` | HTTPS only. Required when using the `__Host-` prefix. |
68| `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. |
69| `__Host-` prefix | Binds the cookie to the exact origin. No `Domain` attribute, `Path=/`, `Secure` required. Defeats subdomain-takeover session fixation. |
70| `Path=/` | Required by `__Host-`. |
71| `Max-Age` | Bounded lifetime. Pair with server-side rotation. |
72β
73## Session Lookup as Middleware
74β
75Centralize session loading in middleware so every protected handler sees a typed session:
76β
77```ts
78// src/server/auth-middleware.ts
79import { createMiddleware } from '@tanstack/react-start'
80import { readSessionToken } from './session'
81β
82export const authMiddleware = createMiddleware({ type: 'function' }).server(
83 async ({ next }) => {
84 const token = readSessionToken()
85 const session = token ? await db.sessions.findValid(token) : null
86 if (!session) throw new Error('Unauthorized')
87 return next({ context: { session } })
88 },
89)
90```
91β
92Attach to every protected server function:
93β
94```ts
95import { createServerFn } from '@tanstack/react-start'
96import { authMiddleware } from '~/server/auth-middleware'
97β
98export const getMyOrders = createServerFn({ method: 'GET' })
99 .middleware([authMiddleware])
100 .handler(async ({ context }) => {
101 return db.orders.findMany({ where: { userId: context.session.userId } })
102 })
103```
104β
105## Login
106β
107```ts
108// src/server/login.functions.ts
109import { createServerFn } from '@tanstack/react-start'
110import { z } from 'zod'
111import { setSessionCookie } from './session'
112β
113export const login = createServerFn({ method: 'POST' })
114 .validator(z.object({ email: z.string().email(), password: z.string() }))
115 .handler(async ({ data }) => {
116 const user = await db.users.findByEmail(data.email)
117 // Always run verifyPasswordHash β even when the user doesn't exist β
118 // so the user-not-found branch takes the same time as wrong-password.
119 // DUMMY_PASSWORD_HASH is a hash of any throwaway password computed once
120 // at startup with the same algorithm/cost as real password hashes.
121 const hashToCheck = user?.passwordHash ?? DUMMY_PASSWORD_HASH
122 const passwordMatches = await verifyPasswordHash(hashToCheck, data.password)
123 const ok = user != null && passwordMatches
124 if (!ok) throw new Error('Invalid email or password')
125β
126 // Rotate: destroy any existing session, then issue fresh.
127 await db.sessions.revokeAllForUser(user.id)
128 const token = await db.sessions.create({ userId: user.id })
129 setSessionCookie(token)
130 return { ok: true }
131 })
132```
133β
134The `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.
135β
136## Logout
137β
138```ts
139import { createServerFn } from '@tanstack/react-start'
140import { authMiddleware } from '~/server/auth-middleware'
141import { clearSessionCookie } from '~/server/session'
142β
143export const logout = createServerFn({ method: 'POST' })
144 .middleware([authMiddleware])
145 .handler(async ({ context }) => {
146 await db.sessions.revoke(context.session.id)
147 clearSessionCookie()
148 return { ok: true }
149 })
150```
151β
152## OAuth: state + PKCE
153β
154For OAuth authorization-code flow:
155β
156- Generate a one-time random `state` parameter β prevents CSRF on the callback.
157- Generate a PKCE `code_verifier`/`code_challenge` pair β defends against authorization-code interception.
158- Store both in a short-lived signed cookie keyed to this exact attempt.
159β
160```ts
161// src/server/oauth.functions.ts
162import { createServerFn } from '@tanstack/react-start'
163import { redirect } from '@tanstack/react-router'
164import { setCookie } from '@tanstack/react-start/server'
165import crypto from 'node:crypto'
166β
167const OAUTH_STATE_COOKIE = '__Host-oauth'
168β
169function base64url(buf: Buffer) {
170 return buf
171 .toString('base64')
172 .replace(/=/g, '')
173 .replace(/\+/g, '-')
174 .replace(/\//g, '_')
175}
176β
177export const startOAuth = createServerFn({ method: 'GET' }).handler(
178 async () => {
179 const state = base64url(crypto.randomBytes(32))
180 const verifier = base64url(crypto.randomBytes(32))
181 const challenge = base64url(
182 crypto.createHash('sha256').update(verifier).digest(),
183 )
184β
185 setCookie(OAUTH_STATE_COOKIE, signed({ state, verifier }), {
186 httpOnly: true,
187 secure: true,
188 sameSite: 'lax',
189 path: '/',
190 maxAge: 600,
191 })
192β
193 throw redirect({
194 href:
195 `https://provider.example/authorize` +
196 `?response_type=code` +
197 `&client_id=${process.env.OAUTH_CLIENT_ID}` +
198 `&redirect_uri=${encodeURIComponent(process.env.OAUTH_REDIRECT_URI!)}` +
199 `&state=${state}` +
200 `&code_challenge=${challenge}` +
201 `&code_challenge_method=S256`,
202 })
203 },
204)
205```
206β
207In the callback handler:
208β
2091. Read the cookie, verify its signature, and extract `state` + `verifier`.
2102. Compare cookie-state to the `state` query param. If they don't match, abort.
2113. Exchange the authorization code for an access token, sending `code_verifier` along with it.
2124. Fetch the user profile, find/create the local user record, issue a session.
2135. Clear the OAuth cookie.
214β
215If any of those checks fail, the request did not originate from your `startOAuth` and must be rejected.
216β
217## Password Reset: defeat user enumeration
218β
219The 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.
220β
221```ts
222import { createServerFn } from '@tanstack/react-start'
223import { z } from 'zod'
224β
225export const requestPasswordReset = createServerFn({ method: 'POST' })
226 .validator(z.object({ email: z.string().email() }))
227 .handler(async ({ data }) => {
228 const user = await db.users.findByEmail(data.email)
229 if (user) {
230 const token = await db.passwordResets.issue(user.id)
231 await sendResetEmail(user.email, token)
232 }
233 // Same response, same body, regardless of existence.
234 return { ok: true }
235 })
236```
237β
238Do NOT:
239β
240- Return 200 if exists, 404 if not.
241- Vary the message ("we sent you a link" vs "no account found").
242- Skip the work when the user doesn't exist (timing leak β measurable from the wire).
243β
244## CSRF for non-GET RPCs
245β
246`SameSite=Lax` on the session cookie blocks most cross-site CSRF for POST/PUT/DELETE. Two cases need explicit defense:
247β
2481. **GET-that-mutates** β never. Use POST/PUT/DELETE for any mutation.
2492. **POST from a sibling subdomain** β `SameSite=Lax` does not block this; verify the `Origin` header matches your app.
250β
251```ts
252import { createMiddleware } from '@tanstack/react-start'
253import { getRequest } from '@tanstack/react-start/server'
254β
255export const csrfMiddleware = createMiddleware().server(async ({ next }) => {
256 const request = getRequest()
257 if (request.method !== 'GET' && request.method !== 'HEAD') {
258 const origin = request.headers.get('origin')
259 // Compare the FULL origin (scheme + host + port) β host alone lets
260 // http://example.com pass a check meant for https://example.com.
261 if (!origin || new URL(origin).origin !== process.env.APP_ORIGIN) {
262 throw new Error('Origin check failed')
263 }
264 }
265 return next()
266})
267```
268β
269Attach this in `src/start.ts` global `requestMiddleware` so it runs on every non-GET request, including server routes and SSR.
270β
271## Rate Limiting Auth Endpoints
272β
273A 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.
274β
275```ts
276import { createMiddleware } from '@tanstack/react-start'
277import { getRequest } from '@tanstack/react-start/server'
278β
279function rateLimitMiddleware(opts: {
280 key: string
281 max: number
282 windowMs: number
283}) {
284 return createMiddleware().server(async ({ next }) => {
285 const request = getRequest()
286 const ip =
287 request.headers.get('cf-connecting-ip') ??
288 request.headers.get('x-forwarded-for')?.split(',')[0] ??
289 'unknown'
290 const allowed = await rateLimiter.consume(
291 `rl:${opts.key}:${ip}`,
292 opts.max,
293 opts.windowMs,
294 )
295 if (!allowed) throw new Error('Too many requests')
296 return next()
297 })
298}
299β
300export const login = createServerFn({ method: 'POST' }).middleware([
301 rateLimitMiddleware({ key: 'login', max: 5, windowMs: 60_000 }),
302])
303// ...
304```
305β
306## Session Rotation
307β
308Whenever 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.
309β
310```ts
311// On login: revoke any pre-login session, create fresh.
312await db.sessions.revokeAllForUser(user.id)
313const token = await db.sessions.create({ userId: user.id })
314setSessionCookie(token)
315β
316// On password change / role grant:
317await db.sessions.revokeAllForUser(user.id)
318const token = await db.sessions.create({ userId: user.id })
319setSessionCookie(token)
320```
321β
322## Read Cookies and Env Per Request, Not at Module Scope
323β
324Module-scope reads are wrong on two axes:
325β
326- **Security:** they can be inlined into the client bundle.
327- **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.
328β
329```ts
330// β Wrong
331const SESSION_SECRET = process.env.SESSION_SECRET
332export function signSession(payload) {
333 return sign(payload, SESSION_SECRET)
334}
335β
336// β
Right
337export function signSession(payload) {
338 return sign(payload, process.env.SESSION_SECRET)
339}
340```
341β
342See [Execution Model: Module-Level `process.env` Reads](./execution-model.md#module-level-processenv-reads) for the full rule.
343β
344## See Also
345β
346- [Authentication Overview](./authentication-overview.md) β choosing between partner solutions, OSS libraries, and DIY.
347- [Authenticated Routes (Router)](/router/latest/docs/framework/react/guide/authenticated-routes) β the routing-side guide.
348- [Server Functions](./server-functions.md) β the RPC primitive that auth lives inside.
349- [Middleware](./middleware.md) β composing `authMiddleware`.
350- [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).
351- [MDN β Set-Cookie](https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie).