How to fix the "document is not defined" error in SvelteKit

Justin Ahinon
Last updated on
One of the most common errors you will encounter while using SvelteKit is the `document is not defined ` error. This can be caused when you either try to access the `document` object inside a `script` tag or import a function that uses the `document` object. In this article, we will look at why this error occurs and how to fix it.
tl; dr : Use the `browser ` module from SvelteKit to check if you are in the browser or the server. Or use the `onMount ` lifecycle function from `svelte` to run code that uses the `document` object.
Why does the "document is not defined" error occur?
By default, SvelteKit will render your components on the server. The components will be rendered in the browser using hydration on subsequent requests. That means that at some point in the component lifecycle, particular browser-specific objects like document document will not be available .
So in this example, we are trying to access the document object inside a script tag:
code loading...
When we run this code, we get an internal server error displayed in the browser. And the following in the Node.js console:
code loading...
How to fix the "document is not defined" error
You can use a few ways to fix this error, depending on the situation.
Use SvelteKit browser module
SvelteKit provides a built-in module called browser that you can use to check the environment your code is running in, whether it's the browser or the server. Here is how you can use it to fix the "document is not defined" error:
code loading...
Here we are only executing the code that uses the document object if we are in the browser.
Use the onMount lifecycle function
Another way to fix the "document is not defined" error is to use the onMount lifecycle function from svelte . This function is called when the component is to the DOM. So you can use it to run code that uses the document object.
code loading...
Conclusion
That's it. I hope this article was helpful!