Open History to see the last commit
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 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/solid-start'
50import { redirect } from '@tanstack/solid-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 },
93)
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/solid-start/server'
112β
113type SessionData = {
114 userId: string
115 oauthState: string
116}
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 )
138}
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/solid-router'
159import type { JSX } from 'solid-js'
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: JSX.Element }) {
170 return (
171 <html>
172 <head>
173 <HeadContent />
174 </head>
175 <body>
176 {children}
177 <Scripts />
178 </body>
179 </html>
180 )
181}
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 context = Route.useRouteContext()
194 return <span>{context().user?.email ?? 'Signed out'}</span>
195}
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/solid-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/solid-router'
229β
230export const Route = createFileRoute('/_authed/dashboard')({
231 component: DashboardComponent,
232})
233β
234function DashboardComponent() {
235 const context = Route.useRouteContext()
236β
237 return (
238 <div>
239 <h1>Welcome, {context().user.email}!</h1>
240 {/* Dashboard content */}
241 </div>
242 )
243}
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/solid-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
289}
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]
312}
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 },
337}
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
436}
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 '@solidjs/testing-library'
494import { RouterProvider, createMemoryHistory } from '@tanstack/solid-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 { createSignal } from 'solid-js'
520import { useHydrated, useRouter } from '@tanstack/solid-router'
521import { useServerFn } from '@tanstack/solid-start'
522import { loginFn } from '../server/auth'
523β
524export function LoginForm() {
525 const hydrated = useHydrated()
526 const [isLoading, setIsLoading] = createSignal(false)
527 const [error, setError] = createSignal('')
528 const login = useServerFn(loginFn)
529 const router = useRouter()
530β
531 const handleSubmit = async (
532 event: SubmitEvent & { currentTarget: HTMLFormElement },
533 ) => {
534 event.preventDefault()
535 const formData = new FormData(event.currentTarget)
536 const email = formData.get('email')
537 const password = formData.get('password')
538 if (typeof email !== 'string' || typeof password !== 'string') {
539 return
540 }
541β
542 setIsLoading(true)
543 setError('')
544 try {
545 const result = await login({ data: { email, password } })
546 if (result?.error) {
547 setError(result.error)
548 return
549 }
550 await router.invalidate()
551 } catch {
552 setError('Login failed. Please try again.')
553 } finally {
554 setIsLoading(false)
555 }
556 }
557β
558 return (
559 <form method="post" onSubmit={handleSubmit}>
560 <fieldset disabled={!hydrated() || isLoading()}>
561 <label>
562 Email
563 <input name="email" type="email" autocomplete="username" required />
564 </label>
565 <label>
566 Password
567 <input
568 name="password"
569 type="password"
570 autocomplete="current-password"
571 required
572 />
573 </label>
574 <button type="submit" disabled={isLoading()}>
575 {isLoading() ? 'Logging in...' : 'Login'}
576 </button>
577 </fieldset>
578 <p role="alert">{error()}</p>
579 </form>
580 )
581}
582```
583β
584### Remember Me Functionality
585β
586```tsx
587export const loginFn = createServerFn({ method: 'POST' })
588 .validator(
589 (data: { email: string; password: string; rememberMe?: boolean }) => data,
590 )
591 .handler(async ({ data }) => {
592 const user = await authenticateUser(data.email, data.password)
593 if (!user) {
594 return { error: 'Invalid credentials' }
595 }
596β
597 const ttl = data.rememberMe ? 30 * 24 * 60 * 60 : 8 * 60 * 60
598 const session = await getAppSession(ttl)
599 session.userId = user.id
600 await session.save()
601β
602 return { success: true }
603 })
604```
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- **SvelteKit**: Move form actions to server functions, update route protection
621β
622## Production Considerations
623β
624When choosing your authentication approach, consider these factors:
625β
626### Hosted vs DIY Comparison
627β
628**Hosted Solutions (Clerk, WorkOS, Better Auth):**
629β
630- Pre-built security measures and regular updates
631- UI components and user management features
632- Compliance certifications and audit trails
633- Support and documentation
634- Per-user or subscription pricing
635β
636**DIY Implementation:**
637β
638- Complete control over implementation and data
639- No ongoing subscription costs
640- Custom business logic and workflows
641- Responsibility for security updates and monitoring
642- Need to handle edge cases and attack vectors
643β
644### Security Considerations
645β
646Authentication systems need to handle various security aspects:
647β
648- Password hashing and timing attack prevention
649- Session management and fixation protection
650- CSRF and XSS protection
651- Rate limiting and brute force prevention
652- OAuth flow security
653- Compliance requirements (GDPR, CCPA, etc.)
654β
655## Next Steps
656β
657When implementing authentication, consider:
658β
659- **Security Review**: Review your implementation for security best practices
660- **Performance**: Add caching for user lookups and session validation
661- **Monitoring**: Add logging and monitoring for authentication events
662- **Compliance**: Ensure compliance with relevant regulations if storing personal data
663β
664For 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).