You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Investigate server-util package usage for Next.js SSR and other environments #942
@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
Reacted by Matthias Lübken, Nicholas Haley and Yegor Karimov
Reacted by Freeman, Ricardo Canelas, Gilbert Lam, linhtrinh18, v-rusu, Naoki Fujisawa, Sean Cullinan, Buniamin Shabanov, Yuriko Matsushita and Adam Tkaczyk
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
Reacted by Freeman, linhtrinh18, Moyez Rabbani, Sean Cullinan, Gemma, Kim Young Seok, Hector Muñoz, Xu Jingxin, Silver Ling, Buniamin Shabanov and 4 more
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
⨯ 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.
⨯ 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.
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.
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.
@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:)
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.
Put your schema into separate file, call it schema.ts. Add "use client" at top.
Duplicate it and call it schemaServer.ts, but don't include 'use client' at top.
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.
This is the key part, in your next.config.mjs add this:
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:
schema.ts: declares schema and exports it.
schemaClient.ts: "use client" at top and export * from './schema.ts';
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
Reacted by Graham Mueller, Adam Tkaczyk and Robert Molina
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.
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.
and here's an example of the server side code trying to extract markdown context from the YJS doc:
asyncfunctionconvertDocumentToMarkdown(content: string,editor: BlockNoteEditor): Promise<string>{awaitensureBlockNoteDOM();constydoc=newY.Doc();constupdate=decompressYDoc(content);Y.applyUpdate(ydoc,update);letmarkdown='';try{constblocks=yXmlFragmentToBlocks(editor,ydoc.getXmlFragment('prosemirror'));markdown=awaiteditor.blocksToMarkdownLossy(blocksasPartialBlock[]);}catch(conversionError){logger.warn('Failed to convert Y.Doc to markdown',{error: conversionError});markdown='';}returnmarkdown;}
So far, it's built successfully when I run next build and the conversion works when I start the server.
@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?
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:
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
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, unshimasyncfunctionwrapBlocknoteJSDOM<T>(cb: ()=>Promise<T>): Promise<T>{constoriginalWindow=globalThis.window;constoriginalDocument=globalThis.document;constoriginalHTMLElement=globalThis.HTMLElement;constoriginalNode=globalThis.Node;constoriginalNavigator=globalThis.navigator;try{constdom=newJSDOM('<!DOCTYPE html><html><body></body></html>');globalThis.window=dom.windowasany;globalThis.document=dom.window.documentasany;globalThis.HTMLElement=dom.window.HTMLElementasany;globalThis.Node=dom.window.Nodeasany;globalThis.navigator=dom.window.navigatorasany;returnawaitcb();}finally{globalThis.window=originalWindowasany;globalThis.document=originalDocumentasany;globalThis.HTMLElement=originalHTMLElementasany;globalThis.Node=originalNodeasany;globalThis.navigator=originalNavigatorasany;}}// Wrapping this function prevents any dom operations from being called before shimfunctioncreateEditorSchemaServer(){returnBlockNoteSchema.create();}asyncfunctionconvertMarkdownToBlocks(markdown: string){returnwrapBlocknoteJSDOM(async()=>{constschema=createEditorSchemaServer();consteditor=BlockNoteEditor.create({ schema });returnmarkdownToBlocks(markdown,editor.pmSchema);});}
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
Activity
leo-paz commentedon Aug 6, 2024
hey @YousefED sorry to bug but any updates on this?
still getting the error in my server action or
/api/route.ts:linhtrinh18 commentedon Aug 6, 2024
@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 }} />
);
};
Syammed2429 commentedon Aug 8, 2024
Yep, I'm also getting the same error as @linhtrinh18 , please help to fix it @YousefED and @matthewlipski
errorYousefED commentedon Aug 8, 2024
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-utilfrom 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
moyezr commentedon Oct 21, 2024
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-componentMy 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.
YousefED commentedon Oct 21, 2024
recommendation for now is to run a nodejs server
moyezr commentedon Oct 22, 2024
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 .
curiousyuvi commentedon Jan 4, 2025
I think I found a solution for this, instead of using
server-utilin api fromappfolder, use it in api frompagesfolder. I tried it withnext 14.2.1and 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
pagesandappfolder implementation in a single project, you can just create a seperatepagesapi to handle yourserver-util.MetaMmodern commentedon May 7, 2025
Getting same error as folks above. My usecase: I use
blocksToYXmlFragmentfor 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.MetaMmodern commentedon May 7, 2025
@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
/reactpackages, 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:)MetaMmodern commentedon Jul 8, 2025
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.
schema.ts. Add "use client" at top.schemaServer.ts, but don't include 'use client' at top.schemaServer.tsin your server-side in pages router, where you want to use ServerBlockNoteEditor, when passing "schema" as parameter. And use theschema.tsfile in the client side, where you have Editor.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:
The
undefinedhere 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:
schema.ts: declares schema and exports it.schemaClient.ts:"use client"at top andexport * from './schema.ts';schemaServer.ts: just one line ofexport * 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
ChromeGG commentedon Aug 11, 2025
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
1 remaining item
sportnak commentedon Nov 20, 2025
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.
sportnak commentedon Nov 24, 2025
Ok - me again, I figured out a work around. I removed my dependency on
@blocknote/server-utilentirely and instead used@blocknote/core. The code is in a separate folder marked withimport 'server-only'and creates a window shim with JSDOM.Here's the shim:
and here's an example of the server side code trying to extract markdown context from the YJS doc:
So far, it's built successfully when I run
next buildand the conversion works when I start the server.yantakus commentedon Nov 29, 2025
@sportnak but don't you need
@blocknote/server-utilto createconst editor = ServerBlockNoteEditor.create()to use yourconvertDocumentToMarkdown? Or you are using it at client side only as a react server action?sportnak commentedon Dec 1, 2025
So I'm using the client side
@blocknote/corepackage with the JSOM mock like so:This worked until I needed the custom schema, then I realized that in another file I was exporting
export const schema = BlockNoteSchema.createWhich happens outside of the dom shim. Instead I wrapped the schema in thecreateEditorschemaServerfunction I showed above. It looks like this: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
yantakus commentedon Dec 1, 2025
@sportnak Could you please share full code example? I still don't get how it works altogether.
sportnak commentedon Dec 1, 2025
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.
ahmednabik commentedon Jan 23, 2026
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
test: add Next.js App Router integration test for server-util (#942)
test: add Next.js integration test for server-util (#942) (#2555)