Laravel: a rich text editor with server-side HTML sanitisation
A rich text field is the one place in a typical Laravel application where you deliberately accept HTML from a user and then show it to other people without escaping. That is why security is decided not by the editor in the browser but by what the server does with the content before saving it. Thi…
This post is also available in: Polski
A rich text field is the one place in a typical Laravel application where you deliberately accept HTML from a user and then show it to other people without escaping. That is why security is decided not by the editor in the browser but by what the server does with the content before saving it. This article shows where to put the sanitizer in your application, how it differs from validation and how to test that it works.
TL;DR
- The editor in the browser can be bypassed – the security boundary is the sanitizer on the server.
- Laravel validation checks that a field is present and of the right type; it does not remove dangerous elements.
VEditorService::sanitize()cleans HTML according to the same content model the editor uses.- Put classes from your theme in
stylesinconfig/veditor.php– then the editor and the sanitizer know the same ones. - Sanitise every entry point: the form, the API, imports, AI output.
Why the frontend is not a security boundary
The VEditor editor cleans content itself – a pasted fragment with <script> will not end up in the document. But that protects the editor user, not the application. An HTTP request with arbitrary HTML can be sent without the editor: from the browser's developer tools, with curl or through another endpoint that accepts the same field. The server then sees only a string in $request->input('content') and has no way of telling where it came from.
The sanitizer documentation puts it plainly: the security boundary is HtmlSanitizer on the server, and you should call it before every save. We look at this problem in more depth in Why filtering HTML in the browser is not enough.
The data model and HTML entry points
The simplest model is a single column of cleaned HTML, e.g. body in the articles table. You save the sanitizer's output, not the raw input – then every read, including through another view or an export, gets content that has passed the check.
Before you write your first controller, list every place through which HTML can reach that column:
- the edit form with the
@veditordirective, - an API endpoint through which a mobile app or another system updates content,
- imports from an old CMS, seeders and migration scripts,
- AI features – here the package does it for you: the
POST /veditor/aicontroller passes the same sanitizer (with yourstyles) to the AI handler, and the model's output is cleaned before the preview.
Every other place needs a sanitizer call. If you do not want to police this in each controller separately, you can put it in a model attribute mutator, so that every assignment to body goes through app(VEditorService::class)->sanitize().
Request validation versus content sanitisation
Validation and sanitisation answer different questions. Laravel validation rules say whether the request can be processed at all: the field is present, is a string, is not empty. The sanitizer changes the content – it removes elements, attributes and URLs the content model does not allow. No validation rule replaces the second operation, and the sanitizer does not replace the first.
The order in the controller: validation first, then sanitize(), and finally an optional check of the result. That last step makes sense because a document made up only of disallowed elements may be empty after cleaning, even though it passed the required rule.
Size is a separate matter. HtmlSanitizer throws a LengthException above maxLength – 1 MB by default. You have to catch the exception and turn it into a message next to the field (a controller example is in the article on integrating a WYSIWYG editor with Laravel). VEditorService::sanitizer() creates a sanitizer with the default limit; if you need a larger one, build it yourself:
use VEditor\HtmlSanitizer;
$sanitizer = (new HtmlSanitizer(maxLength: 2 * 1024 * 1024))
->allowStyles(config('veditor.styles'));
$clean = $sanitizer->sanitize($request->input('content'));
Invalid UTF-8 is cleaned before parsing, and large, deeply nested documents are processed in linear time, so the limit is there to control data size, not to defend against a slow parser.
One list of allowed elements
VEditor's sanitizer has no separate, hand-maintained list – it uses the same content model as the JavaScript editor: text blocks, lists, quotes, details, code blocks, tables, figure with an image, video or audio, and inline elements. Aliases are normalised (b → strong, div → p), and the allowed CSS properties are limited to a few, such as text-align or a width in percent.
In a Laravel application the only thing you usually adjust is the classes from your theme. You list them once, in config/veditor.php:
'styles' => [
['name' => 'Lead', 'element' => 'p', 'classes' => ['lead']],
['name' => 'Marker', 'element' => 'span', 'classes' => ['marker']],
],
The editor shows them in the “Style” list, and sanitize() calls allowStyles() with the same array. A class outside this list disappears on save – the most common cause of reports like “my style was lost after saving”. Class names must match ^[a-zA-Z][a-zA-Z0-9_-]{0,40}$, and styles can be assigned to block elements and span.
If you write your own editor plugin with a new element, the same element must be added to the sanitizer definitions (HtmlSanitizer::DEFAULT_ELEMENTS passed to the constructor). In Laravel this means your own HtmlSanitizer instance instead of VEditorService::sanitize().
Saving, reading and editing again
Valid content produced by the editor passes through the sanitizer byte for byte. Submitting a form turns \n into \r\n, but the sanitizer normalises line endings first, so the output matches editor.getContent(). As a result, a “save – reopen – save” cycle does not change the document and does not create false differences in the revision history.
When the article is reopened, the @veditor directive puts the saved HTML into the <textarea> with escaping, and the editor rebuilds the document from it. On the public page the content goes into {!! !!} – which is safe only because it was cleaned on save. The display context, content styles and forms with validation errors are described in the article on a WYSIWYG editor in Blade templates.
XSS and regression test scenarios
A unit test suite for the sanitizer is worth building from two groups. The first is attacks that must be neutralised:
| Input | Expected result |
|---|---|
<p>Text</p><script>alert(1)</script> | script removed together with its content |
<img src="x.png" onerror="alert(1)"> | onerror attribute removed |
<a href="javascript:alert(1)">link</a> | URL rejected – only http, https, mailto, tel and relative URLs are allowed |
<img src="data:…"> or a malicious srcset entry | URL rejected, each srcset entry checked separately |
<p id="login"> | identifier removed – only those with the ve- prefix are kept |
<a href="…" target="_blank"> | rel="noopener noreferrer" added |
<iframe src="https://example.com"> or youtube.com/embed/… | iframe removed; only a video from youtube-nocookie.com or Vimeo inside figure is kept |
a document larger than maxLength | LengthException |
The second group is regression: real editorial documents – with tables, task lists, captioned images and classes from styles – that must stay identical after sanitize(). The simplest approach is to save them as files in the test directory and compare the output with the original. When a regression test fails after a configuration change, you know straight away which class or element needs adding.
Where responsibility ends
The sanitizer protects rich text content and only that. It does not replace authentication and authorisation on save, protecting the AI endpoint with the auth middleware, secure handling of uploaded files or a CSP header that would block an injected script if something slipped through. Other data in templates – titles, author names, metadata – you still output with {{ }}.
A practical pre-launch checklist
- Every entry point (form, API, import) calls the sanitizer before saving.
- The database stores the output of
sanitize(), not the raw input. LengthExceptionis handled in the controller.- Classes from your theme are in
stylesand pass the regression test. - The tests from the table above pass in CI.
- Existing entries have been run through the sanitizer and compared with the original.
Where does VEditor fit in this process?
In VEditor the sanitizer is not an add-on bolted onto the editor. VEditor\HtmlSanitizer is a PHP class built on DOMDocument, with no external libraries, that applies the same allowlist of tags, attributes, classes and CSS properties as the JavaScript editor's schema. In the Laravel package you get it through VEditorService::sanitize() – already with your styles from the configuration. That does not exempt you from testing your application, but it removes the most common source of mismatches: two different lists of allowed HTML.
See VEditor features, the integration documentation and the editor demo.
Sanitisation on save is common to all VEditor integrations – alongside assets from your own server, CSRF, CSP and the AI endpoint. How it looks in Symfony, Yii2, plain PHP, React and Vue is shown in the guide to integrating a WYSIWYG editor with PHP and JavaScript.
FAQ
Does Laravel validation replace a sanitizer?
No. Validation rules check, for example, that a field is present and how long it is, but they do not remove dangerous elements or attributes from HTML. In the veditor/laravel package you pass content through VEditorService::sanitize() before saving; it uses VEditor\HtmlSanitizer, which throws a LengthException above the size limit (1 MB by default).
Can I save the HTML unchanged?
Valid content produced by the editor passes through the VEditor sanitizer unchanged, byte for byte. Only what the editor would not produce is removed, e.g. HTML sent by bypassing the editor. Saving input without sanitisation is not safe.
What should I do with existing entries?
Run existing content through HtmlSanitizer in a test script and compare the output with the original. Add the classes your theme relies on to styles in config/veditor.php – then the editor shows them in the “Style” list and the sanitizer keeps them.
How are links and iframes handled?
The VEditor sanitizer allows relative URLs and the http, https, mailto and tel protocols in links, and adds rel="noopener noreferrer" to links with target="_blank". An iframe is kept only as an embedded video in figure (YouTube via youtube-nocookie.com or Vimeo) and gets enforced sandbox and referrerpolicy attributes; any other iframe is removed.
Is sanitisation enough for complete XSS protection?
No. The sanitizer removes dangerous HTML from rich text content, but full protection also needs, among other things, escaping of other data in templates, CSP headers, permission checks and secure handling of uploaded files. Test the whole application before going to production.
Try VEditor in practice
The quickest way to check the sanitizer is on your own data: run a few real articles through it and compare the output with the original.