DEV Community

Cover image for Fixing Next js "ReferenceError: document is not defined"
Luteya Coulston
Luteya Coulston

Posted on • Updated on

Fixing Next js "ReferenceError: document is not defined"

I came across this error while learning next js and I couldn't understand what I did wrong. The error is thrown because document is only available inside the browser and not on the server. Next js executes this code on the server side and that's why the error is thrown.
In this tutorial I'll show you three ways on how to solve this issue.
Solution 1:
Since the window is part of the browser, we can wrap our code inside an if statement. If you check on the console the type of window it returns object. The following code illustrates this:

if (typeof window === 'object') {
// Check if document is finally loaded
   document.addEventListener("DOMContentLoaded", function () {
       alert('Finished loading')
     });
  }
Enter fullscreen mode Exit fullscreen mode

Solution 2:
Since nextjs uses reactjs we can use the useEffect hook which checks if component has mounted or updated. Here is an example.

import {useEffect} from "react";

useEffect(() => {
    alert('Finished loading');
  }, []);
Enter fullscreen mode Exit fullscreen mode

Note that I passed [] as a second argument, this is because useEffect watches what has changed which in this case I just want to check if the document has completed loading. If you don't pass it it will keep executing let's say we you click on an internal link it will keep alerting. Check documentation

Solution 3:
I read that this is a deprecated method but I just decided to add this in case you come across it somewhere. I'll be using the process.browser method

if (process.browser) {
    document.addEventListener("DOMContentLoaded", function () {
       alert('Finished loading');
     });
   }
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
__ec73256df profile image
Виктор Щелочков

What if I have no scripts with document object? I searched through my entire project, but it seems document object is used by dependencies or NextScript...

Collapse
 
ch1zo profile image
chizo nwazuo

In my case it is used in a dependency and I'm not quite sure how to go about fixing it

Collapse
 
__ec73256df profile image
Виктор Щелочков

use patch?

Collapse
 
alinanerlichdev profile image
AlinaNerlich-dev

I am wondering if Solution 1 will negatively effect my loading time of the website?!