How to Load, Save and Display Rich Text in Next.js 16 With Froala
Posted on By Mostafa Yousef | Last updated on | In Tutorials,
Table of contents
- Key Takeaways
- Prerequisites
- Step 1. Create a Next.js 16 App
- Step 2. Install the Froala Packages
- Step 3. Understand Why the Editor Must Run in the Browser
- Step 4. Create the Client-Only Editor Component
- Step 5. Load the Editor With next/dynamic
- Step 6. Render the Editor From a Server Page
- Step 7. Store and Display the Content
- Step 8. Save Edits With a Server Action
- Step 9. Customize the Editor
- Common Pitfalls
- Use Froala Skills With Your AI Coding Agent
- Conclusion
- Try It Yourself
- FAQ
- Can I use Froala in a Server Component?
- Does this work with the Pages Router?
- Where should I put my license key?
Getting a rich text editor to load in Next.js is only the first step. You also need to save what people write and publish it without exposing your site to harmful HTML. This guide builds that full loop in a Next.js 16 App Router app: Froala loads only in the browser, a Server Action cleans and stores the HTML, and a server-rendered page displays it.
Key Takeaways
- Froala needs a browser, so in Next.js it must load only on the client.
- Put the editor in a client component, and load it with
next/dynamicandssr: falsefrom a second client component. - Pages import that loader component, never the editor file.
- Keep plugins, custom buttons and languages in the editor file.
- Sanitize HTML on the server before you save it and before you display it.
Prerequisites
- Node.js 20.9 or later, the minimum for Next.js 16.
- Basic React knowledge (state and props).
- A Froala key. Use the public trial key while testing and your commercial key in production.
Step 1. Create a Next.js 16 App
npx create-next-app@latest my-editor-app
cd my-editor-app
Accept the recommended defaults. Check that next.config.ts contains cacheComponents: true, which Step 7 uses. Here is where each file goes:
app/
editor/
FroalaClient.tsx <- the editor (browser only)
Editor.tsx <- the loader
page.tsx <- the editor page (server)
actions.ts <- the save action (Step 8)
post/
page.tsx <- read-only page (Step 7)
lib/
sanitize.ts <- HTML cleaning (Step 7)
store.ts <- demo storage (Step 7)
Step 2. Install the Froala Packages
npm install --save-exact froala-editor@5.6.0 react-froala-wysiwyg@5.6.0 Step 3. Understand Why the Editor Must Run in the Browser
Client Components, even with 'use client', render once on the server before running in the browser. Froala needs real page elements that only exist in a browser, so that server render crashes. The fix is to skip the editor on the server: the page arrives with a placeholder, and the browser swaps in the editor.
Step 4. Create the Client-Only Editor Component
Add your key to .env.local in the project root:
NEXT_PUBLIC_FROALA_KEY=TRIAL-LICENSE-KEY-FOR-FROALA-NOT-FOR-PRODUCTION-USE
That’s Froala’s public 30-day trial key; use your commercial key in production. The NEXT_PUBLIC_ prefix exposes the value to the browser, where the editor reads it.
Create app/editor/FroalaClient.tsx:
'use client';
import { useState } from 'react';
import { useFormStatus } from 'react-dom';
import FroalaEditorComponent, { type FroalaEditorConfig } from 'react-froala-wysiwyg';
import 'froala-editor/css/froala_editor.pkgd.min.css';
import 'froala-editor/css/froala_style.min.css';
import 'froala-editor/js/plugins.pkgd.min.js';
const config: FroalaEditorConfig = {
key: process.env.NEXT_PUBLIC_FROALA_KEY,
placeholderText: 'Start writing...',
heightMin: 300,
htmlExecuteScripts: false,
};
type FroalaClientProps = {
initialHtml?: string;
action?: (formData: FormData) => Promise<void>;
};
export default function FroalaClient({ initialHtml = '', action }: FroalaClientProps) {
const [html, setHtml] = useState(initialHtml);
return (
<>
<FroalaEditorComponent
tag="textarea"
model={html}
onModelChange={setHtml}
config={config}
/>
{action && (
// The hidden input carries the editor's HTML to the Server Action.
<form action={action} style={{ marginTop: '1rem' }}>
<input type="hidden" name="content" value={html} />
<SaveButton />
</form>
)}
</>
);
}
// Shows "Saving..." and blocks double clicks while the Server Action runs.
function SaveButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? 'Saving...' : 'Save'}
</button>
);
}
- The imports. The wrapper doesn’t load Froala’s CSS or plugins. Step 9 slims them down.
configoutside the component. The editor reads it once, at startup.htmlExecuteScripts: false. The default istrue, which lets<script>tags in content run.- The Save form. It appears once a page passes an
action(Step 8).
Step 5. Load the Editor With next/dynamic
Create app/editor/Editor.tsx:
'use client';
import dynamic from 'next/dynamic';
// Load the editor in the browser only. The server renders the placeholder instead.
const Editor = dynamic(() => import('./FroalaClient'), {
ssr: false,
loading: () => (
// Roughly the editor's height (toolbar + heightMin), so the page doesn't jump.
<div style={{ minHeight: 360, border: '1px solid #ccc', padding: '1rem' }}>
Loading editor...
</div>
),
});
export default Editor;
ssr: false is only allowed in Client Components, which is why this loader exists.
Step 6. Render the Editor From a Server Page
Create app/editor/page.tsx. It imports Editor, never FroalaClient:
import type { Metadata } from 'next';
import Editor from './Editor';
export const metadata: Metadata = { title: 'Write a post' };
export default function EditorPage() {
// Runs on the server. Step 8 replaces this with content from storage.
const initialHtml = '<h2>Hello from the server</h2><p>Start editing this text.</p>';
return (
<main style={{ maxWidth: 800, margin: '2rem auto', padding: '0 1rem' }}>
<h1>Write a post</h1>
<Editor initialHtml={initialHtml} />
</main>
);
}
Run npm run dev and open http://localhost:3000/editor. The placeholder appears, then the editor.
Step 7. Store and Display the Content
Browser HTML is user input, so the server cleans it before storing and before showing it:
npm install sanitize-html server-only
npm install -D @types/sanitize-html
Create lib/sanitize.ts, an allow-list:
import 'server-only';
import sanitizeHtml from 'sanitize-html';
// Matches what the editor can produce: standard text tags, images and a few safe styles.
const options: sanitizeHtml.IOptions = {
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img']),
allowedAttributes: {
a: ['href', 'target', 'rel'],
img: ['src', 'alt', 'width', 'height', 'style'],
'*': ['style', 'class'],
},
// Keep only Froala's own classes, such as fr-fic or fr-dib on images.
allowedClasses: { '*': ['fr-*'] },
// Keep only the inline styles the toolbar creates, with safe values.
allowedStyles: {
'*': {
'text-align': [/^(left|right|center|justify)$/],
color: [/^#[0-9a-f]{3,8}$/i, /^rgba?\([\d\s.,%]+\)$/],
'background-color': [/^#[0-9a-f]{3,8}$/i, /^rgba?\([\d\s.,%]+\)$/],
'font-size': [/^\d+(\.\d+)?(px|em|rem|pt|%)$/],
'font-family': [/^[a-z0-9\s,'"-]+$/i],
'line-height': [/^\d+(\.\d+)?(px|em|%)?$/],
width: [/^\d+(\.\d+)?(px|%)$/],
height: [/^\d+(\.\d+)?(px|%)$/],
margin: [/^auto$/], // centered tables
},
},
// Links may only point to web pages or email addresses. No javascript: URLs.
allowedSchemes: ['http', 'https', 'mailto'],
allowedSchemesByTag: { img: ['http', 'https'] },
};
export function sanitizeEditorHtml(dirty: string): string {
return sanitizeHtml(dirty, options);
}
server-only keeps this file out of browser code. If a toolbar feature writes a new inline style, add it to allowedStyles.
Create lib/store.ts, demo storage to swap for your database:
import 'server-only';
import { cacheTag } from 'next/cache';
// Demo storage that lives in server memory and resets on restart.
// Replace the body of these two functions with calls to your database.
let savedHtml = '<h2>Hello from the server</h2><p>Edit this text and click <strong>Save</strong>.</p>';
export async function getPostHtml(): Promise<string> {
'use cache';
cacheTag('post'); // lets a Server Action refresh every page that shows this post
return savedHtml;
}
export async function savePostHtml(html: string): Promise<void> {
savedHtml = html;
}
Create app/post/page.tsx, the read-only page:
import type { Metadata } from 'next';
import { cacheTag } from 'next/cache';
import { getPostHtml } from '@/lib/store';
import { sanitizeEditorHtml } from '@/lib/sanitize';
// Only the content stylesheet. No editor JavaScript is sent to this page.
import 'froala-editor/css/froala_style.min.css';
export const metadata: Metadata = { title: 'Post' };
// Clean the HTML and cache the result until the post changes.
async function getSafePostHtml(): Promise<string> {
'use cache';
cacheTag('post');
return sanitizeEditorHtml(await getPostHtml());
}
export default async function PostPage() {
const html = await getSafePostHtml();
return (
<main style={{ maxWidth: 800, margin: '2rem auto', padding: '0 1rem' }}>
<article className="fr-view" dangerouslySetInnerHTML={{ __html: html }} />
</main>
);
}
Readers get server-rendered HTML styled by fr-view, with no editor JavaScript. Open /post to see the starting content.
Step 8. Save Edits With a Server Action
Create app/editor/actions.ts:
'use server';
import { updateTag } from 'next/cache';
import { redirect } from 'next/navigation';
import { sanitizeEditorHtml } from '@/lib/sanitize';
import { savePostHtml } from '@/lib/store';
export async function savePost(formData: FormData): Promise<void> {
// In a real app, check here that the user is signed in and allowed to edit.
const content = formData.get('content');
if (typeof content !== 'string') {
throw new Error('No content was sent.');
}
// Never trust HTML from the browser. Clean it before it is stored.
await savePostHtml(sanitizeEditorHtml(content));
// Expire the cached post so the next page shows the new version, then go there.
updateTag('post');
redirect('/post');
}
Then update app/editor/page.tsx to load saved content and pass the action:
import type { Metadata } from 'next';
import Editor from './Editor';
import { savePost } from './actions';
import { getPostHtml } from '@/lib/store';
export const metadata: Metadata = { title: 'Write a post' };
export default async function EditorPage() {
// Runs on the server. Loads saved content before the page is sent.
const initialHtml = await getPostHtml();
return (
<main style={{ maxWidth: 800, margin: '2rem auto', padding: '0 1rem' }}>
<h1>Write a post</h1>
<Editor initialHtml={initialHtml} action={savePost} />
</main>
);
}
Open /editor, edit and click Save. You land on /post with the cleaned content.
Step 9. Customize the Editor
Customizations go in FroalaClient.tsx, so they run only in the browser. Replace the .pkgd imports to load only the plugins you use, add a custom button and a language:
import FroalaEditor from 'froala-editor';
// Core styles plus only the plugins you use. Table ships its own CSS.
import 'froala-editor/css/froala_editor.min.css';
import 'froala-editor/css/froala_style.min.css';
import 'froala-editor/js/plugins/lists.min.js';
import 'froala-editor/js/plugins/table.min.js';
import 'froala-editor/css/plugins/table.min.css';
import 'froala-editor/js/languages/de.js';
// Registered once, when this file loads in the browser.
FroalaEditor.DefineIcon('insertToday', { NAME: 'plus', SVG_KEY: 'add' });
FroalaEditor.RegisterCommand('insertToday', {
title: "Insert today's date",
focus: true,
undo: true,
refreshAfterCallback: true,
callback() {
this.html.insert(new Date().toLocaleDateString());
},
});
Rename config to baseConfig and list the toolbar buttons, including the new one:
const baseConfig: FroalaEditorConfig = {
key: process.env.NEXT_PUBLIC_FROALA_KEY,
heightMin: 300,
htmlExecuteScripts: false,
toolbarButtons: {
moreText: { buttons: ['bold', 'italic', 'underline'] },
moreParagraph: { buttons: ['formatUL', 'formatOL'] },
moreRich: { buttons: ['insertTable', 'insertToday'] },
moreMisc: { buttons: ['undo', 'redo'], align: 'right' },
},
};
To change options after startup, such as the language, give the editor a key that changes with them. Import useMemo and useRef, then inside the component:
const [language, setLanguage] = useState<'en' | 'de'>('en');
const config = useMemo<FroalaEditorConfig>(() => ({ ...baseConfig, language }), [language]);
const editorRef = useRef<FroalaEditorComponent>(null);
<FroalaEditorComponent
key={language} // a new key restarts the editor with the new config
ref={editorRef} // editorRef.current?.getEditor() returns the editor instance
tag="textarea"
model={html}
onModelChange={setHtml}
config={config}
skipReset // keep Undo working when you load new content from outside
/>
A new key restarts the editor, and the content survives in html state. Call setLanguage('de') from a button to switch.
Common Pitfalls
ReferenceError: Element is not definedduringnext build. A page importedFroalaClientdirectly. ImportEditorinstead.- “
ssr: falseis not allowed withnext/dynamicin Server Components.” Move the dynamic import into the'use client'loader. - “Next.js encountered the unstable value
Math.random()while prerendering.”sanitize-htmlran directly in a page render. Call it inside a'use cache'function, as in Step 7. - Two copies of
froala-editor. Pin both packages to the same version. - Images disappear after saving. Without
imageUploadURL, uploads get a temporaryblob:address that the sanitizer removes. SetimageUploadURLto an endpoint that stores files. - Lists and headings look unstyled. Tailwind’s reset removes them. Add this to
app/globals.css:
.fr-view ul { list-style: disc; padding-left: 1.5rem; }
.fr-view ol { list-style: decimal; padding-left: 1.5rem; }
.fr-view h1 { font-size: 2em; font-weight: 700; }
.fr-view h2 { font-size: 1.5em; font-weight: 700; }
.fr-view h3 { font-size: 1.25em; font-weight: 700; }
.fr-view p { margin-bottom: 1em; }
Use Froala Skills With Your AI Coding Agent
If you build with an AI coding agent such as Claude Code, Cursor or GitHub Copilot, add Froala’s Agent Skills to your project. They give the agent structured, version-checked knowledge of Froala, including setup for Next.js and the React wrapper, events, custom buttons and plugins, and error diagnosis. The agent then writes code against Froala’s real API instead of guessing.
npx skills add froala/froala-skills
The command detects the agents you have installed and adds the skills to each one. It needs Node.js 22.20 or later. The skills load automatically when your code or question involves Froala. See the froala-skills repository on GitHub for other install options and the full list of skills.
Conclusion
The pattern is three files: FroalaClient.tsx holds the browser-only code, Editor.tsx loads it with ssr: false, and server pages import Editor. See the Froala React docs page for every option.
Try It Yourself
Fork the Froala Next.js demo to run the finished project.
FAQ
Can I use Froala in a Server Component?
No. Load and display content in Server Components, and keep the editor in a client-only file.
Does this work with the Pages Router?
Yes. Call dynamic(() => import('./FroalaClient'), { ssr: false }) directly in the page file. No loader file is needed.
Where should I put my license key?
In .env.local as NEXT_PUBLIC_FROALA_KEY, and in your hosting provider’s settings for production.
- Whats on this page hide
No comment yet, add your voice below!