Hydration mismatches in Nuxt.js occur when the HTML generated on the server does not match the initial DOM tree rendered by the client during hydration. This usually happens when code uses non-deterministic values—such as Date.now()—or browser-only globals like window or document directly in the setup or template.
To prevent these errors, you must ensure that the server and client produce identical output, or isolate the divergent logic to the client side entirely.
Using the <client-only> Component
The most straightforward way to handle logic that only exists in the browser is the <client-only> wrapper. This component tells Nuxt to skip rendering its children during the server-side phase and only render them once the client has mounted.
<client-only>
<!-- This only renders on the client -->
<div>Current time: {{ new Date().toLocaleTimeString() }}</div>
</client-only>
Conditional Rendering with process.client
If you need more control than a wrapper allows, use the process.client boolean within your script logic. This allows you to initialize variables or trigger side effects only when the code is running in the browser.
const setup = () => {
const clientTime = ref(null);
onMounted(() => {
// Only runs after hydration is complete
clientTime.value = new Date().toLocaleTimeString();
});
}
Synchronizing Data with useAsyncData
When the mismatch stems from fetched data, ensure you are using useFetch or useAsyncData. These composables automatically serialize the result into a JSON payload embedded in the HTML, which the client uses to hydrate its state instead of re-fetching or generating data. If you want to avoid the server-side fetch entirely, use the immediate: false option.
Summary of Strategies
- Avoid direct global access: Never call
window or localStorage in the top-level setup without a guard.
- Use onMounted: Move dynamic UI-state logic into
onMounted to ensure it executes after the initial hydration is stable.
- Placeholders: Render a static placeholder on the server that is replaced by dynamic content on the client loads.