The "ReferenceError: document is not defined" error is seen in Node.js or frameworks based in Node.js, like Next.js. It can be solved by moving your JavaScript tag to the bottom of the body
tag or, in Next.js, by wrapping your code in a conditional.
document
is an object that represents a web pages that is loaded in the browser. Node.js does not provide a browser environment, and so the document
variable does not exist. This is because Node.js is a server-side runtime, not a client-side one. The client, also known as the frontend, or the web browser, does not exist.
Try moving your JavaScript tag to the bottom of the body
tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<!-- Your HTML here -->
<!-- 👇️ move script to the bottom of <body>, before </body> -->
<script type="module" src="index.js"></script>
</body>
</html>
If you are using Next.js, a React-based web framework, you can fix this problem by wrapping your code in a conditional. This error occurs because Next.js has server-side rendering, and therefore, no browser.
if (typeof window !== "undefined") {
// ...
}
As the window
is part of the browser, if there is no window
, then the code will not run.
This is the preferred solution. Another solution is to use dynamic rendering to prevent server-side rendering for your component.
import dynamic from "next/dynamic";
const DynamicComponentWithNoSSR = dynamic(() => import("../components/List"), {
ssr: false,
});
export default () => <DynamicComponentWithNoSSR />;
If you are using React Hooks, you can use useEffect
and useState
.
import React, {useState, useEffects} from 'react';
const DynamicComponentWithNoSSR =
<>
{/* your JSX */}
</>
export default function App(){
[a, setA] = useState();
useEffect(() => {
setA(<DynamicComponentWithNoSSR/>)
});
return (<>{a}<>)
}
The "ReferenceError: document is not defined" error is seen in Node.js or frameworks based in Node.js, like Next.js. It can be solved by moving your JavaScript tag to the bottom of the body
tag or, in Next.js, by wrapping your code in a conditional.
Related tutorials curated for you
Cannot use import statement outside a module in JavaScript
Sort dates in JavaScript
ReferenceError: document is not defined in JavaScript
Returning multiple values in JavaScript
Unexpected token u in JSON at position 0 Error
Could not find module '@angular-devkit/build-angular'