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

authentication.md

671 lines20.9 KB

1---
2id: authentication
3title: Implement Authentication in React
4description: Implement sessions, sign-in, sign-out, protected routes, and server-side authorization in a TanStack Start React app.
5---
6​
7Implement the authentication workflow in your React app, from sessions and sign-in to protected routes and authorization.
8​
9To compare libraries and hosted services, read [Choose Authentication for React Apps](./authentication-overview.md).
10​
11## Authentication Approaches
12​
13You have several options for authentication in your TanStack Start application:
14​
15**Hosted Solutions:**
16​
171. **[Clerk](https://clerk.dev)** - Complete authentication platform with UI components
182. **[WorkOS](https://workos.com)** - Enterprise-focused with SSO and compliance features
193. **[Better Auth](https://www.better-auth.com/)** - Open-source TypeScript library
204. **[Auth.js](https://authjs.dev/)** - Open-source library supporting 80+ OAuth providers
21​
22**DIY Implementation Benefits:**
23​
24- **Full Control**: Complete customization over authentication flow
25- **No Vendor Lock-in**: Own your authentication logic and user data
26- **Custom Requirements**: Implement specific business logic or compliance needs
27- **Cost Control**: No per-user pricing or usage limits
28​
29Authentication involves many considerations including password security, session management, rate limiting, CSRF protection, and various attack vectors.
30​
31## Core Concepts
32​
33### Authentication vs Authorization
34​
35- **Authentication**: Who is this user? (Login/logout)
36- **Authorization**: What can this user do? (Permissions/roles)
37​
38TanStack Start provides server functions, request and cookie utilities, and route protection. Session storage and authentication come from your application or a library you choose.
39​
40> Protect the data/API boundary first. Any server function, server route, or other API endpoint that returns or mutates private data must authorize the request itself. `beforeLoad` is useful for route UX: it keeps users out of screens they cannot use and avoids triggering work that would fail anyway. It is not the security boundary for the data. See [Authentication Server Primitives](./authentication-server-primitives.md) for the server-side pattern.
41​
42## Essential Building Blocks
43​
44### 1. Server Functions for Authentication
45​
46Server functions handle sensitive authentication logic securely on the server:
47​
48```tsx
49import { createServerFn } from '@tanstack/react-start'
50import { redirect } from '@tanstack/react-router'
51import { getAppSession } from '~/utils/session'
52​
53// Login server function
54export const loginFn = createServerFn({ method: 'POST' })
55 .validator((data: { email: string; password: string }) => data)
56 .handler(async ({ data }) => {
57 // Verify credentials (replace with your auth logic)
58 const user = await authenticateUser(data.email, data.password)
59​
60 if (!user) {
61 return { error: 'Invalid credentials' }
62 }
63​
64 // Create session
65 const session = await getAppSession()
66 session.userId = user.id
67 await session.save()
68​
69 // Redirect to protected area
70 throw redirect({ to: '/dashboard' })
71 })
72​
73// Logout server function
74export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => {
75 const session = await getAppSession()
76 session.destroy()
77 throw redirect({ to: '/' })
78})
79​
80// Get current user
81export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler(
82 async () => {
83 const session = await getAppSession()
84 const userId = session.userId
85​
86 if (!userId) {
87 return null
88 }
89​
90 const user = await getUserById(userId)
91 return user ? { id: user.id, email: user.email, role: user.role } : null
92 },
94```
95​
96### 2. Session Management
97​
98Start does not provide a session API. This guide uses iron-session for encrypted cookie sessions. Start's cookie helpers connect it to server functions, server routes, and request middleware.
99​
100For encrypted cookie sessions, install [iron-session](https://github.com/vvo/iron-session):
101​
102```sh
103pnpm add iron-session
104```
105​
106This example uses iron-session 9's cookie adapter. Its Node runtime requires Node 22.13 or newer; check the library's runtime requirements for other deployment targets.
107​
108```tsx
109// utils/session.ts β€” import only from server code
110import { getIronSession } from 'iron-session'
111import { getCookie, setCookie } from '@tanstack/react-start/server'
112​
113type SessionData = {
114 userId: string
115 oauthState: string
117​
118export function getAppSession(ttl = 7 * 24 * 60 * 60) {
119 const password = process.env.SESSION_SECRET
120 if (!password || password.length < 32) {
121 throw new Error('SESSION_SECRET must be at least 32 characters')
122 }
123​
124 return getIronSession<SessionData>(
125 { read: getCookie, write: setCookie },
126 {
127 cookieName: 'app-session',
128 password,
129 ttl,
130 cookieOptions: {
131 secure: process.env.NODE_ENV === 'production',
132 sameSite: 'lax',
133 httpOnly: true,
134 path: '/',
135 },
136 },
137 )
139```
140​
141Read fields directly from the returned session, change them, then `await session.save()` before returning or redirecting. Missing or expired sessions have no user ID. `session.destroy()` removes the browser cookie. Keep one session object for the operation; another call to `getAppSession()` reads the incoming request again. For middleware, pass that object through request context when downstream code needs the same mutations.
142​
143The `getAppSession` helper belongs to your application. Start does not cache sessions, choose expiration rules, or synchronize concurrent writes. Keep secrets and session objects in server code, and read request-specific configuration inside the active request.
144​
145### 3. Authentication Context
146​
147Load the current user in your root route's `beforeLoad` so the initial server render and child routes receive the same authentication state. `useServerFn` returns a callable function, not an object with `data`, `isLoading`, or `refetch`. You can call a server function directly from `beforeLoad`.
148​
149Merge this pattern into your existing root route, keeping its metadata and document shell:
150​
151```tsx
152// routes/__root.tsx
153import {
154 createRootRoute,
155 HeadContent,
156 Outlet,
157 Scripts,
158} from '@tanstack/react-router'
159import type { ReactNode } from 'react'
160import { getCurrentUserFn } from '../server/auth'
161​
162export const Route = createRootRoute({
163 headers: () => ({ 'Cache-Control': 'private, no-store' }),
164 beforeLoad: async () => ({ user: await getCurrentUserFn() }),
165 component: Outlet,
166 shellComponent: RootDocument,
167})
168​
169function RootDocument({ children }: { children: ReactNode }) {
170 return (
171 <html>
172 <head>
173 <HeadContent />
174 </head>
175 <body>
176 {children}
177 <Scripts />
178 </body>
179 </html>
180 )
182```
183​
184The root includes session-specific data, so its responses use `Cache-Control: private, no-store`. Keep that policy on child routes that render this data, and do not override it with public caching at your CDN.
185​
186Read that state from a descendant component:
187​
188```tsx
189// components/AuthStatus.tsx
190import { Route } from '../routes/__root'
191​
192export function AuthStatus() {
193 const { user } = Route.useRouteContext()
194 return <span>{user ? user.email : 'Signed out'}</span>
196```
197​
198After login or logout changes the session, call `await router.invalidate()` to reload the current user and rerun route guards. Keep private-data authorization in the server function itself, even when a route already checks the user.
199​
200### 4. Route Protection
201​
202Protect routes using `beforeLoad`:
203​
204```tsx
205// routes/_authed.tsx - Layout route for protected pages
206import { createFileRoute, redirect } from '@tanstack/react-router'
207import { getCurrentUserFn } from '../server/auth'
208​
209export const Route = createFileRoute('/_authed')({
210 beforeLoad: async ({ location }) => {
211 const user = await getCurrentUserFn()
212​
213 if (!user) {
214 throw redirect({
215 to: '/login',
216 search: { redirect: location.href },
217 })
218 }
219​
220 // Pass user to child routes
221 return { user }
222 },
223})
224```
225​
226```tsx
227// routes/_authed/dashboard.tsx - Protected route
228import { createFileRoute } from '@tanstack/react-router'
229​
230export const Route = createFileRoute('/_authed/dashboard')({
231 component: DashboardComponent,
232})
233​
234function DashboardComponent() {
235 const { user } = Route.useRouteContext()
236​
237 return (
238 <div>
239 <h1>Welcome, {user.email}!</h1>
240 {/* Dashboard content */}
241 </div>
242 )
244```
245​
246## Implementation Patterns
247​
248### Basic Email/Password Authentication
249​
250```tsx
251// server/auth.ts
252import bcrypt from 'bcryptjs'
253import { createServerFn } from '@tanstack/react-start'
254​
255// User registration
256export const registerFn = createServerFn({ method: 'POST' })
257 .validator((data: { email: string; password: string; name: string }) => data)
258 .handler(async ({ data }) => {
259 // Check if user exists
260 const existingUser = await getUserByEmail(data.email)
261 if (existingUser) {
262 return { error: 'User already exists' }
263 }
264​
265 // Hash password
266 const hashedPassword = await bcrypt.hash(data.password, 12)
267​
268 // Create user
269 const user = await createUser({
270 email: data.email,
271 password: hashedPassword,
272 name: data.name,
273 })
274​
275 // Create session
276 const session = await getAppSession()
277 session.userId = user.id
278 await session.save()
279​
280 return { success: true, user: { id: user.id, email: user.email } }
281 })
282​
283async function authenticateUser(email: string, password: string) {
284 const user = await getUserByEmail(email)
285 if (!user) return null
286​
287 const isValid = await bcrypt.compare(password, user.password)
288 return isValid ? user : null
290```
291​
292### Role-Based Access Control (RBAC)
293​
294```tsx
295// utils/auth.ts
296export const roles = {
297 USER: 'user',
298 ADMIN: 'admin',
299 MODERATOR: 'moderator',
300} as const
301​
302type Role = (typeof roles)[keyof typeof roles]
303​
304export function hasPermission(userRole: Role, requiredRole: Role): boolean {
305 const hierarchy = {
306 [roles.USER]: 0,
307 [roles.MODERATOR]: 1,
308 [roles.ADMIN]: 2,
309 }
310​
311 return hierarchy[userRole] >= hierarchy[requiredRole]
313​
314// Protected route with role check
315export const Route = createFileRoute('/_authed/admin/')({
316 beforeLoad: async ({ context }) => {
317 if (!hasPermission(context.user.role, roles.ADMIN)) {
318 throw redirect({ to: '/unauthorized' })
319 }
320 },
321})
322```
323​
324### Social Authentication Integration
325​
326```tsx
327// Example with OAuth providers
328export const authProviders = {
329 google: {
330 clientId: process.env.GOOGLE_CLIENT_ID!,
331 redirectUri: `${process.env.APP_URL}/auth/google/callback`,
332 },
333 github: {
334 clientId: process.env.GITHUB_CLIENT_ID!,
335 redirectUri: `${process.env.APP_URL}/auth/github/callback`,
336 },
338​
339export const initiateOAuthFn = createServerFn({ method: 'POST' })
340 .validator((data: { provider: 'google' | 'github' }) => data)
341 .handler(async ({ data }) => {
342 const provider = authProviders[data.provider]
343 const state = generateRandomState()
344​
345 // Store state in session for CSRF protection
346 const session = await getAppSession()
347 session.oauthState = state
348 await session.save()
349​
350 // Generate OAuth URL
351 const authUrl = generateOAuthUrl(provider, state)
352​
353 throw redirect({ href: authUrl })
354 })
355```
356​
357### Password Reset Flow
358​
359```tsx
360// Password reset request
361export const requestPasswordResetFn = createServerFn({ method: 'POST' })
362 .validator((data: { email: string }) => data)
363 .handler(async ({ data }) => {
364 const user = await getUserByEmail(data.email)
365 if (!user) {
366 // Don't reveal if email exists
367 return { success: true }
368 }
369​
370 const token = generateSecureToken()
371 const expires = new Date(Date.now() + 60 * 60 * 1000) // 1 hour
372​
373 await savePasswordResetToken(user.id, token, expires)
374 await sendPasswordResetEmail(user.email, token)
375​
376 return { success: true }
377 })
378​
379// Password reset confirmation
380export const resetPasswordFn = createServerFn({ method: 'POST' })
381 .validator((data: { token: string; newPassword: string }) => data)
382 .handler(async ({ data }) => {
383 const resetToken = await getPasswordResetToken(data.token)
384​
385 if (!resetToken || resetToken.expires < new Date()) {
386 return { error: 'Invalid or expired token' }
387 }
388​
389 const hashedPassword = await bcrypt.hash(data.newPassword, 12)
390 await updateUserPassword(resetToken.userId, hashedPassword)
391 await deletePasswordResetToken(data.token)
392​
393 return { success: true }
394 })
395```
396​
397## Security Best Practices
398​
399### 1. Password Security
400​
401```tsx
402// Use strong hashing (bcrypt, scrypt, or argon2)
403import bcrypt from 'bcryptjs'
404​
405const saltRounds = 12 // Adjust based on your security needs
406const hashedPassword = await bcrypt.hash(password, saltRounds)
407```
408​
409### 2. Session Security
410​
411Set the library's server-validated expiration as well as appropriate cookie attributes. In the iron-session example, `ttl` limits a sealed credential's lifetime from its latest save; saving again renews it. A numeric `cookieOptions.maxAge` controls browser retention. In iron-session 9, explicitly setting `maxAge: undefined` also disables seal expiry; omit the property to use the configured `ttl`. Use an application-validated timestamp or a server-side record if you also need an absolute lifetime that writes cannot extend.
412​
413Use `httpOnly`, `sameSite`, and `path` deliberately, and require `secure: true` on HTTPS deployments. These cookie attributes complement server-side authorization and CSRF protections. Keep only the minimum session data and load current account permissions from their authoritative store. Logout removes a stateless cookie from the current browser; it cannot revoke a copy without server-side state.
414​
415### 3. Rate Limiting
416​
417```tsx
418// Simple in-memory rate limiting (use Redis in production)
419const loginAttempts = new Map<string, { count: number; resetTime: number }>()
420​
421export const rateLimitLogin = (ip: string): boolean => {
422 const now = Date.now()
423 const attempts = loginAttempts.get(ip)
424​
425 if (!attempts || now > attempts.resetTime) {
426 loginAttempts.set(ip, { count: 1, resetTime: now + 15 * 60 * 1000 }) // 15 min
427 return true
428 }
429​
430 if (attempts.count >= 5) {
431 return false // Too many attempts
432 }
433​
434 attempts.count++
435 return true
437```
438​
439### 4. Input Validation
440​
441```tsx
442import { z } from 'zod'
443​
444const loginSchema = z.object({
445 email: z.string().email().max(255),
446 password: z.string().min(8).max(100),
447})
448​
449export const loginFn = createServerFn({ method: 'POST' })
450 .validator((data) => loginSchema.parse(data))
451 .handler(async ({ data }) => {
452 // data is now validated
453 })
454```
455​
456## Testing Authentication
457​
458### Unit Testing Server Functions
459​
460```tsx
461// __tests__/auth.test.ts
462import { describe, it, expect, beforeEach } from 'vitest'
463import { loginFn } from '../server/auth'
464​
465describe('Authentication', () => {
466 beforeEach(async () => {
467 await setupTestDatabase()
468 })
469​
470 it('should login with valid credentials', async () => {
471 const result = await loginFn({
472 data: { email: 'test@example.com', password: 'password123' },
473 })
474​
475 expect(result.error).toBeUndefined()
476 expect(result.user).toBeDefined()
477 })
478​
479 it('should reject invalid credentials', async () => {
480 const result = await loginFn({
481 data: { email: 'test@example.com', password: 'wrongpassword' },
482 })
483​
484 expect(result.error).toBe('Invalid credentials')
485 })
486})
487```
488​
489### Integration Testing
490​
491```tsx
492// __tests__/auth-flow.test.tsx
493import { render, screen, fireEvent, waitFor } from '@testing-library/react'
494import { RouterProvider, createMemoryHistory } from '@tanstack/react-router'
495import { router } from '../router'
496​
497describe('Authentication Flow', () => {
498 it('should redirect to login when accessing protected route', async () => {
499 const history = createMemoryHistory()
500 history.push('/dashboard') // Protected route
501​
502 render(<RouterProvider router={router} history={history} />)
503​
504 await waitFor(() => {
505 expect(screen.getByText('Login')).toBeInTheDocument()
506 })
507 })
508})
509```
510​
511## Common Patterns
512​
513### Loading States
514​
515Call the function returned by `useServerFn` with `{ data }`. Track pending state in the component, handle invalid credentials, and refresh route context after a successful login. This form uses the `loginFn` from the server-functions example above. It requires JavaScript, so the fields stay disabled until hydration; `method="post"` also prevents credentials appearing in a native GET submission.
516​
517```tsx
518// components/LoginForm.tsx
519import { useState } from 'react'
520import type { FormEvent } from 'react'
521import { useHydrated, useRouter } from '@tanstack/react-router'
522import { useServerFn } from '@tanstack/react-start'
523import { loginFn } from '../server/auth'
524​
525export function LoginForm() {
526 const hydrated = useHydrated()
527 const [isLoading, setIsLoading] = useState(false)
528 const [error, setError] = useState('')
529 const login = useServerFn(loginFn)
530 const router = useRouter()
531​
532 const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
533 event.preventDefault()
534 const formData = new FormData(event.currentTarget)
535 const email = formData.get('email')
536 const password = formData.get('password')
537 if (typeof email !== 'string' || typeof password !== 'string') {
538 return
539 }
540​
541 setIsLoading(true)
542 setError('')
543 try {
544 const result = await login({ data: { email, password } })
545 if (result?.error) {
546 setError(result.error)
547 return
548 }
549 await router.invalidate()
550 } catch {
551 setError('Login failed. Please try again.')
552 } finally {
553 setIsLoading(false)
554 }
555 }
556​
557 return (
558 <form method="post" onSubmit={handleSubmit}>
559 <fieldset disabled={!hydrated || isLoading}>
560 <label>
561 Email
562 <input name="email" type="email" autoComplete="username" required />
563 </label>
564 <label>
565 Password
566 <input
567 name="password"
568 type="password"
569 autoComplete="current-password"
570 required
571 />
572 </label>
573 <button type="submit" disabled={isLoading}>
574 {isLoading ? 'Logging in...' : 'Login'}
575 </button>
576 </fieldset>
577 <p role="alert">{error}</p>
578 </form>
579 )
581```
582​
583### Remember Me Functionality
584​
585```tsx
586export const loginFn = createServerFn({ method: 'POST' })
587 .validator(
588 (data: { email: string; password: string; rememberMe?: boolean }) => data,
589 )
590 .handler(async ({ data }) => {
591 const user = await authenticateUser(data.email, data.password)
592 if (!user) {
593 return { error: 'Invalid credentials' }
594 }
595​
596 const ttl = data.rememberMe ? 30 * 24 * 60 * 60 : 8 * 60 * 60
597 const session = await getAppSession(ttl)
598 session.userId = user.id
599 await session.save()
600​
601 return { success: true }
602 })
603```
604​
605## Working Examples
606​
607Study these implementations to understand different authentication patterns:
608​
609- **[Basic Auth with Prisma](https://github.com/TanStack/router/tree/main/examples/react/start-basic-auth)** - Complete DIY implementation with database and sessions
610- **[Supabase Integration](https://github.com/TanStack/router/tree/main/examples/react/start-supabase-basic)** - Third-party service integration example
611- **[Client-side Context Auth](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes)** - Client-only authentication patterns
612​
613## Migration from Other Solutions
614​
615### From Client-Side Auth
616​
617If you're migrating from client-side authentication (localStorage, context only):
618​
6191. Move authentication logic to server functions
6202. Replace localStorage with server sessions
6213. Update route protection to use `beforeLoad`
6224. Add proper security headers and CSRF protection
623​
624### From Other Frameworks
625​
626- **Next.js**: Replace API routes with server functions, migrate NextAuth sessions
627- **SvelteKit**: Move form actions to server functions, update route protection
628​
629## Production Considerations
630​
631When choosing your authentication approach, consider these factors:
632​
633### Hosted vs DIY Comparison
634​
635**Hosted Solutions (Clerk, WorkOS, Better Auth):**
636​
637- Pre-built security measures and regular updates
638- UI components and user management features
639- Compliance certifications and audit trails
640- Support and documentation
641- Per-user or subscription pricing
642​
643**DIY Implementation:**
644​
645- Complete control over implementation and data
646- No ongoing subscription costs
647- Custom business logic and workflows
648- Responsibility for security updates and monitoring
649- Need to handle edge cases and attack vectors
650​
651### Security Considerations
652​
653Authentication systems need to handle various security aspects:
654​
655- Password hashing and timing attack prevention
656- Session management and fixation protection
657- CSRF and XSS protection
658- Rate limiting and brute force prevention
659- OAuth flow security
660- Compliance requirements (GDPR, CCPA, etc.)
661​
662## Next Steps
663​
664When implementing authentication, consider:
665​
666- **Security Review**: Review your implementation for security best practices
667- **Performance**: Add caching for user lookups and session validation
668- **Monitoring**: Add logging and monitoring for authentication events
669- **Compliance**: Ensure compliance with relevant regulations if storing personal data
670​
671For other authentication approaches, check the [Authentication Overview](./authentication-overview.md). For specific integration help, explore our [working examples](https://github.com/TanStack/router/tree/main/examples/react).