🔥 Join our free  SvelteKit Workshop on June 28 - only 9 seats remaining ! 💨 Save Your Spot!

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

Justin's profile pic

Justin Ahinon

Last updated on

Table of Contents

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

    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:

    SVELTE

    When we run this code, we get an internal server error displayed in the browser. And the following in the Node.js console:

    BASH

    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:

    SVELTE

    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.

    SVELTE

    Conclusion

    That's it. I hope this article was helpful!

    You might also like these blog posts

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

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

    Overcome the "window is not defined" error in SvelteKit with ease! Learn effective solutions like using the SvelteKit browser module and onMount lifecycle function.

    Mastering Client-Side Authentication with Firebase and SvelteKit

    Mastering Client-Side Authentication with Firebase and SvelteKit

    Mastering Client-Side Authentication with Firebase and SvelteKit