How to fix the "document is not defined" error in SvelteKit
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
will not be available
So in this example, we are trying to access the
object inside a
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.
SvelteKit provides a built-in module called
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
object if we are in the browser.
Another way to fix the "document is not defined" error is to use the
lifecycle function from
. This function is called when the component is to the DOM. So you can use it to run code that uses the
That's it. I hope this article was helpful!