React项目出现ReferenceError: document is not defined错误,配置路由后问题仍未解决
Hey there! Let's break down why you're still seeing that ReferenceError: document is not defined even after setting up your React Router.
First off, this error almost always pops up when your code tries to access the browser's document object in an environment where it doesn't exist—most commonly server-side rendering (SSR) setups like Next.js. Server-side environments don't have browser-specific APIs like document, so any code that references it directly at the top level will throw this error.
Looking at your code, you're calling ReactDOM.createRoot(document.getElementById("root")) right at the top level. If this code is being executed on the server (for example, in a Next.js app), that's exactly where the error is coming from.
Here are a few practical fixes tailored to your scenario:
1. Wrap your rendering logic in a browser check
Add a simple condition to ensure the code only runs when document is available (i.e., in the browser):
import React from "react"; import ReactDOM from "react-dom/client"; import App from "../components/app"; import reportWebVitals from "./reportWebVitals"; import { createBrowserRouter, RouterProvider } from "react-router-dom"; import Product from "./products/product"; const router = createBrowserRouter([ { path: "/", element: <App />, }, ]); // Only run this in the browser environment if (typeof document !== 'undefined') { ReactDOM.createRoot(document.getElementById("root")).render( <React.StrictMode> <RouterProvider router={router} /> </React.StrictMode> ); } reportWebVitals();
2. If you're using Next.js (App Router)
If you're working with Next.js 13+ and the App Router, you'll need to adjust your routing approach:
- Add
'use client'at the top of your routing file to mark it as a client component (since React Router relies on browser APIs). - Alternatively, consider using Next.js's built-in App Router instead of
react-router-dom—it's designed to work seamlessly with SSR out of the box.
3. Check for other rogue document references
Double-check if any of your components (like App or Product) are using document at the top level (outside of hooks like useEffect). If they are, wrap that code in useEffect to delay execution until the component mounts in the browser:
import { useEffect } from 'react'; function MyComponent() { useEffect(() => { // Code that uses document goes here const element = document.getElementById('some-element'); }, []); return <div>...</div>; }
The core idea here is: any code that touches browser-specific APIs like document needs to be restricted to the browser environment—either via conditional checks or React hooks that run client-side only.
备注:内容来源于stack exchange,提问作者SalimKazi

