Open History to see the last commit
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/react-start'
20import {
21 getRequestHeader,
22 getCookie,
23 setCookie,
24} from '@tanstack/react-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' // deterministic until client sends tz
34β
35 // Persist locale for subsequent requests (optional)
36 setCookie('locale', locale, { path: '/', maxAge: 60 * 60 * 24 * 365 })
37β
38 return next({ context: { locale, timeZone } })
39})
40β
41export const startInstance = createStart(() => ({
42 requestMiddleware: [localeTzMiddleware],
43}))
44```
45β
46```tsx
47// src/routes/index.tsx (example)
48import * as React from 'react'
49import { createFileRoute } from '@tanstack/react-router'
50import { createServerFn } from '@tanstack/react-start'
51import { getCookie } from '@tanstack/react-start/server'
52β
53export const getServerNow = createServerFn().handler(async () => {
54 const locale = getCookie('locale') || 'en-US'
55 const timeZone = getCookie('tz') || 'UTC'
56 return new Intl.DateTimeFormat(locale, {
57 dateStyle: 'medium',
58 timeStyle: 'short',
59 timeZone,
60 }).format(new Date())
61})
62β
63export const Route = createFileRoute('/')({
64 loader: () => getServerNow(),
65 component: () => {
66 const serverNow = Route.useLoaderData() as string
67 return <time dateTime={serverNow}>{serverNow}</time>
68 },
69})
70```
71β
72### Strategy 2 β Let the client tell you its environment
73β
74- On first visit, set a cookie with the client time zone; SSR uses `UTC` until then
75- Do this without risking mismatches
76β
77```tsx
78import * as React from 'react'
79import { ClientOnly } from '@tanstack/react-router'
80β
81function SetTimeZoneCookie() {
82 React.useEffect(() => {
83 const tz = Intl.DateTimeFormat().resolvedOptions().timeZone
84 document.cookie = `tz=${tz}; path=/; max-age=31536000`
85 }, [])
86 return null
87}
88β
89export function AppBoot() {
90 return (
91 <ClientOnly fallback={null}>
92 <SetTimeZoneCookie />
93 </ClientOnly>
94 )
95}
96```
97β
98### Strategy 3 β Make it client-only
99β
100- Wrap unstable UI in `<ClientOnly>` to avoid SSR and mismatches
101β
102```tsx
103import { ClientOnly } from '@tanstack/react-router'
104;<ClientOnly fallback={<span>β</span>}>
105 <RelativeTime ts={someTs} />
106</ClientOnly>
107```
108β
109### Strategy 4 β Disable or limit SSR for the route
110β
111- Use Selective SSR to avoid rendering the component on the server
112β
113```tsx
114export const Route = createFileRoute('/unstable')({
115 ssr: 'data-only', // or false
116 component: () => <ExpensiveViz />,
117})
118```
119β
120### Strategy 5 β Last resort suppression
121β
122- For small, known-different nodes, you can use Reactβs `suppressHydrationWarning`
123β
124```tsx
125<time suppressHydrationWarning>{new Date().toLocaleString()}</time>
126```
127β
128### Checklist
129β
130- **Deterministic inputs**: locale, time zone, feature flags
131- **Prefer cookies** for client context; fallback to `Accept-Language`
132- **Use `<ClientOnly>`** for inherently dynamic UI
133- **Use Selective SSR** when server HTML cannot be stable
134- **Avoid blind suppression**; use `suppressHydrationWarning` sparingly
135β
136See also: [Execution Model](./execution-model.md), [Code Execution Patterns](./code-execution-patterns.md), [Selective SSR](./selective-ssr.md), [Server Functions](./server-functions.md)