Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 38 ยท Frameworks and SSR

Server-Side Rendering Fundamentals in Vite

Understand server-side rendering with Vite: what SSR is, why use it, how the dev server loads modules with ssrLoadModule, and how a Node server renders HTML.

A normal Vite app is a client-side rendered (CSR) single-page application. The server sends a nearly empty index.html, the browser downloads JavaScript, and the JavaScript builds the page. Users see a blank screen until that finishes, and crawlers that do not run JavaScript see nothing at all.

Server-side rendering (SSR) runs your components on the server and sends finished HTML. The page is visible at once; JavaScript then loads and hydrates it, attaching event handlers to the existing markup. Vite has built-in support for this, but it gives you building blocks, not a ready framework. This lesson explains the model and the dev-time piece, ssrLoadModule. The real Vite code is read-only; the runnable blocks are stand-ins.

CSR vs SSR in one picture

flowchart LR
  subgraph CSR
    A1["Browser requests page"] --> A2["Empty HTML + JS"] --> A3["JS runs, page appears"]
  end
  subgraph SSR
    B1["Browser requests page"] --> B2["Server renders components to HTML"] --> B3["HTML visible at once"] --> B4["JS hydrates"]
  end

SSR shows content sooner and gives crawlers real HTML, at the cost of a server that runs your code.

Reasons to use SSR: faster first paint on slow devices, better SEO and link previews, and server-side data fetching with no loading spinner. Reasons not to: it needs a Node (or edge) runtime, adds complexity, and a static site generator or plain CSR may be enough. If your pages are known at build time, consider prerendering (static generation) instead; the same code can do it.

The two entry points

An SSR app has two entries sharing one component tree:

  • entry-client.js: runs in the browser, hydrates the markup.
  • entry-server.js: runs on the server, exports a render(url) function that returns HTML.
JavaScript
// src/entry-server.js (real code with a framework, shown here without one)
import { renderApp } from './app.js';

export async function render(url) {
  const html = renderApp({ url });
  return { html };
}
JavaScript
// src/entry-client.js
import { hydrateApp } from './app.js';
hydrateApp(document.getElementById('app'));

And index.html has a placeholder the server replaces:

HTML
<div id="app"><!--ssr-outlet--></div>
<script type="module" src="/src/entry-client.js"></script>

Stand-in: render a page to a string

At its core, SSR is "turn data into an HTML string". This stand-in uses plain template strings, the same idea frameworks implement with components.

JS Stand-in: render(url) returns HTML

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

No output.

Look at the escaping: the title Hello <Vite> became Hello &lt;Vite&gt;. Rendering user data without escaping is a cross-site scripting hole. Frameworks escape for you; hand-written SSR must do it explicitly.

The dev server in middleware mode

Vite can run inside your own server. In middleware mode you create a Vite server with appType: 'custom' and mount it in Express (or any Connect-compatible server). Vite handles module requests and HMR; you handle HTML.

JavaScript
// server.js (real Vite, read-only)
import fs from 'node:fs/promises';
import express from 'express';
import { createServer as createViteServer } from 'vite';

const app = express();

const vite = await createViteServer({
  server: { middlewareMode: true },
  appType: 'custom',
});
app.use(vite.middlewares);

app.use('*all', async (req, res, next) => {
  const url = req.originalUrl;
  try {
    // 1. read index.html and let Vite inject the HMR client etc.
    let template = await fs.readFile('index.html', 'utf-8');
    template = await vite.transformIndexHtml(url, template);

    // 2. load the server entry; Vite transforms it on the fly (ESM, TS, JSX...)
    const { render } = await vite.ssrLoadModule('/src/entry-server.js');

    // 3. render and inject into the template
    const { html } = await render(url);
    res.status(200).set({ 'Content-Type': 'text/html' })
       .end(template.replace('<!--ssr-outlet-->', html));
  } catch (error) {
    vite.ssrFixStacktrace(error); // map stack traces back to your sources
    next(error);
  }
});

app.listen(5173);

Key calls:

  • vite.transformIndexHtml applies plugin HTML hooks and injects the dev client.
  • vite.ssrLoadModule loads a module for Node, transforming it first, and re-loads it when files change, so you get HMR-like behavior on the server without restarting.
  • vite.ssrFixStacktrace rewrites stack traces to point at your original files.

In recent Vite versions the Environment API formalizes this: the server side is a separate "environment" with its own module graph and runner, which also lets you run server code in runtimes such as workers. The mental model above stays the same.

SSR-safe code

Code that runs on the server must not touch browser-only globals at import time. window, document, localStorage and navigator do not exist in Node.

JavaScript
// Wrong: crashes on the server
const width = window.innerWidth;

// Right: guard, or move into an effect that only runs in the browser
const width = typeof window !== 'undefined' ? window.innerWidth : 0;

Vite also provides import.meta.env.SSR, a boolean that is true on the server and replaced at build time, so the other branch is removed:

JS Stand-in: SSR-safe code

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

No output.

Other rules: do not keep per-request data in module-level variables on the server (all requests share them), and avoid libraries that assume a DOM at import time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is hydration?

    The server sends finished HTML; the client code then makes it interactive without rebuilding it from scratch.
  2. 2. What does vite.ssrLoadModule do?

    It lets the dev server run your server entry through Vite's transform pipeline without a separate build.
  3. 3. Which code crashes in Node at import time?

    window does not exist on the server. Guard it or run it only in the browser.
  4. 4. Why escape data when rendering HTML strings?

    Unescaped user data can inject scripts into the page; frameworks escape by default.

Summary

  • SSR renders HTML on the server; the client hydrates it. It helps first paint and SEO.
  • Use two entries: entry-client and entry-server with a render(url) function.
  • In dev, run Vite in middleware mode and call transformIndexHtml and ssrLoadModule.
  • Keep code SSR-safe: guard browser globals, avoid shared per-request state, escape output.
  • import.meta.env.SSR branches are removed at build time.

Next: SSR Build and Hydration