DEV Community

Abdullah Bashir
Abdullah Bashir

Posted on

3 1 1 1 1

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:

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

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:
     const { default: EditorJs } = ...
    
  • Destructuring Import:

     const Editor = ...
    const EditorJs = Editor.default
    

Here's the full solution:

<script>
import {onMount} from "svelte";
/**
* @type {EditorJS | null}
*/
let editor = $state(null);
/** @type {HTMLElement | null} */
let editorEl = null;
onMount(async () => {
try {
const {default: EditorJS} = await import('@editorjs/editorjs');
const {default: Header} = await import("@editorjs/header")
editor = new EditorJS({
holder: editorEl,
tools: {
header: {
class: Header,
inlineToolbar: ['link']
},
}
});
} catch (error) {
console.error("Failed to load EditorJS:", error);
}
});
let props = $props()
</script>
<div bind:this={editorEl} class="w-full h-full {props.class}"></div>
view raw Editorjs.svelte hosted with ❤ by GitHub

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.

Enterprise-level in-app dashboards. Startup-level speed.

Enterprise-level in-app dashboards. Startup-level speed.

Ship pixel-perfect dashboards that feel native to your app with Embeddable. It's fast, flexible, and built for devs.

Get early access

Top comments (0)

Feature flag article image

Create a feature flag in your IDE in 5 minutes with LaunchDarkly’s MCP server 🏁

How to create, evaluate, and modify flags from within your IDE or AI client using natural language with LaunchDarkly's new MCP server. Follow along with this tutorial for step by step instructions.

Read full post

👋 Kindness is contagious

Dive into this thoughtful piece, beloved in the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A sincere "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay