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

authentication.md

658 lines18.7 KB

1---
2id: authentication
3title: Implement Authentication in SolidJS
4description: Implement sessions, sign-in, sign-out, protected routes, and server-side authorization in a TanStack Start SolidJS app.
5---
6​
7Implement the authentication workflow in your SolidJS app, from sessions and sign-in to protected routes and authorization.
8​
9To compare libraries and hosted services, read [Choose Authentication for SolidJS 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/solid-start'
50import { redirect } from '@tanstack/solid-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.get('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 },
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/solid-start/server'
104​
105type SessionData = {
106 userId?: string
107 email?: string
108 role?: string
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 })
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/solid-router'
140import type { JSX } from 'solid-js'
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: JSX.Element }) {
151 return (
152 <html>
153 <head>
154 <HeadContent />
155 </head>
156 <body>
157 {children}
158 <Scripts />
159 </body>
160 </html>
161 )
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 context = Route.useRouteContext()
175 return <span>{context().user?.email ?? 'Signed out'}</span>
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/solid-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/solid-router'
210​
211export const Route = createFileRoute('/_authed/dashboard')({
212 component: DashboardComponent,
213})
214​
215function DashboardComponent() {
216 const context = Route.useRouteContext()
217​
218 return (
219 <div>
220 <h1>Welcome, {context().user.email}!</h1>
221 {/* Dashboard content */}
222 </div>
223 )
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/solid-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
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]
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 },
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 })
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
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 '@solidjs/testing-library'
485import { RouterProvider, createMemoryHistory } from '@tanstack/solid-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 { createSignal } from 'solid-js'
511import { useHydrated, useRouter } from '@tanstack/solid-router'
512import { useServerFn } from '@tanstack/solid-start'
513import { loginFn } from '../server/auth'
514​
515export function LoginForm() {
516 const hydrated = useHydrated()
517 const [isLoading, setIsLoading] = createSignal(false)
518 const [error, setError] = createSignal('')
519 const login = useServerFn(loginFn)
520 const router = useRouter()
521​
522 const handleSubmit = async (
523 event: SubmitEvent & { currentTarget: HTMLFormElement },
524 ) => {
525 event.preventDefault()
526 const formData = new FormData(event.currentTarget)
527 const email = formData.get('email')
528 const password = formData.get('password')
529 if (typeof email !== 'string' || typeof password !== 'string') {
530 return
531 }
532​
533 setIsLoading(true)
534 setError('')
535 try {
536 const result = await login({ data: { email, password } })
537 if (result?.error) {
538 setError(result.error)
539 return
540 }
541 await router.invalidate()
542 } catch {
543 setError('Login failed. Please try again.')
544 } finally {
545 setIsLoading(false)
546 }
547 }
548​
549 return (
550 <form method="post" onSubmit={handleSubmit}>
551 <fieldset disabled={!hydrated() || isLoading()}>
552 <label>
553 Email
554 <input name="email" type="email" autocomplete="username" required />
555 </label>
556 <label>
557 Password
558 <input
559 name="password"
560 type="password"
561 autocomplete="current-password"
562 required
563 />
564 </label>
565 <button type="submit" disabled={isLoading()}>
566 {isLoading() ? 'Logging in...' : 'Login'}
567 </button>
568 </fieldset>
569 <p role="alert">{error()}</p>
570 </form>
571 )
573```
574​
575### Remember Me Functionality
576​
577```tsx
578export const loginFn = createServerFn({ method: 'POST' })
579 .validator(
580 (data: { email: string; password: string; rememberMe?: boolean }) => data,
581 )
582 .handler(async ({ data }) => {
583 const user = await authenticateUser(data.email, data.password)
584 if (!user) return { error: 'Invalid credentials' }
585​
586 const session = await useAppSession()
587 await session.update(
588 { userId: user.id },
589 {
590 // Extend session if remember me is checked
591 maxAge: data.rememberMe ? 30 * 24 * 60 * 60 : undefined, // 30 days vs session
592 },
593 )
594​
595 return { success: true }
596 })
597```
598​
599## Migration from Other Solutions
600​
601### From Client-Side Auth
602​
603If you're migrating from client-side authentication (localStorage, context only):
604​
6051. Move authentication logic to server functions
6062. Replace localStorage with server sessions
6073. Update route protection to use `beforeLoad`
6084. Add proper security headers and CSRF protection
609​
610### From Other Frameworks
611​
612- **Next.js**: Replace API routes with server functions, migrate NextAuth sessions
613- **Remix**: Convert loaders/actions to server functions, adapt session patterns
614- **SvelteKit**: Move form actions to server functions, update route protection
615​
616## Production Considerations
617​
618When choosing your authentication approach, consider these factors:
619​
620### Hosted vs DIY Comparison
621​
622**Hosted Solutions (Clerk, WorkOS, Better Auth):**
623​
624- Pre-built security measures and regular updates
625- UI components and user management features
626- Compliance certifications and audit trails
627- Support and documentation
628- Per-user or subscription pricing
629​
630**DIY Implementation:**
631​
632- Complete control over implementation and data
633- No ongoing subscription costs
634- Custom business logic and workflows
635- Responsibility for security updates and monitoring
636- Need to handle edge cases and attack vectors
637​
638### Security Considerations
639​
640Authentication systems need to handle various security aspects:
641​
642- Password hashing and timing attack prevention
643- Session management and fixation protection
644- CSRF and XSS protection
645- Rate limiting and brute force prevention
646- OAuth flow security
647- Compliance requirements (GDPR, CCPA, etc.)
648​
649## Next Steps
650​
651When implementing authentication, consider:
652​
653- **Security Review**: Review your implementation for security best practices
654- **Performance**: Add caching for user lookups and session validation
655- **Monitoring**: Add logging and monitoring for authentication events
656- **Compliance**: Ensure compliance with relevant regulations if storing personal data
657​
658For other authentication approaches, check the [Authentication Overview](./authentication-overview.md). For specific integration help, see the [How-to Guides](/router/latest/docs/framework/solid/how-to/README.md#authentication) or explore our [working examples](https://github.com/TanStack/router/tree/main/examples/solid).