How to Fix Hydration Error in Astro: Simple Steps
Hydration errors in
Astro happen when the HTML rendered on the server does not match the client-side JavaScript output. To fix this, ensure your components use proper client:* hydration directives and avoid rendering dynamic content differently on server and client.Why This Happens
Hydration errors occur because Astro renders HTML on the server, then JavaScript on the client tries to 'hydrate' or attach behavior to that HTML. If the server and client output differ, the browser shows a hydration mismatch error.
This often happens when dynamic data or browser-only APIs are used directly in the component without guarding for server rendering.
astro
--- src/components/Counter.astro --- <script> let count = 0; // This runs on server and client, causing mismatch count = Math.floor(Math.random() * 10); </script> <button on:click={() => count++}>Count: {count}</button>
Output
Hydration error: Server rendered HTML does not match client HTML.
The Fix
To fix hydration errors, use Astro's hydration directives like client:load or client:idle to run JavaScript only on the client. Also, avoid using browser-only or dynamic code during server rendering.
In the example, move dynamic code inside a client-only script block.
astro
--- src/components/Counter.astro --- <script client:load> let count = Math.floor(Math.random() * 10); </script> <button on:click={() => count++}>Count: {count}</button>
Output
<button>Count: 7</button> <!-- Count is consistent after hydration, no error -->
Prevention
To avoid hydration errors in the future:
- Use
client:*directives to control when components hydrate. - Keep server-rendered HTML deterministic and avoid random or browser-only code during server render.
- Test components with hydration enabled and check browser console for warnings.
- Use Astro's linting tools or plugins that warn about hydration mismatches.
Related Errors
Other errors similar to hydration issues include:
- Missing hydration directive: Component does not hydrate because no
client:*directive is set. - Event handler not working: Happens if hydration fails and JavaScript is not attached.
- Browser API errors: Using
windowordocumentin server code causes errors.
Key Takeaways
Hydration errors happen when server and client HTML do not match in Astro.
Use
client:* hydration directives to run code only on the client side.Avoid dynamic or browser-only code during server rendering to keep output consistent.
Test your components in the browser and watch for hydration warnings in the console.
Use Astro's linting tools to catch potential hydration issues early.