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')
});
}
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');
}, []);
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');
});
}
Top comments (5)
What about 3rd-party libs and hooks, I am using @fusionauth/react-sdk in my app and it seems that these solution ain't gonna work since I need to call
useFusionAuth
inside my pages (inside app directory). Any suggestion?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...
In my case it is used in a dependency and I'm not quite sure how to go about fixing it
use patch?
I am wondering if Solution 1 will negatively effect my loading time of the website?!