SSR and hydration in Vue
How Vue renders an app to HTML on the server with createSSRApp and renderToString, how hydration adopts that HTML, and how to avoid hydration mismatches.
SSR and hydration in Vue
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Vue's server renderer runs your components in Node and turns them into an HTML string or stream: `createSSRApp` builds the app and `renderToString` (or a streaming variant from `vue/server-renderer`) produces the markup.
- Hydration is the browser running the same app with `createSSRApp(...).mount()` against HTML that already exists, so Vue attaches listeners and reactive state to those nodes instead of building new ones.
- On the server, `setup()` runs but `onMounted` and `onUpdated` never do, and reactivity is switched off, so timers, `window`, `document`, and other browser-only work belong in `onMounted`.
- Module-level state is shared by every request on a long-running server, so SSR apps create a fresh app, router, and store per request to avoid leaking one user's data into another's page.
- A hydration mismatch means the client rendered something different from the server's HTML; the usual causes are invalid HTML nesting, random values, dates and time zones, and client-only state, and Vue 3.5 adds `useId` and `data-allow-mismatch` to deal with the unavoidable ones.
- Vue 3.5's lazy hydration lets an async component stay as inert server HTML until it is idle, visible, matched by a media query, or interacted with, which cuts the JavaScript work on first load.
Why Vue needs a second way to render
Everything in this roadmap so far has run in the browser. createApp(App).mount('#app') takes an empty <div>, runs your components, and builds the DOM from nothing. The HTML file the server sends is a shell, and the page only gets content after the JavaScript bundle downloads and runs.
When that delay matters (a public page that search engines index, a product page on a slow phone, a link preview that never runs JavaScript), you want the server to send finished HTML. Whether to do that, and the trade-offs between client rendering, server rendering, and static generation, are covered in server-side rendering and static site generation on the frontend roadmap. This lesson assumes you have decided to server-render and looks at the machinery Vue gives you for it.
Rendering a Vue app to a string
Vue ships its server renderer as vue/server-renderer. The smallest working example is a few lines of Node:
import { createSSRApp } from 'vue'
import { renderToString } from 'vue/server-renderer'
const app = createSSRApp({
data: () => ({ count: 1 }),
template: `<button @click="count++">{{ count }}</button>`,
})
const html = await renderToString(app)
// '<button>1</button>'
renderToString runs each component’s setup and render logic and resolves to the HTML. When an SFC is compiled for the server, its template is compiled into string concatenation rather than virtual DOM render functions, because the server never patches anything. It only needs the markup once.
A real app shares the same component tree between server and browser. The usual structure is a factory both sides import:
// app.js — imported by the server AND the browser
import { createSSRApp } from 'vue'
import App from './App.vue'
export function createApp() {
const app = createSSRApp(App)
return { app }
}
// server.js
import express from 'express'
import { renderToString } from 'vue/server-renderer'
import { createApp } from './app.js'
const server = express()
server.use(async (req, res) => {
const { app } = createApp() // a fresh app for every request
const html = await renderToString(app)
res.send(`<!doctype html>
<html>
<body>
<div id="app">${html}</div>
<script type="module" src="/client.js"></script>
</body>
</html>`)
})
server.listen(3000)
renderToString waits for the whole page before sending a byte. For large pages Vue also offers streaming variants in the same package: renderToNodeStream and pipeToNodeWritable for Node streams, and renderToWebStream and pipeToWebWritable for the Web Streams API used by edge runtimes. With streaming, the browser can start parsing the top of the page while the server is still rendering the rest.
Hydration: adopting HTML instead of building it
The HTML from renderToString has no behaviour. That <button> is just a tag, and clicking it does nothing, because only running JavaScript can attach a listener. The browser side has to finish the job:
// client.js
import { createApp } from './app.js'
const { app } = createApp()
app.mount('#app')
Because the factory uses createSSRApp, mount() runs in hydration mode. Vue renders the component tree in memory, walks the DOM that is already inside #app, and checks that the two agree node by node. Where they match, it keeps the existing node and attaches event listeners and reactive bindings to it. A plain createApp would ignore the server HTML and rebuild it, which wastes the work and makes the page flicker.
Think of a furnished show home. The server delivers the furniture already arranged, so visitors can look around immediately. Hydration is the electrician walking through afterwards, wiring each lamp that is already standing where the floor plan says it should be. Until the electrician reaches a room, the switches in it do nothing. That gap between “page visible” and “page interactive” is the price of SSR, and it is why hydration speed matters.
What runs where
The same component code now runs twice: once on the server, once in the browser. Vue’s SSR rules follow from that.
- Lifecycle.
setup()and the top level of<script setup>run on both sides.onMounted,onUpdated, and the unmount hooks run only in the browser, because the server never mounts or updates anything (see lifecycle hooks). - No reactivity on the server. Each request renders once, so Vue switches reactivity off during SSR for speed. Watchers don’t fire there.
- Browser globals.
window,document, andlocalStoragedon’t exist in Node. Touching them at the top level of setup crashes the server render. - Side effects that need cleanup. A
setIntervalstarted in setup runs on the server for every request and is never cleared, because unmount hooks never run there.
The fix for the last two is the same: move browser-only work into onMounted.
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
const width = ref(0)
let timer
onMounted(() => {
width.value = window.innerWidth // safe: browser only
timer = setInterval(() => { /* poll something */ }, 5000)
})
onUnmounted(() => clearInterval(timer))
</script>
Async data needs care too. A component with an async setup() is awaited by the server renderer before the HTML is sent, which is the same mechanism async components and Suspense use in the browser. Whatever the server fetched then has to reach the client, or the client will fetch it again and may render something different. Hand-rolled setups serialize that state into the page. Frameworks do it for you.
There is also a server-only trap with no browser equivalent: cross-request state pollution. A Node server loads your modules once and serves thousands of requests from them, so a reactive() object declared at module scope is shared by every visitor. Write one user’s cart into it and the next request may render it. This is why the server example calls createApp() inside the request handler, and why Pinia and Vue Router are designed to be instantiated per request.
Hydration mismatches
A hydration mismatch means the browser’s first render produced different output from the HTML the server sent. Vue recovers by patching the DOM to match the client, discarding nodes it can’t reuse. The page usually still works, but you pay for the extra DOM work, can get a visible flash, and in bad cases end up with listeners attached to the wrong elements. The common causes:
- Invalid HTML nesting.
<p><div>hi</div></p>is not valid HTML, so the browser’s parser rewrites it into<p></p><div>hi</div><p></p>before Vue ever sees it. The server’s string and the browser’s DOM no longer line up. - Values that differ per run.
Math.random(),Date.now(), or anything time-based gives the server and client different answers. - Time zones and locales.
toLocaleString()on the server uses the server’s zone, not the visitor’s. - Client-only state. Reading
localStorageor checkingwindowduring render means the server and client take different branches.
Since Vue 3.4, development builds name the element and show both the server and client values, which turns most of these into a quick fix. Vue 3.5 added two tools for the cases you can’t remove:
<script setup>
import { useId } from 'vue'
// Stable across server and client, unlike a random id
const id = useId()
</script>
<template>
<label :for="id">Email</label>
<input :id="id" type="email" />
<!-- The difference here is expected; don't warn about it -->
<time data-allow-mismatch="text">{{ new Date().toLocaleTimeString() }}</time>
</template>
data-allow-mismatch accepts text, children, class, style, or attribute to scope what may differ. Use it for genuinely unavoidable cases. For everything else, render client-only content after mount.
Lazy hydration
Hydrating everything up front means running every component on the page before any of it responds, including a footer the visitor may never scroll to. Vue 3.5 lets an async component decide when to hydrate:
import { defineAsyncComponent, hydrateOnVisible, hydrateOnInteraction } from 'vue'
const Comments = defineAsyncComponent({
loader: () => import('./Comments.vue'),
hydrate: hydrateOnVisible({ rootMargin: '100px' }),
})
const ShareMenu = defineAsyncComponent({
loader: () => import('./ShareMenu.vue'),
hydrate: hydrateOnInteraction('click'),
})
The other built-in strategies are hydrateOnIdle and hydrateOnMediaQuery. Until the trigger fires, the server HTML stays on screen as plain markup, and the component’s code is not even downloaded. Lazy hydration only affects the first page load; after that, client-side navigation renders normally.
What the video covers
Alexander Lichter, a Nuxt core team member, spends this Vuejs Amsterdam 2024 talk entirely on hydration: what it is, a tour of mismatch causes (invalid nesting, random values and dates, auth state that differs between server and client), how the improved Vue 3.4 warnings point at the culprit, and the “what to hydrate and when” question behind partial and lazy hydration. Some examples use Nuxt’s useState to move server state to the client, which the next lessons cover. The talk predates Vue 3.5, so it presents useId and lazy hydration as upcoming; both shipped in 3.5 as shown above. It doesn’t walk through the raw createSSRApp/renderToString setup. The second “go deeper” link builds exactly that with Vite and Express, and the first shows lazy hydration in action.
Where this fits
Everything above is what a framework has to automate: two builds, a per-request app, state transfer, asset links, and routing on both sides. Nuxt fundamentals covers the framework that does it for Vue, and React’s equivalent story is told in the React roadmap.
Check yourself
Why does a Vue SSR app call `createSSRApp` in the browser instead of `createApp`?
`createApp` assumes it owns an empty container and renders everything from scratch, throwing away the server's HTML. `createSSRApp` mounts in hydration mode: it walks the existing DOM, matches it against what the components would render, and attaches event listeners and reactive bindings to the nodes that are already there.
A component starts a `setInterval` at the top level of `<script setup>` and clears it in `onUnmounted`. Why is that a problem under SSR, and what is the fix?
`setup()` runs on the server for every request, but unmount hooks never run there, so each request starts a timer that is never cleared and the server slowly leaks timers. Moving the `setInterval` into `onMounted` means it only ever starts in the browser, where `onUnmounted` will clean it up.
A page renders `{{ new Date().toLocaleTimeString() }}` and logs a hydration mismatch warning. What happened, and what are two ways to handle it?
The server rendered the time when it handled the request, and the client rendered it again a moment later, possibly in a different time zone, so the text differs. You can render the time only on the client (for example with a ref set in `onMounted`, shown with `v-if`), or, in Vue 3.5+, mark the element with `data-allow-mismatch="text"` to say the difference is expected and silence the warning.
What problem does a per-request app factory solve on the server?
A Node server loads your modules once and reuses them for every request, so a reactive object declared at module scope is shared by all users. If one request writes user-specific data into it, the next request can render that data. Creating a new app instance, router, and store inside a function called per request gives each request its own state.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.