Digital Dreamer
Writing /
Read on dev.to

Make EditorJS work in Svelte(kit) SSR

If you're here, you've probably been having issues using EditorJs in Sveltekit (like me). Since SSR isn't supported in EditorJs, you might encounter errors like 'Element is not defined'. Here's how to solve it.

Make EditorJS work in Svelte(kit) SSR

If you're here, you've probably been having issues using EditorJs in Sveltekit (like me). Since SSR isn't supported in EditorJs (see discussion), you might encounter errors like this:

text
[vite] Error when evaluating SSR module /src/routes/+page.svelte: failed to import "@editorjs/editorjs" |- ReferenceError: Element is not defined

Here's how I solved it:

  1. Load Editor Asynchronously: Ensure the editor loads only on the client side using onMount to avoid SSR complications.
  2. Element Initialization: Bind elements properly and handle initialization using onMount to ensure the element is available after component setup.
  3. Be Sure To Import EditorJs Correctly (since it's a default export):

Default Import:

javascript
const { default: EditorJs } = await import('@editorjs/editorjs');

Destructuring Import:

javascript
const Editor = await import('@editorjs/editorjs');
const EditorJs = Editor.default;

Here's the full solution:

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

  let editor;

  onMount(async () => {
    const { default: EditorJS } = await import('@editorjs/editorjs');
    const { default: Header } = await import('@editorjs/header');
    const { default: List } = await import('@editorjs/list');

    editor = new EditorJS({
      holder: 'editorjs',
      tools: {
        header: Header,
        list: List,
      },
      data: {} // your data here
    });
  });
</script>

<div id="editorjs"></div>

Happy Hacking!

PS: If you're using Svelte 4, remember to change the Svelte-5-specific syntax. I'd advise you to switch as soon as possible tho.