javascript / expert
Snippet
Defensive Isomorphic Design with Browser Checks
In Server-Side Rendering (SSR) environments, accessing browser-specific globals like 'window' or 'localStorage' outside of lifecycle hooks will cause server crashes. Using the '$app/environment' browser flag or 'onMount' ensures code is only executed in the appropriate context, maintaining isomorphic stability.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { browser } from '$app/environment';import { onMount } from 'svelte';let storageValue;// Expert Pattern: Prevent SSR crashesif (browser) {storageValue = localStorage.getItem('user_prefs');}onMount(() => {// Guaranteed to run only on clientconst width = window.innerWidth;console.log('Client-only logic:', width);});
svelte
Breakdown
1
import { browser }
SvelteKit-specific boolean that is true only when running in the user's browser.
2
if (browser) { ... }
Protects top-level script execution from referencing APIs that don't exist in Node.js.