bf135e4c2ae932613071
·2 min read

"document is not defined" Error in Next.js

nextjs
build
error
fix
4d5fd787ac74e0caa4f7

Sohan R. Emon

Developer, Learner, Tech Enthusiast

When working with Next.js, you might come across the "ReferenceError: document is not defined" error. This error typically occurs when you attempt to access the document object, which represents the web page's DOM, on the server side.

This error can be especially common when integrating third-party libraries or components that assume they are running in a browser environment, like rich text editors or other client-side JavaScript code.

To resolve this error and ensure your code runs smoothly in a Next.js application, follow these steps:

1. Dynamic Import: When you encounter the "document is not defined" error, consider using dynamic imports for the problematic code. Next.js provides a dynamic function that allows you to load components or modules asynchronously. By specifying { ssr: false }, you can prevent the code from being executed on the server side.

Here's an example of how to use dynamic imports to fix the error:

javascript
import dynamic from "next/dynamic";

const YourComponent = dynamic(() => import('your-component'), { ssr: false });

This ensures that the code is only executed in the browser, where the document object is defined.

2. Conditional Checks: Another approach is to include conditional checks in your code. This trick is universal for React. Before accessing the document object, ensure it is defined in a browser environment. You can use the following code snippet:

javascript
if (typeof window !== 'undefined') {
    // Your code that relies on the document object
}

This check ensures that the code runs on the client side, where document is available, and avoids execution on the server.

Happy Coding!

Found this useful?