Vite SSR Overview
So far every page was rendered in the browser: the server sends an almost empty index.html, JavaScript downloads, then the UI appears. Server-side rendering (SSR) renders the HTML on the server first, so users (and search engines) get real content immediately; then the client-side JavaScript hydrates it to make it interactive.
Vite provides low-level SSR building blocks. Most people use them through a framework — Nuxt, SvelteKit, Astro, React Router, TanStack Start, Analog, Vike — but understanding the basics helps you debug any of them.
CSR vs SSR vs SSG
| Strategy | HTML produced | Good for |
|---|---|---|
| CSR (client-side rendering) | In the browser, after JS loads | Dashboards, apps behind a login |
| SSR (server-side rendering) | On the server, per request | Personalized pages, SEO, fast first paint |
| SSG (static site generation) | At build time, once | Docs, blogs, marketing pages |
The core idea, runnable
An SSR app has one shared component and two entry points. The server calls render(url) to get an HTML string and injects it into the template; the client attaches event listeners to that existing HTML.
// shared "component"
function App({ url, courses }) {
return `<main><h1>Courses</h1><p>Path: ${url}</p><ul>${courses
.map((c) => `<li>${c}</li>`)
.join('')}</ul></main>`;
}
// entry-server.js
function render(url) {
const courses = ['Rust', 'Vite']; // e.g. loaded from a database
return { html: App({ url, courses }) };
}
// server.js
const template = '<!doctype html><html><body><div id="app"><!--app-html--></div><script type="module" src="/src/entry-client.js"></script></body></html>';
const { html } = render('/courses');
console.log(template.replace('<!--app-html-->', html));<!doctype html><html><body><div id="app"><main><h1>Courses</h1><p>Path: /courses</p><ul><li>Rust</li><li>Vite</li></ul></main></div><script type="module" src="/src/entry-client.js"></script></body></html>
Project layout
├── index.html ← contains <!--app-html--> placeholder
├── server.js ← Node/Express server
└── src/
├── main.js ← shared app code
├── entry-client.js ← hydrates in the browser
└── entry-server.js ← exports render(url)npm create vite-extra@latest offers ready-made SSR templates (ssr-vanilla, ssr-react, ssr-vue, …) with exactly this layout.
Development: Vite as middleware
In dev, your own Node server owns the HTTP port and uses Vite in middleware mode for module transforms and HMR. ssrLoadModule imports source files (TS, JSX, Vue…) on the server, transformed on the fly:
// server.js (development part)
import express from 'express';
import { createServer as createViteServer } from 'vite';
import fs from 'node:fs/promises';
const app = express();
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'custom', // we serve HTML ourselves
});
app.use(vite.middlewares);
app.use('*all', async (req, res, next) => {
try {
const url = req.originalUrl;
let template = await fs.readFile('index.html', 'utf-8');
template = await vite.transformIndexHtml(url, template); // injects HMR client
const { render } = await vite.ssrLoadModule('/src/entry-server.js');
const { html } = await render(url);
res.status(200).set({ 'Content-Type': 'text/html' }).end(template.replace('<!--app-html-->', html));
} catch (e) {
vite.ssrFixStacktrace(e);
next(e);
}
});
app.listen(5173);| API | Role |
|---|---|
createServer({ server: { middlewareMode: true } }) |
Vite without its own HTTP server |
vite.middlewares |
Connect-style middleware for assets, modules, HMR |
vite.transformIndexHtml(url, html) |
Apply HTML plugins + inject the HMR client |
vite.ssrLoadModule(path) |
Import a source module in Node with Vite transforms |
vite.ssrFixStacktrace(err) |
Map stack traces back to source |
Note: Vite 6 introduced the Environment API, which models "client" and "ssr" (and e.g. edge workers) as separate environments with their own module graphs.
ssrLoadModulestill works; frameworks increasingly use the newModuleRunnerAPIs.
Production: two builds
{
"scripts": {
"dev": "node server.js",
"build:client": "vite build --outDir dist/client",
"build:server": "vite build --ssr src/entry-server.js --outDir dist/server",
"build": "npm run build:client && npm run build:server",
"start": "NODE_ENV=production node server.js"
}
}npm run build:server> my-ssr-app@0.0.0 build:server
> vite build --ssr src/entry-server.js --outDir dist/server
vite v8.3.4 building ssr environment for production...
✓ 4 modules transformed.
dist/server/entry-server.js 1.21 kB
✓ built in 52ms
In production, the server reads dist/client/index.html as the template, imports ./dist/server/entry-server.js directly, and serves dist/client/assets as static files (for example with sirv or express.static).
Hydration
The client entry doesn't rebuild the page; it attaches behaviour to the server's HTML. Try it — the list below arrives "from the server", and the script only adds a click handler:
<!doctype html>
<html>
<body style="font-family: system-ui">
<!-- HTML as rendered by the server: visible before any JS runs -->
<div id="app"><main><h1>Courses</h1><ul><li>Rust</li><li>Vite</li></ul><button id="more">Load more</button></main></div>
<script type="module">
// entry-client.js: hydrate — reuse the existing DOM, attach events
const list = document.querySelector('#app ul');
document.querySelector('#more').addEventListener('click', () => {
list.insertAdjacentHTML('beforeend', '<li>TypeScript (client-rendered)</li>');
});
</script>
</body>
</html>SSR gotchas
- No
windowordocumenton the server. Guard browser-only code (if (typeof window !== 'undefined')) or run it in lifecycle hooks that only run on the client. - Dependencies are externalized during SSR (loaded from
node_modulesby Node). Packages that ship un-compiled code may needssr.noExternal: ['some-pkg']. import.meta.env.SSRistruein server code, so you can branch at build time.- Mismatched HTML between server and client causes hydration warnings — render the same data on both sides.
Test yourself
What does vite.ssrLoadModule('/src/entry-server.js') do?
- Sends the file to the browser
- Imports the module in Node, transformed by Vite
- Builds the client bundle
- Starts a new dev server
What is hydration?
- Rendering HTML on the server
- Attaching client-side behaviour to server-rendered HTML
- Compressing assets
- Caching API responses
Which command builds the server bundle?
- vite build --ssr src/entry-server.js
- vite preview --ssr
- vite serve --node
- vite build --lib