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

Justin Ahinon
Last updated on
Table of Contents
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. On subsequent requests, the components will be rendered in the browser using hydration. 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:
When we run this code, we get an internal server error displayed in the browser. And the following in the Node.js console:
How to fix the "document is not defined" error
They are a few ways to fix this error that you can use 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:
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.
Conclusion
That's it. I hope this article was helpful!