Separating client and server entries for Vite SSR
Build separate React entries with Vite, render the server entry through Express, and verify that the response hydrates against the same initial state.
A Vite SSR application has two consumers of the same components. Node renders the first HTML response, and the browser attaches behavior to it. I separate those two entry points so each can use the APIs of its own runtime.
Drawing the SSR boundary
A framework can supply routing, data loading, assets, and deployment policy around SSR. Vite also exposes lower-level build and development APIs. The minimal server here owns request routing and data preparation. The client bundle owns hydration and later interactions.
flowchart TD
APP["Shared React components"] --> CLIENT["Build browser entry"]
APP --> SERVER["Build Node SSR entry"]
CLIENT --> HTML["Client assets and template"]
SERVER --> RENDER["Render request on server"]
HTML --> RENDER
RENDER --> BROWSER["Browser hydrates the response"]
Keep the shared components portable between the runtimes. Code that needs window belongs behind a browser boundary. Application data for a server render should come from the current request rather than shared mutable module state.
Sharing the component and separating the entries
The app receives data as props. The browser entry reads the same data from the served page and calls React’s hydrateRoot(). The server entry renders the component tree to a string for each request.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// src/App.tsx
import React, { useState } from 'react';
import './App.css';
export interface UserState {
id: number;
role: string;
}
interface AppProps {
initialUser?: UserState;
}
export const App: React.FC<AppProps> = ({ initialUser }) => {
const [user] = useState<UserState>(initialUser || { id: 0, role: 'guest' });
const [count, setCount] = useState(0);
return (
<div className="ssr-container">
<header className="gnb">
<h1>Namju's Commit Log</h1>
</header>
<main className="container">
<h2>Initial HTML rendered on the server</h2>
<p>User ID: {user.id} ({user.role})</p>
<button
className="interactive-btn"
onClick={() => setCount((prev) => prev + 1)}
>
Hydration counter: {count}
</button>
</main>
</div>
);
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// src/entry-client.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { App, UserState } from './App';
// Read the initial state embedded by the server.
declare global {
interface Window {
__INITIAL_STATE__?: {
user: UserState;
};
}
}
const initialState = window.__INITIAL_STATE__;
const container = document.getElementById('app');
if (container) {
// Attach React to the server-rendered HTML using hydrateRoot.
ReactDOM.hydrateRoot(
container,
<React.StrictMode>
<App initialUser={initialState?.user} />
</React.StrictMode>
);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/entry-server.tsx
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { App, UserState } from './App';
export interface RenderContext {
url: string;
user: UserState;
}
export interface RenderResult {
html: string;
initialState: {
user: UserState;
};
}
export function render(context: RenderContext): RenderResult {
const initialState = {
user: context.user
};
const html = ReactDOMServer.renderToString(
<React.StrictMode>
<App initialUser={context.user} />
</React.StrictMode>
);
return { html, initialState };
}
Hydration assumes that the first browser render matches the server output. Check branching based on time, randomness, browser globals, or locale. If those values are essential to the first render, make them deterministic or pass the same explicit data through both entries.
Building the HTML, client, and server bundles
The client HTML contains slots for the rendered markup and browser bootstrap state. Vite runs once for the client bundle and again in SSR mode for the server entry. Keep the two outputs separate so the server bundle is imported by Node and not exposed as a static asset.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- index.html -->
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite SSR Production</title>
<!--app-head-->
</head>
<body>
<div id="app"><!--app-html--></div>
<!--app-state-->
<script type="module" src="/src/entry-client.tsx"></script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// package.json
{
"name": "vite-ssr-app",
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "node server.js",
"build:client": "vite build --outDir dist/client",
"build:server": "vite build --ssr src/entry-server.tsx --outDir dist/server",
"build:ssr": "pnpm build:client && pnpm build:server",
"serve": "cross-env NODE_ENV=production node server.js"
},
"dependencies": {
"compression": "^1.7.4",
"express": "^4.21.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"sirv": "^2.0.4"
},
"devDependencies": {
"@types/compression": "^1.7.5",
"@types/express": "^4.17.21",
"@types/react": "^18.3.11",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.2",
"cross-env": "^7.0.3",
"typescript": "^5.6.3",
"vite": "^5.4.8"
}
}
1
2
# Build the client and server bundles
pnpm run build:ssr
Figure 1. The client output and the Node server entry are built separately.
The client directory holds assets and the HTML template. The server directory holds the SSR entry. Enable the client manifest if server-side code actually needs it. The template approach shown here can use the links that Vite already placed in the built HTML.
Serving the built response
Express serves static assets from the client output and uses the server module for application requests. The sample loads the built template and server entry and prepares a per-request input. A long-running server can cache a verified template and import the entry before listening. A development implementation normally uses Vite’s middleware and module-loading API instead.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// server.js
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import express from 'express';
import compression from 'compression';
import sirv from 'sirv';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const isProduction = process.env.NODE_ENV === 'production';
async function createServer() {
const app = express();
app.use(compression());
if (isProduction) {
// 1. Serve the built client assets in production.
app.use(
sirv(path.resolve(__dirname, 'dist/client'), {
extensions: []
})
);
}
// 2. Handle requests that need SSR.
app.use(async (req, res, next) => {
const url = req.originalUrl;
try {
let template;
let render;
if (isProduction) {
// Read the built HTML and import the built SSR entry.
template = fs.readFileSync(
path.resolve(__dirname, 'dist/client/index.html'),
'utf-8'
);
const serverEntry = await import('./dist/server/entry-server.js');
render = serverEntry.render;
} else {
// Development middleware is outside this production example.
return next();
}
// Simulate loading request-specific user data.
const mockUser = { id: 1, role: 'admin' };
// Render the component tree on the server.
const { html: appHtml, initialState } = render({
url,
user: mockUser
});
// Insert the markup and safely serialized browser state.
const stateScript = `<script>window.__INITIAL_STATE__=${JSON.stringify(initialState).replace(/</g, '\\u003c')}</script>`;
const finalHtml = template
.replace('<!--app-html-->', () => appHtml)
.replace('<!--app-state-->', () => stateScript);
res.status(200).set({ 'Content-Type': 'text/html' }).end(finalHtml);
} catch (e) {
console.error('SSR Render Error:', e);
res.status(500).end('Internal Server Error');
}
});
const port = process.env.PORT || 5173;
app.listen(port, () => {
console.log(`Server listening on http://localhost:${port}`);
});
}
createServer();
Bootstrap state is visible to the browser. Include only the data it needs, escape serialized values for the HTML script context, and keep authentication tokens and other secrets on the server. The example’s mock user illustrates the handoff.
Verifying markup and hydration
Start the application and fetch it with curl. The response should already contain the rendered markup and the expected initial-state script without executing browser JavaScript.
1
2
3
4
5
# Start the production server
pnpm serve
# Inspect the HTTP response in another terminal
curl -i http://localhost:5173/
Figure 2. The server response contains the page markup plus the data used by hydration.
Open the same URL in a browser and check that the counter works without a hydration mismatch. Then send two requests with different inputs and confirm that neither response includes the other request’s data. That check is especially important when adding a store, a cache, or an authenticated route.