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 CallThe "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
- Import the
browser
Variable: Import thebrowser
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>
- Use Conditional Statements: Wrap any code that uses the
window
object in a conditional statement that checks ifbrowser
istrue
.
<!-- +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
- Import the
onMount
Function: Import theonMount
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>
- Wrap Your Code in
onMount
: Place any code that uses thewindow
object inside theonMount
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:
- Use the browser variable: This checks if the code is running in the browser environment.
- Use the
onMount
lifecycle function: This ensures that code only runs after the component has been mounted in the browser.
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