SvelteKit: disable SSR

Viewed 3084

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 ran in browser. But because of that, my app is not working.

I'd be glad to get some help.

Thanks.

3 Answers

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.

The previous answer does no longer work because of changes in SvelteKit. See the PR for more information: https://github.com/sveltejs/kit/pull/6197 and also the documentation: https://kit.svelte.dev/docs/page-options

Basically now you disable SSR on a per page/layout level, so instead of in src/hooks.server.js (yes, hooks.js was also separated into client as server with the addition of client side hooks.)

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

You now do

    // src/routes/+layout.js
    export const ssr = false;

Make sure to put the line above in +layout.js and not +layout.svelte

You can also disable ssr in the svelte.config.js file. See svelte configuration to see the options. Set prerender enabled = false to disable prerendering altogether throughout the app.

Related