I’m working on setting up Server-Side Rendering (SSR) for a React application using Vite. I am also using react-router-dom
for routing. While the server and client rendering works fine individually, I’m encountering several hydration errors when the client attempts to hydrate the HTML rendered by the server. Below are the details of my setup:
Project Structure:
-
Router.tsx:
import { Routes, Route } from 'react-router-dom'; import Card from './Card'; import Home from './Home'; export const Router = () => { return ( <Routes> <Route path="/" element={<Home />} /> <Route path="/card" element={<Card />} /> </Routes> ); };
-
Home.tsx:
const Home = () => { return ( <div>Home Page</div> ); }; export default Home;
-
Card.tsx:
import { useState } from 'react'; function Card() { const [count, setCount] = useState(0); return ( <div className="card"> <button onClick={() => setCount(count + 1)}> count is {count} </button> <p> Edit <code>src/App.tsx</code> and save to test HMR </p> </div> ); } export default Card;
-
entry-client.tsx:
import React from 'react'; import ReactDOM from 'react-dom/client'; import { BrowserRouter } from 'react-router-dom'; import './index.css'; import { Router } from './Router'; ReactDOM.hydrateRoot( document.getElementById('root') as HTMLElement, <React.StrictMode> <BrowserRouter> <Router /> </BrowserRouter> </React.StrictMode> );
-
entry-server.tsx:
import React from 'react'; import ReactDOMServer from 'react-dom/server'; import { StaticRouter } from 'react-router-dom/server'; import { Router } from './Router'; interface IRenderProps { path: string; } export function render({ path }: IRenderProps) { const html = ReactDOMServer.renderToString( <React.StrictMode> <StaticRouter location={path}> <Router /> </StaticRouter> </React.StrictMode> ); return { html }; }
-
server.js:
import fs from 'node:fs/promises'; import express from 'express'; const isProduction = process.env.NODE_ENV === 'production'; const port = process.env.PORT || 5173; const base = process.env.BASE || '/'; const templateHtml = isProduction ? await fs.readFile('./dist/client/index.html', 'utf-8') : ''; const ssrManifest = isProduction ? await fs.readFile('./dist/client/.vite/ssr-manifest.json', 'utf-8') : undefined; const app = express(); let vite; if (!isProduction) { const { createServer } = await import('vite'); vite = await createServer({ server: { middlewareMode: 'ssr' }, appType: 'custom', base, }); app.use(vite.middlewares); } else { const compression = (await import('compression')).default; const sirv = (await import('sirv')).default; app.use(compression()); app.use(base, sirv('./dist/client', { extensions: [] })); } app.use('*', async (req, res) => { try { const url = req.originalUrl.replace(base, ''); let template; let render; if (!isProduction) { template = await fs.readFile('./index.html', 'utf-8'); template = await vite.transformIndexHtml(url, template); render = (await vite.ssrLoadModule('/src/entry-server.tsx')).render; } else { template = templateHtml; render = (await import('./dist/server/entry-server.js')).render; } const rendered = await render({ path: url }); const html = template .replace(`<!--app-head-->`, '') .replace(`<!--app-html-->`, rendered.html); res.status(200).set({ 'Content-Type': 'text/html' }).send(html); } catch (e) { vite?.ssrFixStacktrace(e); console.log(e.stack); res.status(500).end(e.stack); } }); app.listen(port, () => { console.log(`Server started at http://localhost:${port}`); });
-
vite.config.ts:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], });
The Errors:
When running the app, I’m encountering the following errors:
chunk-M324AGAM.js?v=5551cca4:519 Warning: Expected server HTML to contain a matching <button> in <div>.
chunk-M324AGAM.js?v=5551cca4:9471 Uncaught Error: Hydration failed because the initial UI does not match what was rendered on the server.
chunk-M324AGAM.js?v=5551cca4:519 Warning: An error occurred during hydration. The server HTML was replaced with client content in <div>.
chunk-M324AGAM.js?v=5551cca4:9471 Uncaught Error: Hydration failed because the initial UI does not match what was rendered on the server.
chunk-M324AGAM.js?v=5551cca4:14758 Uncaught Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.
Problem:
The errors suggest a mismatch between the HTML generated on the server and what is expected by React on the client. This is causing hydration to fail, and React is falling back to client-side rendering, which negates the benefits of SSR.
Question:
What could be causing these hydration errors, and how can I ensure that the server and client render the same HTML to prevent these issues? Are there specific considerations I should take into account when using react-router-dom
with SSR in Vite?
Any help or suggestions on how to resolve these issues would be greatly appreciated!