Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 87 ยท Performance, Security and Ecosystem

Server-Side Rendering and Hydration

Understand Vue server-side rendering: what renderToString produces, how hydration makes HTML interactive, why mismatches happen, and when SSR or SSG pays off.

A normal Vue app is a single-page application (SPA). The server sends an almost empty HTML file and a JavaScript bundle. The browser downloads and runs the bundle, and only then does Vue build the page. Until that finishes, the visitor sees a blank screen, and crawlers or link preview bots that do not run JavaScript see nothing useful.

Server-side rendering (SSR) changes who builds the first version of the page. The server runs your Vue components, turns them into an HTML string, and sends real content right away. The browser can show it before any JavaScript arrives. Then Vue loads in the browser and hydrates the page: it attaches event listeners and reactivity to the HTML that is already there, instead of throwing it away and starting over. This lesson explains both steps, the traps they create, and how to decide whether you need them. It is explanatory and mostly read-only: the site sandbox runs in the browser, so there is no server to render on.

The idea in one picture

sequenceDiagram
  participant B as Browser
  participant S as Server
  B->>S: request /products
  S->>S: run Vue, render components to HTML
  S-->>B: full HTML with content
  Note over B: the page is visible but not interactive
  B->>S: request the JavaScript bundle
  S-->>B: bundle
  Note over B: Vue hydrates the existing HTML
  Note over B: the page is interactive

SSR shows content first and makes it interactive second. Between those two moments, buttons are visible but do nothing.

Compare the three common strategies:

Strategy HTML is built Strength Cost
Client-side rendering (SPA) In the browser Simple hosting, rich app feel Blank screen at first, weaker SEO
Server-side rendering (SSR) On the server, per request Fast first paint, fresh data, good SEO Needs a running Node server, more complexity
Static site generation (SSG) At build time, once Fastest, cheap static hosting Content only changes on rebuild

What the server produces

On the server, Vue exposes renderToString, imported from vue/server-renderer. It takes an app and returns a promise for an HTML string. The code below is read-only, since it needs Node:

JavaScript
// server.js (read-only: runs on Node, not in the browser)
import { createSSRApp, h, ref } from "vue";
import { renderToString } from "vue/server-renderer";

const Greeting = {
  props: ["name"],
  setup(props) {
    const count = ref(0);
    return () =>
      h("div", { class: "card" }, [
        h("h2", "Hello, " + props.name),
        h("button", { onClick: () => count.value++ }, "Clicked " + count.value + " times")
      ]);
  }
};

const html = await renderToString(createSSRApp(Greeting, { name: "Ada" }));
console.log(html);
// <div class="card"><h2>Hello, Ada</h2><button>Clicked 0 times</button></div>

Look at the output. It is plain HTML text with the current state baked in. The onClick handler is not in it: HTML strings cannot hold JavaScript functions. That is the whole reason hydration exists. Also note that text is escaped: if name were <b>Bo</b>, the server would output &lt;b&gt;Bo&lt;/b&gt;, the same safe default you learned in Security in Vue.

Notice also createSSRApp instead of createApp. It creates an app that knows it will hydrate existing markup. In a real project the server entry creates a new app per request, and the browser entry creates one with createSSRApp and mounts it on the server-rendered container:

JavaScript
// client.js (read-only: the browser entry of an SSR project)
import { createSSRApp } from "vue";
import App from "./App.vue";

createSSRApp(App).mount("#app"); // hydrates, does not re-create the DOM

In a real project you will rarely write this plumbing by hand: Nuxt (see Nuxt Overview) and Vite's SSR templates set it up for you.

Hydration

When mount runs on a container that already has server-rendered HTML, Vue walks the existing DOM nodes alongside the virtual DOM that the components produce. It reuses each element, attaches event listeners, and sets up reactive updates. No elements are created for content that matches, which is faster than rendering from scratch.

The demo below fakes the server step. A string of HTML, exactly as the server would have sent it, is placed in the page. Click its button before hydrating: nothing happens, because the markup is static. Press "Hydrate", and the same button starts counting. Reset puts the static HTML back.

Before and after hydration

This gap between "visible" and "interactive" is real in production too. A slow device on a slow network may show the page for seconds before the buttons work. Vue 3.5 added lazy hydration strategies for async components (for example hydrating only when the component becomes visible or when the browser is idle), which lets you delay hydration for parts that are not needed straight away.

Hydration mismatches

For hydration to work, the HTML from the server and the first render in the browser must be identical. If they differ, Vue has to guess, and you get a hydration mismatch. A development build reports it in the console, and the page may contain stale or wrong content, or in bad cases broken interactivity.

Common causes:

  • Browser-only values during render: window.innerWidth, matchMedia, localStorage, the user's time zone.
  • Values that change between runs: Math.random(), Date.now(), ids generated with a counter.
  • Invalid HTML nesting: a <div> inside a <p> is repaired by the browser's parser, so the DOM no longer matches what Vue expects.
  • Different data on server and client (for example the server fetched data, the client did not receive it).

The demo has a server page that says "Theme: light". The naive component reads a browser-only value (here a constant that pretends to be matchMedia) right in its render. The safe component starts with the value the server used and changes it in onMounted, which only runs in the browser, after hydration. Run each, and read the log.

A mismatch and its fix

With the naive component, Vue notices that the server text and the client text differ. It fixes the text so the page shows "dark", and the browser console notes that hydration completed with mismatches (a development build lists the exact difference). With the safe component, the first render matches the server, so hydration is clean, and the theme switches right after mount. The trade-off is a visible flicker from light to dark. For a real theme switch you would avoid even that by setting a class on <html> with a tiny inline script before the page paints.

The usual rule: render the same thing on the server and in the first client render, and move anything browser-specific into onMounted. Frameworks give you helpers for the rest, such as a client-only wrapper component for widgets that cannot run on the server at all.

Writing code that runs in two places

The server is a shared, long-running process that serves many users. Code that was fine in a browser, where each tab is isolated, becomes dangerous there:

  • No shared state at module level. A const state = reactive({ user: null }) at the top of a file is created once on the server and then shared by every request: one user's data could leak into another user's page. Create the app, router and stores inside a function that runs per request, and use provide/inject or the framework's per-request state instead of global singletons.
  • Few lifecycle hooks run on the server. Only setup() (and the Options API's beforeCreate and created) run. onMounted, onUpdated and friends run only in the browser. Do not start timers or listeners in setup(), because on the server they would never be cleaned up.
  • Guard browser APIs. window and document do not exist in Node. Use them inside onMounted, or check before using them.
  • Side effects in render. Rendering must have no side effects, because the server renders every request.
  • Data fetching needs a plan. The server should fetch data before rendering and send it to the browser, so the client does not fetch it again and render something different.

Static site generation

SSG is SSR run once at build time. Each page is rendered to an .html file and uploaded to a static host or CDN. You get the same fast first paint without a running server, and the page can be cached everywhere. It suits content that changes rarely: documentation, a blog, a marketing site. Pages with per-user data are loaded in the browser after hydration. Many frameworks mix the two, with some routes pre-rendered and others rendered on demand.

Should you use it?

Use SSR or SSG when:

  • search engines and link previews must see your content (public marketing pages, shops, blogs);
  • first paint speed on slow networks matters;
  • the content is public and mostly the same for everyone.

Skip it when:

  • the app sits behind a login (a dashboard, an admin panel), so SEO is irrelevant;
  • you cannot run Node on the server, and the content changes too often for SSG;
  • the team is small and the extra complexity would cost more than it returns.

An SPA with good code splitting (see Build and Load Performance) is a fine answer for many apps. If you do need SSR, use a framework such as Nuxt rather than building the plumbing yourself.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is hydration?

    The server sends finished HTML. Hydration lets Vue reuse those elements and make them interactive, instead of rebuilding them from scratch.
  2. 2. Why can't a server-rendered HTML string contain your onClick handlers?

    renderToString returns plain text. Event handlers are functions that exist only in running JavaScript, which is why the browser must hydrate.
  3. 3. Which code is most likely to cause a hydration mismatch?

    Randomness and browser-only values give different results on the server and in the browser, so the first client render does not match the server HTML.
  4. 4. Why is a module-level reactive store dangerous in SSR?

    The server process lives across many requests. State created at module level is shared by all of them, so create apps and stores per request.
  5. 5. Which hook runs on the server during SSR?

    Only setup and the creation phase run during server rendering. Hooks that need a DOM, such as onMounted, run only in the browser.

Summary

  • SSR renders components to HTML on the server (renderToString), so users and crawlers get content before any JavaScript runs.
  • Hydration (createSSRApp(...).mount(...)) makes that HTML interactive by reusing the existing elements.
  • Server HTML and the first client render must match; avoid browser-only or random values in render and use onMounted for them.
  • Create apps, routers and stores per request, and keep module-level state out of server code.
  • SSG pre-renders pages at build time and suits mostly static content.
  • Choose SSR or SSG for public, SEO-sensitive pages, and a plain SPA for apps behind a login.

Next, in Nuxt Overview, you will see the framework that wires SSR, routing and data fetching together for you.