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

hydration-errors.md

129 lines3.7 KB

1---
2id: hydration-errors
3title: Hydration Errors
4---
5​
6### Why it happens
7​
8- **Mismatch**: Server HTML differs from client render during hydration
9- **Common causes**: `Intl` (locale/time zone), `Date.now()`, random IDs, responsive-only logic, feature flags, user prefs
10​
11### Strategy 1 β€” Make server and client match
12​
13- **Pick a deterministic locale/time zone on the server** and use the same on the client
14- **Source of truth**: cookie (preferred) or `Accept-Language` header
15- **Compute once on the server** and hydrate as initial state
16​
17```tsx
18// src/start.ts
19import { createStart, createMiddleware } from '@tanstack/solid-start'
20import {
21 getRequestHeader,
22 getCookie,
23 setCookie,
24} from '@tanstack/solid-start/server'
25​
26const localeTzMiddleware = createMiddleware().server(async ({ next }) => {
27 const header = getRequestHeader('accept-language')
28 const headerLocale = header?.split(',')[0] || 'en-US'
29 const cookieLocale = getCookie('locale')
30 const cookieTz = getCookie('tz') // set by client later (see Strategy 2)
31​
32 const locale = cookieLocale || headerLocale
33 const timeZone = cookieTz || 'UTC'
34​
35 setCookie('locale', locale, { path: '/', maxAge: 60 * 60 * 24 * 365 })
36​
37 return next({ context: { locale, timeZone } })
38})
39​
40export const startInstance = createStart(() => ({
41 requestMiddleware: [localeTzMiddleware],
42}))
43```
44​
45```tsx
46// src/routes/index.tsx (example)
47import { createFileRoute } from '@tanstack/solid-router'
48import { createServerFn } from '@tanstack/solid-start'
49import { getCookie } from '@tanstack/solid-start/server'
50​
51export const getServerNow = createServerFn().handler(async () => {
52 const locale = getCookie('locale') || 'en-US'
53 const timeZone = getCookie('tz') || 'UTC'
54 return new Intl.DateTimeFormat(locale, {
55 dateStyle: 'medium',
56 timeStyle: 'short',
57 timeZone,
58 }).format(new Date())
59})
60​
61export const Route = createFileRoute('/')({
62 loader: () => getServerNow(),
63 component: () => {
64 const serverNow = Route.useLoaderData() as string
65 return <time dateTime={serverNow}>{serverNow}</time>
66 },
67})
68```
69​
70### Strategy 2 β€” Let the client tell you its environment
71​
72- On first visit, set a cookie with the client time zone; SSR uses `UTC` until then
73​
74```tsx
75import { ClientOnly } from '@tanstack/solid-router'
76​
77function SetTimeZoneCookie() {
78 if (typeof window !== 'undefined') {
79 const tz = Intl.DateTimeFormat().resolvedOptions().timeZone
80 document.cookie = `tz=${tz}; path=/; max-age=31536000`
81 }
82 return null
84​
85;<ClientOnly fallback={null}>
86 <SetTimeZoneCookie />
87</ClientOnly>
88```
89​
90### Strategy 3 β€” Make it client-only
91​
92- Use `<ClientOnly>` or Solid’s `<NoHydration>` to avoid SSR/hydration
93​
94```tsx
95import { ClientOnly } from '@tanstack/solid-router'
96import { NoHydration } from 'solid-js/web'
97​
98<ClientOnly fallback={<span>β€”</span>}>
99 <RelativeTime ts={someTs} />
100</ClientOnly>
101​
102<NoHydration>
103 <time>{new Date().toLocaleString()}</time>
104</NoHydration>
105```
106​
107### Strategy 4 β€” Disable or limit SSR for the route
108​
109- Use Selective SSR to avoid rendering the component on the server
110​
111```tsx
112export const Route = createFileRoute('/unstable')({
113 ssr: 'data-only', // or false
114 component: () => <ExpensiveViz />,
115})
116```
117​
118### Strategy 5 β€” Last resort suppression
119​
120- Prefer the tools above; avoid mismatches instead of hiding them
121​
122### Checklist
123​
124- **Deterministic inputs**: locale, time zone, feature flags
125- **Prefer cookies** for client context; fallback to `Accept-Language`
126- **Use `<ClientOnly>`/`<NoHydration>`** for inherently dynamic UI
127- **Use Selective SSR** when server HTML cannot be stable
128​
129See also: [Execution Model](./execution-model.md), [Code Execution Patterns](./code-execution-patterns.md), [Selective SSR](./selective-ssr.md), [Server Functions](./server-functions.md)