ReferenceError: document is not defined in Svelte 3

Sapper works well with most third-party libraries you are likely to come across. However, sometimes, a third-party library comes bundled in a way which allows it to work with multiple different module loaders. Sometimes, this code creates a dependency on window, such as checking for the existence of window.global might do.

Since there is no window in a server-side environment like Sapper's, the action of simply importing such a module can cause the import to fail, and terminate the Sapper's server with an error such as:

ReferenceError: window is not defined

The way to get around this is to use a dynamic import for your component, from within the onMount function (which is only called on the client), so that your import code is never called on the server.

<script>
    import { onMount } from 'svelte';

    let MyComponent;

    onMount(async () => {
        const module = await import('my-non-ssr-component');
        MyComponent = module.default;
    });
</script>

<svelte:component this={MyComponent} foo="bar"/>

document is not defined on the server, so you need to guard against that in your component so that particular piece of code is only run in the browser.

You can use the onMount function which is only run in the browser when the component has been rendered.

<script>
  import { onMount } from 'svelte';

  onMount(() => {
    document.createElement(...);

    // ...
  });
</script>

Tags:

Svelte