Fixing Hydration Mismatch Errors in Astro Islands

Astro islands render twice: once at build time, producing static HTML, and again in the browser when the island hydrates. If the two renders disagree, React logs "Hydration failed because the server rendered HTML didn't match the client" (or "Text content does not match"), Preact and Vue log their own versions, and React 18+ throws away the server HTML for that island and renders it from scratch. The reader sees the content flash, the layout may shift, and the main thread does the rendering work twice. On a static site the problem is sharper than on a server-rendered one, because the "server" render happened at build time, possibly days earlier, on a machine with a different clock, time zone and locale.

This guide fixes the hydration mismatches on an Astro 5 marketing and docs site with 14 React and Preact islands, where the console showed mismatch errors on 9 of them. It shows how to find the differing output, the five causes found, and a test that fails on any new mismatch. It belongs to JavaScript Hydration & Partial Rendering.

Step 1: Find Which Islands Mismatch

React 19 reports mismatches with a diff of the server and client output, which makes most cases quick to read. To find them across the site, a Playwright script visits a sample of pages and collects console errors that mention hydration:

const errors = [];
page.on('console', (m) => { if (m.type() === 'error' && /hydrat/i.test(m.text())) errors.push(`${page.url()}: ${m.text().slice(0, 200)}`); });
for (const url of samplePages) { await page.goto(url, { waitUntil: 'networkidle' }); }

Run in a browser context with a different time zone and locale from the build machine — timezoneId: 'Pacific/Auckland', locale: 'de-DE' — because many mismatches only appear when they differ, which is the normal case for real readers.

Number of islands with hydration mismatches by cause Horizontal bars. Dates and relative times formatted differently at build and view time 3 islands. Random IDs or values generated during render 2. Reading window or localStorage during render 2. Invalid HTML nesting repaired by the browser 1. Data that changed between build and view 1. Mismatches by cause Dates and relative times 3 Random values in render 2 Browser APIs in render 2 Invalid HTML nesting 1 Data changed since build 1
9 of 14 islands mismatched; found with a Playwright run in a different time zone and locale from CI.

Cause 1: Dates Rendered in Two Time Zones

A changelog island formatted release dates with toLocaleDateString() and showed "3 days ago" with a relative-time helper. At build time in CI (UTC, en-US) it rendered "Sep 29, 2026 · 3 days ago"; in a German reader's browser two days later it rendered "29.9.2026 · vor 5 Tagen". Two fixes:

  • Absolute dates use an explicit locale and time zone on both sides: new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeZone: 'UTC' }). The site's content is English, so a fixed locale is correct.
  • Relative times render as the absolute date during hydration and switch to relative text in an effect after hydration:
function Released({ iso }: { iso: string }) {
  const [rel, setRel] = useState<string | null>(null);
  useEffect(() => setRel(relativeTime(iso)), [iso]);
  return <time dateTime={iso}>{rel ?? fmt.format(new Date(iso))}</time>;
}

The server and first client render now agree; the relative text appears a moment later without a mismatch.

Cause 2: Random Values During Render

Two islands generated IDs with Math.random() for aria-labelledby pairs. Each render produced different IDs. React's useId() produces IDs that match between server and client; Preact has useId from preact/hooks with the same guarantee. Replacing the random IDs fixed both.

Cause 3: Browser APIs Read During Render

A pricing table read localStorage.getItem('currency') during render to choose euros or dollars, guarded by typeof window !== 'undefined'. At build time the guard skipped it and rendered dollars; in the browser it rendered euros for European readers — a mismatch on every price. A theme-aware illustration read matchMedia('(prefers-color-scheme: dark)') the same way. Both moved the browser read into an effect, rendering the default first:

const [currency, setCurrency] = useState<'USD' | 'EUR'>('USD');
useEffect(() => { const c = localStorage.getItem('currency'); if (c === 'EUR') setCurrency(c); }, []);

For the price table, the visible switch from dollars to euros after hydration was itself a small layout shift; reserving the width of the price column with min-width in ch units kept it stable.

Rendering a browser-dependent value during render compared with after hydration Two panels. Reading localStorage during render produced dollars at build time and euros in the browser, a mismatch on every price, so React discarded the server HTML. Rendering the default during render and reading localStorage in an effect produced dollars in both renders, then switched to euros after hydration with no mismatch. Rendering browser-dependent values safely Read during render build: USD browser: EUR mismatch island re-rendered flash + wasted work Read in an effect build: USD first client render: USD effect: switch to EUR no mismatch
The rule: render the same thing in both places, then update in an effect.

Cause 4: Invalid HTML Nesting

A card component rendered <p>{children}</p> and was used with a child that contained a <div>. The browser's parser closed the <p> before the <div>, so the DOM had a different structure from what React expected. React reported "In HTML, <div> cannot be a descendant of <p>". Changing the wrapper to a <div> fixed it. The site's HTML validation step (Validating HTML Output in CI) now flags invalid nesting in island markup, so these appear as build failures rather than runtime errors.

Cause 5: Data That Changed After the Build

A "GitHub stars" island received the star count as a prop at build time and fetched the live count on hydration, rendering it immediately. The values differed by the stars gained since the build. Rendering the build-time value first and updating after a fetch in an effect removed the mismatch. In general, any island that refreshes data must render the build-time data on its first client render.

Why Not client:only?

Each of these could have been "fixed" by switching the island to client:only="react", which skips the build-time render. That would have hidden three islands' content from the static HTML — including the pricing table, which was the LCP element on the pricing page — and turned each into an empty box until its JavaScript ran. The site uses client:only for exactly one island, an interactive map that cannot render without the browser, with its space reserved by an aspect-ratio container. Deferring Hydration with client:visible in Astro covers choosing directives.

Decision tree for fixing an island hydration mismatch The root asks what differs between the server and client render. If it is a date or time, format with explicit locale and time zone, and show relative times after hydration. If it is a random ID, use useId. If it comes from window, localStorage or matchMedia, render the default and read it in an effect. If the HTML structure differs, fix the invalid nesting. If the data is fresher on the client, render build-time data first and update in an effect. Fixing a mismatch What differs between the two renders? Date or time text Explicit locale + TZ relative time in effect Random IDs useId() stable across renders Browser API value Default then effect reserve its space HTML structure Fix nesting validate in CI
client:only is the fallback only for components that cannot render without a browser.

Step 2: Fail the Build on New Mismatches

The Playwright check runs on preview deploys with a non-UTC time zone and non-English locale, across one page per island, and fails on any console error matching /hydrat/i. It takes about 25 seconds and has caught two new mismatches since, both dates.

Measured Impact

MeasureBeforeAfterTool
Islands with mismatches9 of 140Playwright console check
Islands using client:only11Code
Pricing page LCP, mobile lab2.6 s1.9 sLighthouse, median of 5
Total Blocking Time, pricing page340 ms150 msLighthouse
CLS, pricing page0.080.01web-vitals RUM

The pricing page improved most: its table had been discarded and re-rendered on every visit, which delayed LCP (the table) and shifted the layout as the re-render settled.

Pitfalls & Rollback

  • Testing only in the build machine's time zone and locale. Run checks with different values.
  • Guarding browser APIs with typeof window during render. It creates mismatches; use effects.
  • Reaching for client:only. It removes content from the HTML and costs LCP.
  • Ignoring warnings in development. They become re-renders in production.
  • Rollback: each fix is local to one component; the console check makes any reintroduced mismatch visible on the preview.

Conclusion

Hydration mismatches in Astro islands come from rendering something different at build time than in the reader's browser: dates in another time zone, random IDs, browser state read during render, HTML the parser repairs, and data that changed since the build. Rendering the same output in both places and updating in effects fixed all nine affected islands without resorting to client:only, and cut the pricing page's lab LCP from 2.6 to 1.9 seconds.

FAQ

What is a hydration mismatch in an Astro island?

The island's component renders HTML on the server at build time, then renders again in the browser during hydration. If the two renders produce different output, the framework warns or errors, and depending on the framework it may discard the server HTML and re-render from scratch, causing a visible flash, layout shift and wasted work.

Why do dates cause hydration mismatches on static sites?

The server render happens at build time, possibly days before the page is viewed, in the build machine's time zone and locale. The browser renders at view time in the reader's time zone and locale. Relative times such as 3 days ago, or dates formatted with the default locale, differ between the two. Format dates with an explicit time zone and locale, or render relative times only after hydration.

Is client:only a good fix for mismatches?

It removes the error by skipping server rendering, but the island then renders nothing until its JavaScript loads, which costs LCP for visible content, adds layout shift unless space is reserved, and hides the content from crawlers and readers without JavaScript. Use it only for components that genuinely cannot render without the browser.

Can invalid HTML cause hydration errors?

Yes. Browsers repair invalid nesting such as a div inside a p, or a nested anchor, when parsing the server HTML, so the DOM no longer matches what the component expects during hydration. React reports these as mismatches. Validating the built HTML catches them before they reach the browser.

Filed underFixesAstro