How to Handle SSR in SvelteKit: Fixes and Best Practices
SvelteKit, SSR runs your code on the server before sending HTML to the browser. To handle SSR correctly, avoid using browser-only APIs like window or document directly in your components; instead, check if the code runs on the client using browser from $app/environment. Use load functions for data fetching to keep SSR smooth and error-free.Why This Happens
SSR in SvelteKit runs your code on the server, where browser-specific objects like window or document do not exist. If you try to use them directly in your components, it causes errors because the server environment can't find these objects.
<script> import { onMount } from 'svelte'; export let name; // This will break SSR because window is not defined on the server console.log(window.location.href); onMount(() => { console.log('Component mounted'); }); </script> <h1>Hello {name}</h1>
The Fix
Use the browser variable from $app/environment to check if the code runs in the browser before accessing browser-only APIs. Also, use onMount to run code only on the client side after the component loads. For data fetching, use load functions to keep SSR safe and efficient.
<script> import { browser } from '$app/environment'; import { onMount } from 'svelte'; export let name; if (browser) { console.log(window.location.href); // Safe to use in browser only } onMount(() => { console.log('Component mounted'); }); </script> <h1>Hello {name}</h1>
Prevention
Always separate server and client code by using browser checks or onMount. Avoid direct use of browser globals in component top-level code. Use load functions for fetching data during SSR. Enable linting rules that warn about browser-only APIs in server code to catch issues early.
Related Errors
Common related errors include ReferenceError: document is not defined and hydration mismatches caused by rendering different content on server and client. Fix these by using browser checks and ensuring consistent rendering output.
Key Takeaways
browser variable to detect client environment before accessing browser APIs.onMount to avoid SSR errors.load functions to keep SSR smooth and safe.window or document directly in component top-level code.