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

authentication-overview.md

246 lines9.7 KB

1---
2id: authentication-overview
3title: Choose Authentication for React Apps
4description: Compare hosted services, auth libraries, and custom authentication for React apps built with TanStack Start. Choose an approach before implementing sessions and authorization.
5---
6​
7Choose how your React app will handle identity, sessions, and permissions. This page compares approaches and providers. Once you have chosen an approach, use [Implement Authentication in React](./authentication.md) for the application workflow.
8​
9## Authentication vs Authorization
10​
11- **Authentication**: Who is this user? (Login/logout, identity verification)
12- **Authorization**: What can this user do? (Permissions, roles, access control)
13​
14## Architecture Overview
15​
16### Full-Stack Authentication Model
17​
18**Server-Side (Secure)**
19​
20- Session storage and validation
21- User credential verification
22- Database operations
23- Token generation/verification
24- Protected API endpoints
25​
26**Client-Side (Public)**
27​
28- Authentication state management
29- Route protection logic
30- Login/logout user interface
31- Redirect handling
32​
33**Isomorphic (Both)**
34​
35- Route loaders checking auth state
36- Shared validation logic
37- User profile data access
38​
39### Session Management Patterns
40​
41**HTTP-Only Cookies (Recommended)**
42​
43- Most secure approach - not accessible via JavaScript
44- Automatic browser handling
45- Built-in CSRF protection with `sameSite`
46- Best for traditional web applications
47​
48**JWT Tokens**
49​
50- Stateless authentication
51- Good for API-first applications
52- Requires careful handling to avoid XSS vulnerabilities
53- Consider refresh token rotation
54​
55**Server-Side Sessions**
56​
57- Centralized session control
58- Easy to revoke sessions
59- Requires session storage (database, Redis)
60- Good for applications requiring immediate session control
61​
62### Route Protection Architecture
63​
64**Layout Route Pattern (Recommended)**
65​
66- Protect entire route subtrees with parent layout routes
67- Centralized authentication logic
68- Automatic protection for all child routes
69- Clean separation of authenticated vs public routes
70​
71**Component-Level Protection**
72​
73- Conditional rendering within components
74- More granular control over UI states
75- Good for mixed public/private content on same route
76- Requires careful handling to prevent layout shifts
77​
78**Data/API Protection (Security Boundary)**
79​
80- Authorize every server function, server route, or API endpoint that reads or writes private data
81- Reject unauthorized requests even if no protected route was loaded first
82- Treat route guards as UX and navigation control, not as the data boundary
83​
84### State Management Patterns
85​
86**Server-Driven State (Recommended)**
87​
88- Authentication state sourced from server on each request
89- Always up-to-date with server state
90- Works seamlessly with SSR
91- Best security - server is source of truth
92​
93**Context-Based State**
94​
95- Client-side authentication state management
96- Good for third-party auth providers (Auth0, Firebase)
97- Requires careful synchronization with server state
98- Consider for highly interactive client-first applications
99​
100**Hybrid Approach**
101​
102- Initial state from server, client-side updates
103- Balance between security and UX
104- Periodic server-side validation
105​
106## Authentication Options
107​
108### 🏒 Partner Solutions
109​
110- **[WorkOS](https://workos.com)**
111- **[Clerk](https://clerk.dev)**
112​
113### πŸ› οΈ DIY Authentication
114​
115Build your own authentication system using TanStack Start's server functions and session management. Start with the [Authentication Server Primitives](./authentication-server-primitives.md) guide β€” it covers session cookies (`HttpOnly`/`Secure`/`SameSite`/`__Host-`), session lookup as middleware, OAuth `state` + PKCE, password-reset enumeration defense, CSRF, rate limiting, and session rotation, with the WRONG/CORRECT patterns that catch the common mistakes.
116​
117- **Full Control**: Complete customization over authentication flow
118- **Server Primitives**: Sessions, OAuth, CSRF, rate limiting β€” see [Authentication Server Primitives](./authentication-server-primitives.md)
119- **Session Management**: HTTP-only cookies written with `setCookie`, read with `getCookie`
120- **Type Safety**: End-to-end type safety for authentication state
121​
122### 🌐 Other Excellent Options
123​
124**Open Source & Community Solutions:**
125​
126- **[Better Auth](https://www.better-auth.com/)** - Modern, TypeScript-first authentication library
127- **[Auth.js](https://authjs.dev/)** (formerly NextAuth.js) - Popular authentication library for React
128​
129**Hosted Services:**
130​
131- **[Supabase Auth](https://supabase.com/auth)** - Open source Firebase alternative with built-in auth
132- **[Auth0](https://auth0.com/)** - Established authentication platform with extensive features
133- **[Firebase Auth](https://firebase.google.com/docs/auth)** - Google's authentication service
134​
135## Partner Solutions
136​
137### WorkOS - Enterprise Authentication
138​
139<a href="https://workos.com/" alt="WorkOS Logo">
140 <picture>
141 <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/tanstack/tanstack.com/main/src/images/workos-white.svg" width="280">
142 <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/tanstack/tanstack.com/main/src/images/workos-black.svg" width="280">
143 <img alt="WorkOS logo" src="https://raw.githubusercontent.com/tanstack/tanstack.com/main/src/images/workos-black.svg" width="280">
144 </picture>
145</a>
146​
147- **Single Sign-On (SSO)** - SAML, OIDC, and OAuth integrations
148- **Directory Sync** - SCIM provisioning with Active Directory and Google Workspace
149- **Multi-factor Authentication** - Enterprise-grade security options
150- **Compliance Ready** - SOC 2, GDPR, and CCPA compliant
151​
152[Visit WorkOS β†’](https://workos.com/) | [View example β†’](https://github.com/TanStack/router/tree/main/examples/react/start-workos)
153​
154### Clerk - Complete Authentication Platform
155​
156<a href="https://go.clerk.com/wOwHtuJ" alt="Clerk Logo">
157 <picture>
158 <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/tanstack/tanstack.com/main/src/images/clerk-logo-dark.svg" width="280">
159 <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/tanstack/tanstack.com/main/src/images/clerk-logo-light.svg" width="280">
160 <img alt="Clerk logo" src="https://raw.githubusercontent.com/tanstack/tanstack.com/main/src/images/clerk-logo-light.svg" width="280">
161 </picture>
162</a>
163​
164- **Ready-to-use UI Components** - Sign-in, sign-up, user profile, and organization management
165- **Social Logins** - Google, GitHub, Discord, and 20+ providers
166- **Multi-factor Authentication** - SMS, TOTP, and backup codes
167- **Organizations & Teams** - Built-in support for team-based applications
168​
169[Visit Clerk β†’](https://go.clerk.com/wOwHtuJ) | [Sign up free β†’](https://go.clerk.com/PrSDXti) | [View example β†’](https://github.com/TanStack/router/tree/main/examples/react/start-clerk-basic)
170​
171## Examples
172​
173**Partner Solutions:**
174​
175- [Clerk Integration](https://github.com/TanStack/router/tree/main/examples/react/start-clerk-basic)
176- [WorkOS Integration](https://github.com/TanStack/router/tree/main/examples/react/start-workos)
177​
178**DIY Implementations:**
179​
180- [Basic Auth with Prisma](https://github.com/TanStack/router/tree/main/examples/react/start-basic-auth)
181- [Supabase Auth](https://github.com/TanStack/router/tree/main/examples/react/start-supabase-basic)
182​
183**Client-Side Examples:**
184​
185- [Basic Authentication](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes)
186- [Firebase Auth](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes-firebase)
187​
188## Architecture Decision Guide
189​
190### Choosing an Authentication Approach
191​
192**Partner Solutions:**
193​
194- Focus on your core business logic
195- Enterprise features (SSO, compliance)
196- Managed security and updates
197- Pre-built UI components
198​
199**OSS Solutions:**
200​
201- Community-driven development
202- Specific customizations
203- Self-hosted solutions
204- Avoid vendor lock-in
205​
206**DIY Implementation:**
207​
208- Complete control over the auth flow
209- Custom security requirements
210- Specific business logic needs
211- Full ownership of authentication data
212​
213### Production Auth Checklist
214​
215- Use HTTPS in production and set a strong session secret.
216- Store sessions in `HttpOnly`, `Secure`, `SameSite` cookies. Do not store session tokens in `localStorage` or `sessionStorage`.
217- Enforce auth in every server function, server route, or API endpoint that reads or writes private user, tenant, or account data. Use `beforeLoad` for page UX, not as the data boundary.
218- Use `.validator()` on every server function that accepts input.
219- Hash passwords with bcrypt, scrypt, or Argon2. For missing users, verify against a dummy hash and return the same login/reset message.
220- Rate limit login, registration, and password-reset endpoints.
221- Use CSRF or same-origin protections for non-GET server functions and server routes.
222- Log authentication events and monitor failures.
223- Test direct unauthenticated calls to protected server functions; they should reject before returning data.
224​
225## Next Steps
226​
227- **Partner solutions** β†’ [Clerk](https://go.clerk.com/wOwHtuJ) or [WorkOS](https://workos.com/)
228- **DIY implementation** β†’ [Authentication Guide](./authentication.md)
229- **Examples** β†’ [Working implementations](https://github.com/TanStack/router/tree/main/examples/react)
230​
231## Resources
232​
233**Implementation Guides:**
234​
235- [Authentication Server Primitives](./authentication-server-primitives.md) β€” sessions, cookies, OAuth, CSRF, rate limiting (the server half)
236- [Authentication Patterns](./authentication.md)
237- [Router Authentication Guide](/router/latest/docs/framework/react/guide/authenticated-routes)
238​
239**Foundation Concepts:**
240​
241- [Execution Model](./execution-model.md)
242- [Server Functions](./server-functions.md)
243​
244**Step-by-Step Tutorials:**
245​
246- [Router How-to Guides](/router/latest/docs/framework/react/how-to/README.md#authentication)