When does this error occur?
The document object is part of the browser’s Window interface and represents the DOM (Document Object Model) of the current web page. When Next.js renders pages on the server, there is no browser environment, so the document object is not defined. This results in the “document is not defined” error when code that references the document is executed on the server.
This error typically occurs in this scenario: Direct usage of document in the component’s render method or lifecycle methods.
//index.js
import Head from "next/head";
// This code will throw an error during SSR
const MyComponent = () => {
const element = document.getElementById("some-id");
return <div>{element ? element.textContent : "No element"}</div>;
};
export default function Home() {
return (
<>
<Head>
<title>Create Next App</title>
<meta name="description"
content="Generated by create next app" />
<meta name="viewport"
content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<div style={{
minHeight: "100vh", backgroundColor: "white"
}}>
<MyComponent />
</div>
</main>
</>
);
}
How to fix “Next.js: document is not defined”?
Next.js is a powerful React framework that allows developers to create server-side rendered (SSR) and static web applications. A common error encountered while working with Next.js is the “document is not defined” error. This error happens because the document is a client-side browser object, which isn’t available during server-side rendering. In this article, we’ll explain why this error occurs and how to fix it.
Table of Content
- When does this error occur?
- Fixing Document not defined
- Detailed Code Explanation
- Best practices to avoid document is not defined error
- Conclusion
Contact Us