Hydration Errors in React SSR with Vite and React-Router-Dom

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:

  1. 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>
      );
    };
    
  2. Home.tsx:

    const Home = () => {
      return (
        <div>Home Page</div>
      );
    };
    
    export default Home;
    
  3. 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;
    
  4. 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>
    );
    
  5. 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 };
    }
    
  6. 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}`);
    });
    
  7. 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!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật