Olddevs UI4.14.0
Recipes

Server-side HTML sanitization: safe saving and display

sanitizeRichText with the same tools array on save, server-side code highlighting and RichTextView in a Next.js server component.

The Document comes from the client, and the client can't be trusted. The server sanitizes the HTML on save with the same rules as the Editor, and the page shows the already sanitized Document with a server RichTextView.

What the reader gets
Sanitized HTML

Try it

Edit the HTML on the left and watch the result on the right: <script>, onclick, style, javascript: and tags outside the Schema go away, the text stays, a Block with a disallowed tone loses the attribute, and code gets highlighted.

App code in Next.js

The example above sanitizes in the browser so you can see the result. In an app the server does the same:

app/articles/actions.ts
"use server";
import { JSDOM } from "jsdom";
import createDOMPurify from "dompurify";
import { sanitizeRichText } from "@olddevs/ui/editor/schema";
import { EDITOR_TOOLS } from "@/editor/tools"; // the same array as the Editor's `tools`

const DOMPurify = createDOMPurify(new JSDOM("").window);

export async function saveArticle(id: string, dirty: string) {
  await db.articles.update(id, { html: sanitizeRichText(dirty, DOMPurify, EDITOR_TOOLS) });
}
app/articles/[id]/page.tsx
import { RichTextView } from "@olddevs/ui/editor";
import { highlightCodeBlocks } from "@olddevs/ui/editor/highlight";
import { EDITOR_TOOLS } from "@/editor/tools";

// A server component: no directive needed, and no Tiptap goes to the browser.
export default async function ArticlePage({ params }: { params: Promise<{ id: string }> }) {
  const article = await db.articles.get((await params).id);
  return <RichTextView html={highlightCodeBlocks(article.html)} tools={EDITOR_TOOLS} />;
}

How it works

One tools array

The Editor, sanitizeRichText and the View receive the same array. Without the third argument sanitizeRichText strips custom Blocks.

The lightweight @olddevs/ui/editor/schema entry point

An entry point without Tiptap or React. If the Extensions (engine) of a custom Tool are supplied as a Loader, the Tool description is imported on the server without the engine: sanitization reads only the rules.

RichTextView doesn't sanitize HTML

RichTextView shows what was saved. Sanitize on save, not on display.

Highlighting on the server

highlightCodeBlocks highlights code blocks on the server — neither lowlight nor grammars go to the browser.

optimizePackageImports in Next.js

Add the @olddevs/ui/editor entry point to optimizePackageImports as a separate item, or the whole Editor ships to the browser with the View. For details, see “The package in server components”.

On this page