Next.js: 2 ways to fix the ‘document is not defined’ error

Updated: January 9, 2023 By: Frienzied Flame Post a comment

When working with Next.js, you might encounter the document is not defined error. This article will explain why this error happens, then walk you through a couple of different ways to get rid of it.

The Cause of the Error

Next.js supports both server-side rendering and client-side rendering.

The document object is only available on the client side. Therefore, if you accidentally use it in server-side pages or components, you will inevitably run into the document is not defined error:

Server Error
ReferenceError: document is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.

Screenshot:

Sometimes, the error does not originate from your code but from a third-party library that uses the document object.

Solutions

Now that we have discussed the reasons why you might get the error, let’s talk about how to fix it. What we have to do is to ensure that we only use the document object on the client side.

Adding a check

You will be safe by checking if the document object exists before using it, like so:

if(typeof document !== 'undefined') {
    // you are safe to use the "document" object here
    console.log(document.location.href);
}

Using the useEffect hook

The useEffect will make sure that you will never get the document is not defined error:

useEffect(() => {
    // you are safe to use the 'document' object here
    document.title = 'Sling Academy';
}, []);

Conclusion

In this article, we discussed the reasons why you might get the document is not defined error, as well as how to fix it. The solutions are quite short and simple. Good luck and happy coding!