How to Resolve the “document is not defined” Error
If you encounter the “ReferenceError: document is not defined” error in a Node.js or Next.js environment, there are steps you can take to resolve it.
The document
object is specific to browsers and is not accessible in server-side JavaScript environments. To learn more about the document
object, refer to the detailed DOM Document Object Model guide.
In the case of Node.js, there is no direct workaround for this issue. It is essential to identify the specific section of code where the document
object is being accessed and investigate why it is being used in a server-side context.
When working with Next.js, you can address this problem by wrapping the relevant code in a conditional statement. The code may be executed in both frontend and server-side scenarios. For instance, when navigating to a page using a link, it runs on the frontend. On the server-side, code may be executed by using getServerSideProps()
.
To handle this, limit references to the document
object within a conditional statement that checks for the availability of the window
object. Here is an example:
1 | if (typeof window !== 'undefined') { |
By implementing this approach, you ensure that the code within the conditional statement runs exclusively in a browser environment.
tags: [“Node.js”, “Next.js”, “DOM”, “server-side JavaScript”, “document object”, “frontend”, “backend”, “conditional statement”]