Skip to content

Server-side rendering

This library supports rendering an editor as an HTML string on a server and mounting the editor on the client. This has multiple advantages. Layout shifts can be completely avoided, and the editors will be visible before the JavaScript has been executed. This is the method used to render editors on this documentation website.

renderEditor() renders an editor with the specified RenderOptions as an HTML string.

The tokenizeCallback option can be used to modify the tokens before they’re stringified. If you’re using an extension that modifies tokens such as matchBrackets(), the same modifications should be done on the server to prevent the editor from flashing with incorrect tokens.

The overlays option accepts an array of functions that will be called with the current RenderOptions. Any HTML returned by them will be inserted inside the overlays element. This can be used to server render indentation guides for example.

The editors created from plain HTML are obviously not interactive. They must be mounted on the client using mountEditorsUnder(). This function mounts all editors under the specified root in document order. Editors that have already been mounted are skipped.

The second argument receives the options for an editor and returns the extensions that editor should be initialized with. This means you can add different extensions to editors with different options.

You can define extra properties for renderEditor() that will get stringified as JSON and later parsed by mountEditorsUnder(). This can be very useful for configuring which extensions to add. In the example below, we are adding a _pairs option to customize which characters are matched together by matchBrackets().

server.ts
client.ts

The editor below now matches < and > inside tags together. Try clicking on one of the tags.

Many of the examples shown on this page might seem abstract. This is because the SSR utilities are meant to be usable with many technologies. It’s your job to integrate this API with the server-side framework or static-site generator you’re using. Here’s a working example for astro.

There are markdown plugins for both rehype and marked that can create editors from fenced code blocks. These use renderEditor() under the hood. Read their documentation to learn more.