Skip to content

Instantly share code, notes, and snippets.

@mizchi
Last active September 6, 2023 11:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizchi/3d5df8ec8c2deef967c07bd368ec077a to your computer and use it in GitHub Desktop.
Save mizchi/3d5df8ec8c2deef967c07bd368ec077a to your computer and use it in GitHub Desktop.
Minimum Vite SSR (dev)
// src/entry.client.tsx
import Root from "./Root";
import { hydrateRoot } from "react-dom/client";
hydrateRoot(document.getElementById("app")!, <Root />);
// src/entry.ssr.tsx
import App from "./Root";
import { renderToString } from "react-dom/server";
export const render = (_req: Request) => {
return renderToString(<App />);
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SSR Example</title>
</head>
<body>
<div id="app"><!--ssr-outlet--></div>
<script type="module" src="/src/entry.client.tsx"></script>
</body>
</html>
// src/Root.tsx
import {useState} from "react";
export default function Root() {
const [count, setCount] = useState(0);
return <div>
<h1>App</h1>
<button type="button" onClick={() => setCount(n => n+1)}>{count}</button>
</div>
}
// $ vite --mode ssr
import {defineConfig, type Plugin} from 'vite';
import fs from 'fs';
import path from 'path';
const myssr = (): Plugin => {
return {
name: 'myssr',
configureServer(server) {
const templateBase = fs.readFileSync(
path.resolve(__dirname, 'index.html'),
'utf-8',
);
return () => {
server.middlewares.use(async (req, res) => {
const url = req.originalUrl! ?? req.url!;
const ssr = await server.ssrLoadModule('/src/entry.ssr.tsx');
const content = ssr.render(req);
const transformed = await server.transformIndexHtml(url, templateBase);
const html = transformed.replace(`<!--ssr-outlet-->`, content);
res.setHeader('Content-Type', 'text/html')
res.end(html)
});
}
}
}
};
export default defineConfig({
plugins: [
myssr()
],
build: {
ssr: true,
rollupOptions: {
input: ['src/entry.ssr.tsx']
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment