server-side-renderingsveltesveltekit

SvelteKit: disable SSR


I made an app in Svelte and now I wanted to port it to SvelteKit. My app uses window and document objects, but those aren't available in SSR. Firstly, it threw ReferenceError: window is not defined, but I fixed that by checking if the app is running in the browser. But because of that, my app is not working.


Solution

  • You can disable server-side rendering from your handle hook, defined in src/hooks.js:

    export async function handle({ event, resolve }) {
        return resolve(event, { ssr: false });
    }
    

    It's even possible to do it conditionally, usually by inspecting event and making your decision per-request.


    If your use-case requires everything to happen client-side anyway, disabling SSR makes sense. But do note that disabling it strictly because of some browser-only code is not recommended — in that case, it's usually better to execute code conditionally with browser checks and dynamic imports for client-side only dependencies. I'd explore why your app stopped working before jumping to disabling SSR.