Open History to see the last commit
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 the tools for both through server functions, sessions, and route protection.
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'
51β
52// Login server function
53export const loginFn = createServerFn({ method: 'POST' })
54 .validator((data: { email: string; password: string }) => data)
55 .handler(async ({ data }) => {
56 // Verify credentials (replace with your auth logic)
57 const user = await authenticateUser(data.email, data.password)
58β
59 if (!user) {
60 return { error: 'Invalid credentials' }
61 }
62β
63 // Create session
64 const session = await useAppSession()
65 await session.update({
66 userId: user.id,
67 email: user.email,
68 })
69β
70 // Redirect to protected area
71 throw redirect({ to: '/dashboard' })
72 })
73β
74// Logout server function
75export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => {
76 const session = await useAppSession()
77 await session.clear()
78 throw redirect({ to: '/' })
79})
80β
81// Get current user
82export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler(
83 async () => {
84 const session = await useAppSession()
85 const userId = session.data.userId
86β
87 if (!userId) {
88 return null
89 }
90β
91 const user = await getUserById(userId)
92 return user ? { id: user.id, email: user.email, role: user.role } : null
93 },
94)
95```
96β
97### 2. Session Management
98β
99TanStack Start provides secure HTTP-only cookie sessions:
100β
101```tsx
102// utils/session.ts
103import { useSession } from '@tanstack/react-start/server'
104β
105type SessionData = {
106 userId?: string
107 email?: string
108 role?: string
109}
110β
111export function useAppSession() {
112 return useSession<SessionData>({
113 // Session configuration
114 name: 'app-session',
115 password: process.env.SESSION_SECRET!, // At least 32 characters
116 // Optional: customize cookie settings
117 cookie: {
118 secure: process.env.NODE_ENV === 'production',
119 sameSite: 'lax',
120 httpOnly: true,
121 },
122 })
123}
124```
125β
126### 3. Authentication Context
127β
128Load 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`.
129β
130Merge this pattern into your existing root route, keeping its metadata and document shell:
131β
132```tsx
133// routes/__root.tsx
134import {
135 createRootRoute,
136 HeadContent,
137 Outlet,
138 Scripts,
139} from '@tanstack/react-router'
140import type { ReactNode } from 'react'
141import { getCurrentUserFn } from '../server/auth'
142β
143export const Route = createRootRoute({
144 headers: () => ({ 'Cache-Control': 'private, no-store' }),
145 beforeLoad: async () => ({ user: await getCurrentUserFn() }),
146 component: Outlet,
147 shellComponent: RootDocument,
148})
149β
150function RootDocument({ children }: { children: ReactNode }) {
151 return (
152 <html>
153 <head>
154 <HeadContent />
155 </head>
156 <body>
157 {children}
158 <Scripts />
159 </body>
160 </html>
161 )
162}
163```
164β
165The 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.
166β
167Read that state from a descendant component:
168β
169```tsx
170// components/AuthStatus.tsx
171import { Route } from '../routes/__root'
172β
173export function AuthStatus() {
174 const { user } = Route.useRouteContext()
175 return <span>{user ? user.email : 'Signed out'}</span>
176}
177```
178β
179After 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.
180β
181### 4. Route Protection
182β
183Protect routes using `beforeLoad`:
184β
185```tsx
186// routes/_authed.tsx - Layout route for protected pages
187import { createFileRoute, redirect } from '@tanstack/react-router'
188import { getCurrentUserFn } from '../server/auth'
189β
190export const Route = createFileRoute('/_authed')({
191 beforeLoad: async ({ location }) => {
192 const user = await getCurrentUserFn()
193β
194 if (!user) {
195 throw redirect({
196 to: '/login',
197 search: { redirect: location.href },
198 })
199 }
200β
201 // Pass user to child routes
202 return { user }
203 },
204})
205```
206β
207```tsx
208// routes/_authed/dashboard.tsx - Protected route
209import { createFileRoute } from '@tanstack/react-router'
210β
211export const Route = createFileRoute('/_authed/dashboard')({
212 component: DashboardComponent,
213})
214β
215function DashboardComponent() {
216 const { user } = Route.useRouteContext()
217β
218 return (
219 <div>
220 <h1>Welcome, {user.email}!</h1>
221 {/* Dashboard content */}
222 </div>
223 )
224}
225```
226β
227## Implementation Patterns
228β
229### Basic Email/Password Authentication
230β
231```tsx
232// server/auth.ts
233import bcrypt from 'bcryptjs'
234import { createServerFn } from '@tanstack/react-start'
235β
236// User registration
237export const registerFn = createServerFn({ method: 'POST' })
238 .validator((data: { email: string; password: string; name: string }) => data)
239 .handler(async ({ data }) => {
240 // Check if user exists
241 const existingUser = await getUserByEmail(data.email)
242 if (existingUser) {
243 return { error: 'User already exists' }
244 }
245β
246 // Hash password
247 const hashedPassword = await bcrypt.hash(data.password, 12)
248β
249 // Create user
250 const user = await createUser({
251 email: data.email,
252 password: hashedPassword,
253 name: data.name,
254 })
255β
256 // Create session
257 const session = await useAppSession()
258 await session.update({ userId: user.id })
259β
260 return { success: true, user: { id: user.id, email: user.email } }
261 })
262β
263async function authenticateUser(email: string, password: string) {
264 const user = await getUserByEmail(email)
265 if (!user) return null
266β
267 const isValid = await bcrypt.compare(password, user.password)
268 return isValid ? user : null
269}
270```
271β
272### Role-Based Access Control (RBAC)
273β
274```tsx
275// utils/auth.ts
276export const roles = {
277 USER: 'user',
278 ADMIN: 'admin',
279 MODERATOR: 'moderator',
280} as const
281β
282type Role = (typeof roles)[keyof typeof roles]
283β
284export function hasPermission(userRole: Role, requiredRole: Role): boolean {
285 const hierarchy = {
286 [roles.USER]: 0,
287 [roles.MODERATOR]: 1,
288 [roles.ADMIN]: 2,
289 }
290β
291 return hierarchy[userRole] >= hierarchy[requiredRole]
292}
293β
294// Protected route with role check
295export const Route = createFileRoute('/_authed/admin/')({
296 beforeLoad: async ({ context }) => {
297 if (!hasPermission(context.user.role, roles.ADMIN)) {
298 throw redirect({ to: '/unauthorized' })
299 }
300 },
301})
302```
303β
304### Social Authentication Integration
305β
306```tsx
307// Example with OAuth providers
308export const authProviders = {
309 google: {
310 clientId: process.env.GOOGLE_CLIENT_ID!,
311 redirectUri: `${process.env.APP_URL}/auth/google/callback`,
312 },
313 github: {
314 clientId: process.env.GITHUB_CLIENT_ID!,
315 redirectUri: `${process.env.APP_URL}/auth/github/callback`,
316 },
317}
318β
319export const initiateOAuthFn = createServerFn({ method: 'POST' })
320 .validator((data: { provider: 'google' | 'github' }) => data)
321 .handler(async ({ data }) => {
322 const provider = authProviders[data.provider]
323 const state = generateRandomState()
324β
325 // Store state in session for CSRF protection
326 const session = await useAppSession()
327 await session.update({ oauthState: state })
328β
329 // Generate OAuth URL
330 const authUrl = generateOAuthUrl(provider, state)
331β
332 throw redirect({ href: authUrl })
333 })
334```
335β
336### Password Reset Flow
337β
338```tsx
339// Password reset request
340export const requestPasswordResetFn = createServerFn({ method: 'POST' })
341 .validator((data: { email: string }) => data)
342 .handler(async ({ data }) => {
343 const user = await getUserByEmail(data.email)
344 if (!user) {
345 // Don't reveal if email exists
346 return { success: true }
347 }
348β
349 const token = generateSecureToken()
350 const expires = new Date(Date.now() + 60 * 60 * 1000) // 1 hour
351β
352 await savePasswordResetToken(user.id, token, expires)
353 await sendPasswordResetEmail(user.email, token)
354β
355 return { success: true }
356 })
357β
358// Password reset confirmation
359export const resetPasswordFn = createServerFn({ method: 'POST' })
360 .validator((data: { token: string; newPassword: string }) => data)
361 .handler(async ({ data }) => {
362 const resetToken = await getPasswordResetToken(data.token)
363β
364 if (!resetToken || resetToken.expires < new Date()) {
365 return { error: 'Invalid or expired token' }
366 }
367β
368 const hashedPassword = await bcrypt.hash(data.newPassword, 12)
369 await updateUserPassword(resetToken.userId, hashedPassword)
370 await deletePasswordResetToken(data.token)
371β
372 return { success: true }
373 })
374```
375β
376## Security Best Practices
377β
378### 1. Password Security
379β
380```tsx
381// Use strong hashing (bcrypt, scrypt, or argon2)
382import bcrypt from 'bcryptjs'
383β
384const saltRounds = 12 // Adjust based on your security needs
385const hashedPassword = await bcrypt.hash(password, saltRounds)
386```
387β
388### 2. Session Security
389β
390```tsx
391// Use secure session configuration
392export function useAppSession() {
393 return useSession({
394 name: 'app-session',
395 password: process.env.SESSION_SECRET!, // 32+ characters
396 cookie: {
397 secure: process.env.NODE_ENV === 'production', // HTTPS only in production
398 sameSite: 'lax', // CSRF protection
399 httpOnly: true, // XSS protection
400 maxAge: 7 * 24 * 60 * 60, // 7 days
401 },
402 })
403}
404```
405β
406### 3. Rate Limiting
407β
408```tsx
409// Simple in-memory rate limiting (use Redis in production)
410const loginAttempts = new Map<string, { count: number; resetTime: number }>()
411β
412export const rateLimitLogin = (ip: string): boolean => {
413 const now = Date.now()
414 const attempts = loginAttempts.get(ip)
415β
416 if (!attempts || now > attempts.resetTime) {
417 loginAttempts.set(ip, { count: 1, resetTime: now + 15 * 60 * 1000 }) // 15 min
418 return true
419 }
420β
421 if (attempts.count >= 5) {
422 return false // Too many attempts
423 }
424β
425 attempts.count++
426 return true
427}
428```
429β
430### 4. Input Validation
431β
432```tsx
433import { z } from 'zod'
434β
435const loginSchema = z.object({
436 email: z.string().email().max(255),
437 password: z.string().min(8).max(100),
438})
439β
440export const loginFn = createServerFn({ method: 'POST' })
441 .validator((data) => loginSchema.parse(data))
442 .handler(async ({ data }) => {
443 // data is now validated
444 })
445```
446β
447## Testing Authentication
448β
449### Unit Testing Server Functions
450β
451```tsx
452// __tests__/auth.test.ts
453import { describe, it, expect, beforeEach } from 'vitest'
454import { loginFn } from '../server/auth'
455β
456describe('Authentication', () => {
457 beforeEach(async () => {
458 await setupTestDatabase()
459 })
460β
461 it('should login with valid credentials', async () => {
462 const result = await loginFn({
463 data: { email: 'test@example.com', password: 'password123' },
464 })
465β
466 expect(result.error).toBeUndefined()
467 expect(result.user).toBeDefined()
468 })
469β
470 it('should reject invalid credentials', async () => {
471 const result = await loginFn({
472 data: { email: 'test@example.com', password: 'wrongpassword' },
473 })
474β
475 expect(result.error).toBe('Invalid credentials')
476 })
477})
478```
479β
480### Integration Testing
481β
482```tsx
483// __tests__/auth-flow.test.tsx
484import { render, screen, fireEvent, waitFor } from '@testing-library/react'
485import { RouterProvider, createMemoryHistory } from '@tanstack/react-router'
486import { router } from '../router'
487β
488describe('Authentication Flow', () => {
489 it('should redirect to login when accessing protected route', async () => {
490 const history = createMemoryHistory()
491 history.push('/dashboard') // Protected route
492β
493 render(<RouterProvider router={router} history={history} />)
494β
495 await waitFor(() => {
496 expect(screen.getByText('Login')).toBeInTheDocument()
497 })
498 })
499})
500```
501β
502## Common Patterns
503β
504### Loading States
505β
506Call 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.
507β
508```tsx
509// components/LoginForm.tsx
510import { useState } from 'react'
511import type { FormEvent } from 'react'
512import { useHydrated, useRouter } from '@tanstack/react-router'
513import { useServerFn } from '@tanstack/react-start'
514import { loginFn } from '../server/auth'
515β
516export function LoginForm() {
517 const hydrated = useHydrated()
518 const [isLoading, setIsLoading] = useState(false)
519 const [error, setError] = useState('')
520 const login = useServerFn(loginFn)
521 const router = useRouter()
522β
523 const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
524 event.preventDefault()
525 const formData = new FormData(event.currentTarget)
526 const email = formData.get('email')
527 const password = formData.get('password')
528 if (typeof email !== 'string' || typeof password !== 'string') {
529 return
530 }
531β
532 setIsLoading(true)
533 setError('')
534 try {
535 const result = await login({ data: { email, password } })
536 if (result?.error) {
537 setError(result.error)
538 return
539 }
540 await router.invalidate()
541 } catch {
542 setError('Login failed. Please try again.')
543 } finally {
544 setIsLoading(false)
545 }
546 }
547β
548 return (
549 <form method="post" onSubmit={handleSubmit}>
550 <fieldset disabled={!hydrated || isLoading}>
551 <label>
552 Email
553 <input name="email" type="email" autoComplete="username" required />
554 </label>
555 <label>
556 Password
557 <input
558 name="password"
559 type="password"
560 autoComplete="current-password"
561 required
562 />
563 </label>
564 <button type="submit" disabled={isLoading}>
565 {isLoading ? 'Logging in...' : 'Login'}
566 </button>
567 </fieldset>
568 <p role="alert">{error}</p>
569 </form>
570 )
571}
572```
573β
574### Remember Me Functionality
575β
576```tsx
577export const loginFn = createServerFn({ method: 'POST' })
578 .validator(
579 (data: { email: string; password: string; rememberMe?: boolean }) => data,
580 )
581 .handler(async ({ data }) => {
582 const user = await authenticateUser(data.email, data.password)
583 if (!user) return { error: 'Invalid credentials' }
584β
585 const session = await useAppSession()
586 await session.update(
587 { userId: user.id },
588 {
589 // Extend session if remember me is checked
590 maxAge: data.rememberMe ? 30 * 24 * 60 * 60 : undefined, // 30 days vs session
591 },
592 )
593β
594 return { success: true }
595 })
596```
597β
598## Working Examples
599β
600Study these implementations to understand different authentication patterns:
601β
602- **[Basic Auth with Prisma](https://github.com/TanStack/router/tree/main/examples/react/start-basic-auth)** - Complete DIY implementation with database and sessions
603- **[Supabase Integration](https://github.com/TanStack/router/tree/main/examples/react/start-supabase-basic)** - Third-party service integration example
604- **[Client-side Context Auth](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes)** - Client-only authentication patterns
605β
606## Migration from Other Solutions
607β
608### From Client-Side Auth
609β
610If you're migrating from client-side authentication (localStorage, context only):
611β
6121. Move authentication logic to server functions
6132. Replace localStorage with server sessions
6143. Update route protection to use `beforeLoad`
6154. Add proper security headers and CSRF protection
616β
617### From Other Frameworks
618β
619- **Next.js**: Replace API routes with server functions, migrate NextAuth sessions
620- **Remix**: Convert loaders/actions to server functions, adapt session patterns
621- **SvelteKit**: Move form actions to server functions, update route protection
622β
623## Production Considerations
624β
625When choosing your authentication approach, consider these factors:
626β
627### Hosted vs DIY Comparison
628β
629**Hosted Solutions (Clerk, WorkOS, Better Auth):**
630β
631- Pre-built security measures and regular updates
632- UI components and user management features
633- Compliance certifications and audit trails
634- Support and documentation
635- Per-user or subscription pricing
636β
637**DIY Implementation:**
638β
639- Complete control over implementation and data
640- No ongoing subscription costs
641- Custom business logic and workflows
642- Responsibility for security updates and monitoring
643- Need to handle edge cases and attack vectors
644β
645### Security Considerations
646β
647Authentication systems need to handle various security aspects:
648β
649- Password hashing and timing attack prevention
650- Session management and fixation protection
651- CSRF and XSS protection
652- Rate limiting and brute force prevention
653- OAuth flow security
654- Compliance requirements (GDPR, CCPA, etc.)
655β
656## Next Steps
657β
658When implementing authentication, consider:
659β
660- **Security Review**: Review your implementation for security best practices
661- **Performance**: Add caching for user lookups and session validation
662- **Monitoring**: Add logging and monitoring for authentication events
663- **Compliance**: Ensure compliance with relevant regulations if storing personal data
664β
665For 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).