Skip to content

Investigate server-util package usage for Next.js SSR and other environments #942

Closed
1 of 1 issue completed

Description

@YousefED

@blocknote/server-util has been designed / tested for usage in node.js based environments.

However, some users want to use it in Next.js server side actions or Partykit functions (see #451). These functions probably run in different environments, so we'll need to investigate compatibility with this

Sub-issues

Sub-issues

1 of 1 Issues completed
Loading 1 sub-issues

Activity

  1. leo-paz commented on Aug 6, 2024

    @leo-paz

    hey @YousefED sorry to bug but any updates on this?

    still getting the error in my server action or /api/route.ts:

    createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component
    And it doesn't change if it's in an api route vs a server action
    
  2. linhtrinh18 commented on Aug 6, 2024

    @linhtrinh18

    @YousefED Same here, using nextjs 14 and the error pops up:

    Server Error
    Error: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component

    This error happened while generating the page. Any console logs will be displayed in the terminal window.

    import { ServerBlockNoteEditor } from "@blocknote/server-util";

    export const Introduction = async ({ text }: { text: any }) => {
    const editor = ServerBlockNoteEditor.create();
    const html = await editor.blocksToFullHTML(text);

    return (
    <div dangerouslySetInnerHTML={{ __html: html }} />
    );
    };

  3. Syammed2429 commented on Aug 8, 2024

    @Syammed2429

    Yep, I'm also getting the same error as @linhtrinh18 , please help to fix it @YousefED and @matthewlipski

    'use server'
    
    import { ServerBlockNoteEditor } from "@blocknote/server-util";
    
    export const blockToYDoc= async ( blocks: any ) => {
    const editor = ServerBlockNoteEditor.create();
    const blocksToYDocs = await editor.blocksToYDoc (blocks);
    
    return blocksToYDocs
    }

    error

    Error: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more:
    
  4. YousefED commented on Aug 8, 2024

    @YousefED
    CollaboratorAuthor

    I've done some further investigation into this. I want to split my findings into two parts:

    NextJS (SSR etc)
    Because BlockNote blocks are defined using React, we need to access certain react functionality on the server to call BlockNote APIs. For example, we need to render certain components to get their HTML version (for Blocks To HTML / Blocks To Markdown, etc). This is different than most React apps, because BlockNote uses React internally as a framework. However, next.js seems to block various React calls. This means certain React APIs are not available for BlockNote to use when evaluating calls like "Blocks to HTML". I tried some workarounds but could not find an easy way to call React APIs not affected / blocked by the Next bundler.

    It would be interesting to explore what a "next.js-first" architecture for BlockNote could look like (e.g.: with native support for SSR, etc). However, I think this would be several weeks of work at a minimum so it would require a corporate sponsor (I don't have a need for this feature myself at this moment).

    A workaround for now is to run a regular Node server somewhere and use server-util from there, and then expose an API.

    Non-node runtimes (bun, deno, etc)
    There also was a report that JSDom doesn't work in non-node environments like Bun (https://discord.com/channels/928190961455087667/1015169282444894219/1269960495264305153). I think this should be fixable by making the DOM shim pluggable, and make it possible to use something like happy-dom instead of jsdom. Would gladly accept any PRs for this / will consider adding this option if there are more requests for this coming in

  5. moyezr commented on Oct 21, 2024

    @moyezr

    Still kinda doesn't work with next.js api routes

    ⨯ createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component

    My use case: I am storing the contents of the editor in convex and in the server I want to retrieve them, parse them to blocks, and then using editor, parse them to markdown to generate vector embeddings for my AI application.

    Any help is highly appreciated.

  6. YousefED commented on Oct 21, 2024

    @YousefED
    CollaboratorAuthor

    Still kinda doesn't work with next.js api routes

    ⨯ createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component

    My use case: I am storing the contents of the editor in convex and in the server I want to retrieve them, parse them to blocks, and then using editor, parse them to markdown to generate vector embeddings for my AI application.

    Any help is highly appreciated.

    recommendation for now is to run a nodejs server

  7. moyezr commented on Oct 22, 2024

    @moyezr

    Alrighty.

    But I think it would be extremely useful if you could add server side compatibility with next.js as it's one of the most widely used frameworks.

    Anyways, kudos to your work @YousefED .

  8. curiousyuvi commented on Jan 4, 2025

    @curiousyuvi

    I think I found a solution for this, instead of using server-util in api from app folder, use it in api from pages folder. I tried it with next 14.2.1 and it works fine. I rendered some basic blocks (p,h1,ul,ol) and few of my custom blocks.

    Since nextjs allows you to have both pages and app folder implementation in a single project, you can just create a seperate pages api to handle your server-util.

  9. MetaMmodern commented on May 7, 2025

    @MetaMmodern

    Getting same error as folks above. My usecase: I use blocksToYXmlFragment for the first client that connects to a collaborative doc to retrieve blocks from database and then apply them to Y.Doc on server so that when client connects he immidiately syncs latest Yjs state with server. And I want to call that inside app server component(page.tsx) so that it happens right when user tries to access the page. I don't want to have a separate api call for this, it kills the purpose of SSR. Any hackaround would be fine by me(to somehow force nextjs to use this stuff). Or, if maybe this specific util doesn't require react context. I kinda don't understand why a util needs an editor to be created in the first place, looks like Java/OOP kinda kink.

  10. MetaMmodern commented on May 7, 2025

    @MetaMmodern

    @YousefED with the help of chatgpt I wrote this util for myself. It uses 2/3 methods from the original class. the only thing I was stuck with was pmSchema and chat suggested to use a headless BlockNoteEditor to obtain one, because client-side BlockNoteEditor is not importing anything from /react packages, so it doesn't trigger Nextjs blockage. So, I bet some of other utils can also be extracted this way. Of course you'll end up with half utils here half utils there, but you have more expretise in this to carry this on so I'm sure you'll figure out an elegant API for this:)

    import { prosemirrorToYXmlFragment } from "y-prosemirror";
    import {
      BlockSchema,
      blockToNode,
      InlineContentSchema,
      PartialBlock,
      StyleSchema,
    } from "@blocknote/core";
    import { BlockNoteEditor } from "@blocknote/core";
    
    import { XmlFragment } from "yjs";
    
    function _getPmSchema() {
      const pmSchema = BlockNoteEditor.create({
        // schema: mySchema,
        _headless: true,
      }).pmSchema;
    
      return pmSchema;
    }
    
    function _blocksToProsemirrorNode(
      blocks: PartialBlock<BlockSchema, InlineContentSchema, StyleSchema>[]
    ) {
      const pmSchema = _getPmSchema();
      const pmNodes = blocks.map((b) => blockToNode(b, pmSchema));
    
      const doc = pmSchema.topNodeType.create(
        null,
        pmSchema.nodes["blockGroup"].create(null, pmNodes)
      );
      return doc;
    }
    
    export function blocksToYXmlFragment(
      blocks: BlockSchema[],
      xmlFragment?: XmlFragment
    ) {
      return prosemirrorToYXmlFragment(
        _blocksToProsemirrorNode(blocks),
        xmlFragment
      );
    }
  11. MetaMmodern commented on Jul 8, 2025

    @MetaMmodern

    Previous approach started falling apart as soon as I tried using Custom Blocks. So, I started thinking of how can I force nextjs to allow usage of react APIs, so that I could use ServerEditor. and I found a way.

    1. Put your schema into separate file, call it schema.ts. Add "use client" at top.
    2. Duplicate it and call it schemaServer.ts, but don't include 'use client' at top.
    3. Use the schema from schemaServer.ts in your server-side in pages router, where you want to use ServerBlockNoteEditor, when passing "schema" as parameter. And use the schema.ts file in the client side, where you have Editor.
    4. This is the key part, in your next.config.mjs add this:
      serverExternalPackages: [
          "@blocknote/server-util",
          "@blocknote/react",
          "@blocknote/core",
        ],

    Docs on nextjs: https://nextjs.org/docs/app/api-reference/config/next-config-js/serverExternalPackages

    Why do you have to make duplicate schemas? I don't really know. All I know is that when I use a single one in both client and server, it gives me an error:

    TypeError: Cannot use 'in' operator to search for 'table' in undefined
    

    The undefined here means pmSchema afaik, so it fails to initiate schema if I do it like this.

    @YousefED this took couple of hours digging through your source codes different versions(and TipTaps code), I hope you give this a bit more attention and can pick it up from here. Last item to figure out is why it fails when using same schema file in both client and server.

    UPDATE:

    Thought you can optimize duplication by creating 3 files:

    1. schema.ts: declares schema and exports it.
    2. schemaClient.ts: "use client" at top and export * from './schema.ts';
    3. schemaServer.ts: just one line of export * from './schema.ts'
      Tested and yes, it works

    UPDATE 2:
    Yo, if anyone tries this, be aware, for some reason my server-side yjs stops receiving updates from time to time. can't say if my code does this or something else

  12. ChromeGG commented on Aug 11, 2025

    @ChromeGG

    Any progress here? I tried to create a dedicated NextJS API route for converting the json to HTML, but facing the same error on the server side :c

  13. 1 remaining item

  14. sportnak commented on Nov 20, 2025

    @sportnak

    Adding on to the above. With next.js - if you add

    serverExternalPackages: ['@blocknote/server-util', 'react', 'react-dom', '@blocknote/react', 'jsdom'],
    To your next.config.mjs file, it should work. I was running into an issue that wasn't manifesting locally, but when I deployed to vercel I was running into issues where createContext was still not available.

    And I'm back - the above is not ideal because it creates multiple instances of React in your server which I believe causes hydration issues etc.

  15. sportnak commented on Nov 24, 2025

    @sportnak

    Ok - me again, I figured out a work around. I removed my dependency on @blocknote/server-util entirely and instead used @blocknote/core. The code is in a separate folder marked with import 'server-only' and creates a window shim with JSDOM.

    Here's the shim:

    let initialized = false;
    
    export async function ensureBlockNoteDOM() {
      const { JSDOM } = await import('jsdom');
      if (initialized) return;
    
      const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>');
    
      globalThis.window = dom.window as any;
      globalThis.document = dom.window.document as any;
      globalThis.HTMLElement = dom.window.HTMLElement as any;
      globalThis.Node = dom.window.Node as any;
    
      initialized = true;
    }

    and here's an example of the server side code trying to extract markdown context from the YJS doc:

    async function convertDocumentToMarkdown(content: string, editor: BlockNoteEditor): Promise<string> {
      await ensureBlockNoteDOM();
      const ydoc = new Y.Doc();
      const update = decompressYDoc(content);
      Y.applyUpdate(ydoc, update);
    
      let markdown = '';
      try {
        const blocks = yXmlFragmentToBlocks(editor, ydoc.getXmlFragment('prosemirror'));
        markdown = await editor.blocksToMarkdownLossy(blocks as PartialBlock[]);
      } catch (conversionError) {
        logger.warn('Failed to convert Y.Doc to markdown', { error: conversionError });
        markdown = '';
      }
    
      return markdown;
    }

    So far, it's built successfully when I run next build and the conversion works when I start the server.

  16. yantakus commented on Nov 29, 2025

    @yantakus

    @sportnak but don't you need @blocknote/server-util to create const editor = ServerBlockNoteEditor.create() to use your convertDocumentToMarkdown? Or you are using it at client side only as a react server action?

  17. sportnak commented on Dec 1, 2025

    @sportnak

    So I'm using the client side @blocknote/core package with the JSOM mock like so:

      return wrapBlocknoteJSDOM(async () => {
        const schema = createEditorSchemaServer();
        const editor = BlockNoteEditor.create({
          schema,
        });
        const blocks = markdownToBlocks(newContent, editor.pmSchema);

    This worked until I needed the custom schema, then I realized that in another file I was exporting export const schema = BlockNoteSchema.create Which happens outside of the dom shim. Instead I wrapped the schema in the createEditorschemaServer function I showed above. It looks like this:

    export const createEditorSchemaServer = () => BlockNoteSchema.create({})

    Then the schema can use custom blocks which means I can convert all the markdown to the ydoc content I need to stream the updates to the client. Server utils was just actively trying to use the bundled version of react which was stripped of the necessary react functions cc @yantakus

  18. yantakus commented on Dec 1, 2025

    @yantakus

    @sportnak Could you please share full code example? I still don't get how it works altogether.

  19. sportnak commented on Dec 1, 2025

    @sportnak

    Sure @yantakus here's a full snippet. This let's me use a custom schema on the server side to convert markdown generated by an LLM into blocks that can be sent to the client. Should work the same for ydoc to markdown etc. To use custom schema blocks, you'll need to re-implement the block definitions with non-react implementations.

    import { BlockNoteSchema, BlockNoteEditor } from '@blocknote/core';
    import { blocksToYDoc } from '@blocknote/core/yjs';
    
    // shim, call, unshim
    async function wrapBlocknoteJSDOM<T>(cb: () => Promise<T>): Promise<T> {
      const originalWindow = globalThis.window;
      const originalDocument = globalThis.document;
      const originalHTMLElement = globalThis.HTMLElement;
      const originalNode = globalThis.Node;
      const originalNavigator = globalThis.navigator;
    
      try {
        const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>');
        globalThis.window = dom.window as any;
        globalThis.document = dom.window.document as any;
        globalThis.HTMLElement = dom.window.HTMLElement as any;
        globalThis.Node = dom.window.Node as any;
        globalThis.navigator = dom.window.navigator as any;
        return await cb();
      } finally {
        globalThis.window = originalWindow as any;
        globalThis.document = originalDocument as any;
        globalThis.HTMLElement = originalHTMLElement as any;
        globalThis.Node = originalNode as any;
        globalThis.navigator = originalNavigator as any;
      }
    }
    
    // Wrapping this function prevents any dom operations from being called before shim
    function createEditorSchemaServer() {
      return BlockNoteSchema.create();
    }
    
    async function convertMarkdownToBlocks(markdown: string) {
      return wrapBlocknoteJSDOM(async () => {
        const schema = createEditorSchemaServer();
        const editor = BlockNoteEditor.create({ schema });
        return markdownToBlocks(markdown, editor.pmSchema);
      });
    }
  20. ahmednabik commented on Jan 23, 2026

    @ahmednabik

    I ran into this exact issue while trying to use the server/util inside NextJS. Any plan to fix this soon? Running a seperate node server just to convert markdown into blocks is a PTA

  21. added
    needs-triage
    on Feb 3, 2026
  22. added
    bug:P2
    and removed
    needs-triage
    on Feb 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug:P2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions