Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 32 ยท Rendering modes

Hydration and SSR pitfalls

Learn why Nuxt hydration mismatches happen (Date, Math.random, window, bad HTML) and fix them with useState, onMounted, ClientOnly, useId and debugging steps.

Server rendering gives you fast, readable pages, but it adds one rule that catches nearly every beginner: the first render in the browser must produce exactly the same HTML the server already sent. When it does not, Vue prints a hydration mismatch warning, and the page may flicker, show wrong content or behave strangely.

This lesson explains why mismatches happen, shows the five most common causes, and gives you the standard fixes and a debugging routine. Nuxt code is read-only here because the framework cannot run on this site. Two plain JavaScript stand-ins run live: one renders components "on the server" and "in the browser" and reports mismatches, and one applies the fixes. They model Vue's comparison, which is more detailed in reality. If hydration itself is new to you, read Rendering modes first.

Why a mismatch happens

Server render Runs once, in Node, at one moment.
Browser render Runs later, in another place.
Compare Vue expects identical HTML.
Different? Warning, flicker, wrong DOM.
1 / 2

What actually goes wrong

During hydration Vue does not rebuild the page. It runs your components in the browser to learn what the DOM should look like, then walks the existing server HTML and assumes it matches. It attaches listeners and state to those nodes. If a text node, an attribute or a child element differs, Vue's assumption is wrong. In development you get a warning in the console naming the kind of mismatch (text content, node type, children, or attribute). In production, Vue tries to patch the difference quietly, which can leave visible flicker or, worse, stale or incorrect content.

The key insight is that your component code runs twice in two different worlds:

Server Browser
Time of the run when the request arrives later, when JavaScript has loaded
window, document, localStorage do not exist exist
Time zone and language the server's the visitor's
Randomness one set of values a different set

Anything that reads one of those rows while rendering can produce different HTML in the two worlds.

A mismatch detector

The first stand-in builds four small components as functions that return HTML from an "environment". It renders each one with a server environment and a browser environment (different time, time zone, random values and a window that only exists in the browser) and compares the strings, which is the heart of what Vue does.

JS Detect a hydration mismatch

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Three components report MISMATCH: the clock shows 1/1/2026 on the server and 1/2/2026 in the browser, the lucky number is 12 versus 87, and the layout says Desktop menu versus Mobile menu. Only the stable greeting is OK. (The stand-in uses fixed values instead of the real Date and Math.random, so the output is always the same. In a real app the numbers change on every request.)

The common causes

1. Dates, times and locales. new Date() differs between server and browser by at least the network delay, and formatting with toLocaleString() uses the machine's time zone and language, which differ. A page rendered at 23:59:58 on the server and hydrated at 00:00:03 shows two different days.

2. Random values. Math.random() and crypto.randomUUID() give different results every call. This includes random ids used for for/id pairs on form fields, random "featured" items and shuffled lists.

3. Browser-only APIs. Reading window.innerWidth, localStorage, navigator.language or document.cookie while rendering gives nothing (or an error) on the server and a real value in the browser. Using them at the top level of <script setup> can even crash the server render with window is not defined.

4. Invalid HTML. Browsers repair some markup when they parse it. A <div> inside a <p>, a <p> inside a <p>, a <a> inside an <a>, or a <tr> directly in a <table> without a body may be restructured by the browser before Vue sees it, so the real DOM no longer matches what Vue expects:

VUE
<!-- read-only: this can cause a mismatch -->
<p>
  Intro text
  <div class="note">A block element inside a paragraph</div>
</p>

The HTML parser closes the <p> early when it meets the <div>. Fix it by using valid nesting: swap the <p> for a <div>, or move the block out.

5. Outside interference. Browser extensions that inject elements into the page (translators, password managers, ad blockers), CDNs or proxies that rewrite HTML (some "minify" or inject scripts) and cached HTML that is out of date with your code can all change the DOM before hydration. If a mismatch only appears for some visitors or only in production, suspect these.

A related issue is code that behaves differently by environment:

TypeScript
// read-only: a mismatch factory
const isMobile = import.meta.client && window.innerWidth < 600;

On the server isMobile is false; on the client it may be true, so the first client render differs from the server HTML.

The standard fixes

You have a small toolbox, and each tool matches a cause.

Make the value come from one place: useState. When a value must be random or time-based but identical on both sides, create it once on the server and let the browser reuse it. useState stores its value in the server payload:

VUE
<script setup lang="ts">
const lucky = useState('lucky', () => Math.floor(Math.random() * 100));
</script>

<template>
  <p>Lucky number: {{ lucky }}</p>
</template>

The initializer runs on the server; the browser receives the finished value in the payload and does not run it again. The next lesson on state, State with useState and Pinia, goes deeper. For stable unique ids, Vue 3.5 and newer give you useId(), which produces the same id on the server and in the browser:

VUE
<script setup lang="ts">
const id = useId();
</script>

<template>
  <label :for="id">Email</label>
  <input :id="id" type="email" />
</template>

Render the browser-only part after mount: onMounted. Code in onMounted runs only in the browser, after hydration. Render something stable first, then update it:

VUE
<script setup lang="ts">
const today = ref('...');
onMounted(() => {
  today.value = new Date().toLocaleDateString();
});
</script>

<template>
  <p>Today is {{ today }}</p>
</template>

Server and browser both start with ..., so they match; the real date appears right after hydration. The same pattern works for localStorage values and screen-size checks.

Skip the server for a whole piece: <ClientOnly>. For things that make no sense on the server, such as a map widget, a chart library that needs the DOM or a menu that depends on the screen width, wrap them and give a fallback:

VUE
<template>
  <ClientOnly>
    <HeavyChart :data="data" />
    <template #fallback>
      <p>Loading chart...</p>
    </template>
  </ClientOnly>
</template>

The server renders the fallback, the browser's first render also renders the fallback, and the real content replaces it after mount. A component file named with a .client.vue suffix does the same for the whole component. Give the fallback the same size as the final content, or the page will jump (a layout shift).

Guard environment checks. To run code only on one side, use import.meta.client and import.meta.server, which Nuxt replaces at build time. The older process.client and process.server still appear in many tutorials but are deprecated in favor of these. Keep such checks outside rendering, in onMounted or event handlers, or the guarded value itself will cause a mismatch.

The second stand-in models three of these fixes. first is the render that must match the server HTML; mounted is what runs afterwards in the browser only.

JS Fixes: shared state, onMounted and ClientOnly

Press Run (or Ctrl + Enter) to see the console output here.

No output.

All three print match. The shared-state component hydrates as Lucky number: 12, the value the server created, even though the browser's own random value would have been 87. The onMounted component hydrates as the placeholder Today is ... and then becomes Today is 2026-01-02. The client-only component hydrates as Loading menu... and becomes Mobile menu after mount. The trade-off of the last two is a brief moment where the visitor sees the placeholder, so use them for details and not for your main content.

Debugging a mismatch

When the console reports a mismatch, work through this routine:

  1. Read the warning. In development Vue names the kind (text, node, children, attribute) and points at the component. The first one is the real one; later ones are often consequences.
  2. Compare the raw HTML to the DOM. Use "View page source" (what the server sent) and the browser inspector (what the DOM is now). Find the first difference.
  3. Ask the five questions. Is there a date, a random value, a browser API, invalid nesting, or something outside the app (extension, CDN) near that spot?
  4. Isolate it. Wrap the suspect component in <ClientOnly>. If the warning disappears, the cause is inside it. Remove half of its template and repeat until you find the line.
  5. Test without extensions. Open a private window with extensions disabled; if the warning vanishes, an extension is touching your HTML.
  6. Fix at the source with the tools above. If a mismatch is intentional and harmless (for example a timestamp that you accept will differ), Vue 3.5 lets you mark the element with a data-allow-mismatch attribute to silence the warning for it. Use it rarely, and only for text or attributes you really do not care about.

Also remember that a mismatch warning only appears in development builds. Test with a production build (nuxt build and nuxt preview) before you ship, since caching and CDNs are only present there. The rules for caching are in Rendering modes, and wider performance topics, including lazy hydration, are in Performance and Core Web Vitals.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which code in a component's render path is most likely to cause a hydration mismatch?

    Random values differ between the server render and the browser's first render, so the HTML the server sent no longer matches.
  2. 2. Why does reading localStorage at the top of script setup cause trouble?

    Browser-only APIs are missing on the server. Read them in onMounted or inside a client-only component instead.
  3. 3. What is the effect of wrapping a component in <ClientOnly> with a #fallback slot?

    Both sides render the same fallback first, so they match, and the component itself is mounted in the browser afterwards.
  4. 4. How can a <div> placed inside a <p> cause a mismatch?

    Invalid nesting is repaired by the browser when it parses the HTML, so the DOM no longer matches the structure Vue expects.
  5. 5. Which helper gives a unique id that is identical on the server and in the browser?

    useId() generates ids that are stable across server and client renders, so form label and input pairs hydrate correctly.

Summary

  • Hydration expects the browser's first render to produce the same HTML the server sent; otherwise you get a mismatch warning and possible glitches.
  • Typical causes: dates and locales, random values, browser-only APIs, invalid HTML nesting and outside interference.
  • Use useState for values created once on the server, useId() for stable ids, onMounted for browser-only updates and <ClientOnly> for browser-only components.
  • Use import.meta.client and import.meta.server instead of the deprecated process.client checks, and keep them out of the render path.
  • Debug by comparing page source with the DOM, isolating with <ClientOnly>, and testing with extensions off and in a production build.

Next, extend your app with reusable behavior in Plugins and Nuxt modules.