Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 38 ยท Frameworks and SSR

SSR Build, Hydration and Prerendering

Build both bundles for a Vite SSR app, serve them in production, pass state to the client, avoid hydration mismatches, and prerender pages to static HTML.

In development, ssrLoadModule transforms files on demand. In production you need real build output: a client bundle for browsers and a server bundle for Node. This lesson covers the two build commands, the production server, how to hand data from server to client, hydration mismatches and the static alternative, prerendering.

You should know the model from SSR Fundamentals. Real Vite code is read-only; stand-ins in plain JavaScript show state serialization and a mismatch check.

Two builds

JSON
{
  "scripts": {
    "dev": "node server.js",
    "build": "npm run build:client && npm run build:server",
    "build:client": "vite build --outDir dist/client",
    "build:server": "vite build --outDir dist/server --ssr src/entry-server.js",
    "preview": "NODE_ENV=production node server.js"
  }
}
  • The client build (the normal vite build) outputs hashed assets and dist/client/index.html. The index.html includes the <!--ssr-outlet--> placeholder untouched.
  • The server build with --ssr outputs a Node-targeted module. Dependencies stay external by default (they are required from node_modules at runtime), which keeps the server bundle small and fast to load.

For a manifest that lets the server preload the right chunks, add --ssrManifest to the client build (named ssr-manifest in newer versions). A framework uses it to emit <link rel="modulepreload"> for exactly the modules a page needs.

The production server

JavaScript
// server.js, production branch (real Vite, read-only)
import fs from 'node:fs/promises';
import express from 'express';
import compression from 'compression';
import sirv from 'sirv';

const app = express();
app.use(compression());
app.use('/', sirv('./dist/client', { extensions: [] })); // static assets

const template = await fs.readFile('./dist/client/index.html', 'utf-8');
const { render } = await import('./dist/server/entry-server.js');

app.use('*all', async (req, res) => {
  const { html, state } = await render(req.originalUrl);
  const page = template
    .replace('<!--ssr-outlet-->', html)
    .replace('<!--ssr-state-->', '<script>window.__STATE__=' + serialize(state) + '</script>');
  res.status(200).set({ 'Content-Type': 'text/html' }).end(page);
});

app.listen(3000);

No Vite server is involved in production: the template is read once, render is imported once, and static files are served with long cache headers (they have hashes).

Passing state from server to client

If the server fetched data to render the page, the client must start from the same data, otherwise it would fetch again and the markup could differ. The usual pattern is to embed the state as JSON in the HTML. Serialize it safely: a string containing </script> would end your script tag early and open an injection hole.

JS Stand-in: safe state serialization

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

No output.

The escaped version still parses to the identical value because < is a valid JSON escape for <. Libraries such as devalue or serialize-javascript do this and also handle dates, Maps and cycles.

Hydration and mismatches

On the client, hydrate (React: hydrateRoot, Vue: createSSRApp().mount) walks the existing DOM and attaches handlers. It assumes the first client render produces the same markup the server produced. If not, you get a hydration mismatch warning, flashes of wrong content, or lost state.

Typical causes:

  • Output that depends on Date.now(), Math.random() or a time zone.
  • Reading window, localStorage or matchMedia during render.
  • Invalid HTML nesting (<div> inside <p>), which the browser repairs before hydration sees it.
  • Different data on the client than on the server.

Fixes: compute such values once on the server and send them as state, or render them after mount (in an effect) so both first renders match.

JS Stand-in: detect a mismatch

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

No output.

Prerendering (static site generation)

If a page does not need per-request data, render it once at build time and publish plain HTML files. The server entry is reused; a script loops over a list of routes:

JavaScript
// prerender.js (real Vite, read-only)
import fs from 'node:fs';
import path from 'node:path';

const template = fs.readFileSync('dist/client/index.html', 'utf-8');
const { render } = await import('./dist/server/entry-server.js');

const routes = ['/', '/about', '/pricing'];
for (const url of routes) {
  const { html } = await render(url);
  const file = 'dist/client' + (url === '/' ? '/index' : url) + '.html';
  fs.mkdirSync(path.dirname(file), { recursive: true });
  fs.writeFileSync(file, template.replace('<!--ssr-outlet-->', html));
  console.log('pre-rendered:', file);
}

Then host dist/client on any static host or CDN. You get SSR's first-paint and SEO benefits without running a server, at the cost that content changes need a rebuild. Frameworks combine both: static where possible, server rendering where data is per-request.

SSR build options worth knowing

  • ssr.noExternal: ['some-lib']: bundle a dependency into the server build (needed for packages that ship untranspiled ESM or CSS imports).
  • ssr.external: keep specific packages external.
  • build.ssrEmitAssets: also emit assets in the server build (off by default).
  • ssr.target: 'node' (default) or 'webworker' for edge runtimes.

When to choose a framework

Everything above, plus routing, data loading, streaming, caching and error handling, is what a framework implements for you. If your app needs more than one or two SSR pages in production, evaluate a Vite-based meta-framework (React Router framework mode, Nuxt, SvelteKit, SolidStart, Astro) before building your own server.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the --ssr flag do in vite build --ssr src/entry-server.js?

    --ssr builds the given entry for server-side execution, keeping dependencies external by default.
  2. 2. Why must embedded JSON state escape the < character?

    Replacing < with \u003c keeps the data identical when parsed but prevents breaking out of the script element.
  3. 3. Which is a common cause of hydration mismatch?

    The server and client compute different values, so the first client render differs from the server markup.
  4. 4. When is prerendering a good choice?

    Prerendered HTML can be served from a CDN with no server, but it only fits content that does not vary per request.

Summary

  • SSR production needs two builds: client (vite build) and server (vite build --ssr).
  • The production server reads the built template, imports the server bundle and serves hashed assets statically.
  • Embed state as safely escaped JSON so the client starts with the same data.
  • Avoid hydration mismatches: no random or time-based values or browser globals in the first render.
  • Prerender static pages at build time; use a framework when needs grow.

Next: Backend Integration