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

Justin Ahinon
Last updated on
Table of Contents
Get this article emailed to you .
While working with SvelteKit, you may encounter the "window is not defined" error. This issue arises when attempting to access the
window
object in a script tag or importing a function that utilizes the
window
object.
This post explores the reasons behind this error and how to address it.
tl; dr
: Utilize SvelteKit's
browser
browser
module to check if you are in the browser or the server. Alternatively, use Svelte's onMount
onMount
lifecycle function to run code involving the window object.
Why do we encounter the "window is not defined" error?
In SvelteKit, components are initially rendered server-side by default. Once this server-side rendering is done, the components are hydrated in the browser. During the component's lifecycle, there will be instances when certain browser-specific objects, such as
window
, are not accessible.
For example, when attempting to access the
window
object within a script tag:
Executing this code results in an internal server error being displayed in the browser, while the Node.js console shows:
Resolving the "window is not defined" error
Depending on your specific use case, there are several ways to address this error.
Utilize the SvelteKit browser module
SvelteKit offers a built-in module called
browser
that can be used to determine whether your code is executing in a browser or server environment. You can use it to resolve the "window is not defined" error as follows:
In this example, we only execute the code that utilizes the
window
object when we are in a browser environment.
Employ the onMount lifecycle function
Another approach to resolving the "window is not defined" error is to use Svelte's
onMount
lifecycle function. This function is called when a component is added to the DOM, making it ideal for running code that depends on the
window
object.
By using these methods, you can successfully overcome the "window is not defined" error in SvelteKit.
Wrapping Up
In summary, the "window is not defined" error in SvelteKit can be effectively resolved by using either the SvelteKit
browser
module or Svelte's
onMount
lifecycle function. These techniques ensure that your code only accesses the
window
object when running in a browser environment, avoiding errors and providing a smooth development experience.