19

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.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
Libertas
  • 358
  • 2
  • 5
  • 11

3 Answers3

32

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

LeoDog896
  • 3,472
  • 1
  • 15
  • 40
Magnus
  • 598
  • 1
  • 5
  • 9
  • 1
    I note that `vite` still tries to make a "ssr bundle" when building that seems to build empty .js files... And I have not found a way to stop vite from doing that in order to speed up `vite build` – cassepipe Mar 07 '23 at 09:49
12

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.

mrkishi
  • 5,602
  • 1
  • 20
  • 18
1

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.

Monty
  • 361
  • 1
  • 3
  • 8