Fixing the "Window Is Not Defined" Error in SvelteKit

Need help with Svelte?

Book a complimentary 15-minute call, and I'll analyze your code base and provide you with individualized feedback.

Schedule a Call

The "window is not defined" error in SvelteKit occurs because SvelteKit applications are server-side rendered (SSR) by default. During SSR, there is no window object because it only exists in the browser environment.

To fix this error, you can use one of two methods: checking for the browser variable or running your code in the onMount lifecycle hook.

Method 1: Using the browser Variable

  1. Import the browser Variable: Import the browser variable from $app/environment. This variable helps you check if the code is running in the browser environment.
<!-- +page.svelte -->
<script lang="ts">
  import { browser } from '$app/environment';
</script>
  1. Use Conditional Statements: Wrap any code that uses the window object in a conditional statement that checks if browser is true.
<!-- +page.svelte -->
<script lang="ts">
  import { browser } from '$app/environment';

  if (browser) {
    console.log(window.innerWidth);
  }
</script>

Why this works

The browser variable is a boolean that is true when the code is running in the browser and false during server-side rendering. By using this variable, you ensure that any code referencing window only runs in the appropriate environment.

Method 2: Using the onMount Lifecycle Function

  1. Import the onMount Function: Import the onMount function from Svelte. This function allows you to run code only after the component has been mounted in the browser.
<!-- +page.svelte -->
<script lang="ts">
  import { onMount } from 'svelte';
</script>
  1. Wrap Your Code in onMount: Place any code that uses the window object inside the onMount function.
<!-- +page.svelte -->
<script lang="ts">
  import { onMount } from 'svelte';

  onMount(() => {
    console.log(window.innerWidth);
  });
</script>

Why this works

The onMount function runs only in the client-side context, ensuring that any code inside it will not execute during server-side rendering. This is useful for operations that depend on browser-specific objects like window.

Summary

To fix the "window is not defined" error in SvelteKit, you can use either of the following methods:

That's it! Happy coding.

Need help with Svelte?

Book a complimentary 15-minute call, and I'll analyze your code base and provide you with individualized feedback.

Schedule a Call