How to integrate OpenAI with a WYSIWYG editor?

To integrate OpenAI with a WYSIWYG editor, you need an endpoint on your own server that accepts an action name and text from the editor, checks permissions, adds the API key and sends a cleaned result back to the preview. The OpenAI key never reaches the browser, and you treat the model’s respons…

This post is also available in: Polski

To integrate OpenAI with a WYSIWYG editor, you need an endpoint on your own server that accepts an action name and text from the editor, checks permissions, adds the API key and sends a cleaned result back to the preview. The OpenAI key never reaches the browser, and you treat the model’s response as untrusted HTML. Everything else – streaming, error handling and limits – you design around this one endpoint.

TL;DR

  • The browser talks only to your endpoint; the endpoint talks to OpenAI. You keep the API key in an environment variable on the server.
  • The endpoint must check login, edit permission, the CSRF token, the request size and the allowed features – before it spends a single token.
  • Streamed responses (text/event-stream) require buffering to be disabled in nginx, Apache, the CDN and PHP.
  • HTML returned by the model goes through the same sanitizer as ordinary content, and only then reaches the preview.
  • In VEditor, the AI endpoint comes ready-made in the Laravel, Symfony and Yii2 integrations, and in plain PHP it is a single file; OpenAI is the default provider.

The architecture in one sentence and one diagram

The editor sends an action → the server verifies and enriches the request → OpenAI generates a response → the server cleans the result → the editor shows a preview. Every arrow is a place where something can go wrong, so it is worth spelling out which party is responsible for what.

LayerResponsible forShould not
Editor (browser)selection, choice of action, result preview, decision buttonsknow the API key or the contents of the prompts
Endpoint (your server)authentication, CSRF, limits, building the instruction, calling the API, sanitizationsave the document automatically
OpenAIgenerating the responsereceive more data than the action requires
CMSsaving and publishing after the editor’s decisiontreat the AI result as approved

A key in browser code is public – the developer tools are all it takes to copy it. The endpoint protects the secret and is the only place where you can enforce limits and permissions.

Step 1: the API key and server configuration

You generate the OpenAI key in the provider’s dashboard, ideally one for production and a separate one for test environments. You store it in an environment variable, not in the repository. Set a spending limit in the provider’s dashboard straight away – it is the last line of defence if the limits in the application fail.

In VEditor, the server configuration has the keys aiProvider, aiApiKey, aiEndpoint and aiTextModel. The openai provider is the default and uses the Responses API, and aiApiKey reads the OPENAI_API_KEY variable by default. An empty aiTextModel means the provider’s default model – in the VEditor documentation, for OpenAI this is gpt-6.1-terra. The list of models available from the provider changes over time, so before deployment check the current OpenAI documentation and, if necessary, set the model explicitly.

In Laravel, two entries in .env are enough:

VEDITOR_LICENSE_KEY="VED1.…"
OPENAI_API_KEY="…"          # only for the AI edition

The package also reads the variables VEDITOR_AI_PROVIDER, VEDITOR_AI_ENDPOINT and VEDITOR_AI_MODEL, so you can change the provider and the model without touching the code. Without aiApiKey the editor shows no AI buttons.

Step 2: the endpoint and its safeguards

The endpoint calls a paid API, so it needs controls:

  1. POST only. You reject other methods (405).
  2. Authentication and role. Only logged-in users who can edit content.
  3. A CSRF token in a header, compared with the session (403 on mismatch).
  4. A request body size limit checked before parsing the JSON (413).
  5. An allowlist of actions. An unknown action is an error (400), not “pass whatever arrived to the model”.
  6. Feature permissions and usage limits – before calling the API (403 and 429).

In Laravel, the veditor/laravel package registers the POST /veditor/ai route with the ['web', 'auth'] middleware. The documentation warns you to keep auth (or your own middleware), because the endpoint calls a paid API. You set features and limits in AppServiceProvider::boot():

use Illuminate\Support\Facades\RateLimiter;
use VEditor\Laravel\VEditorService;

$veditor = app(VEditorService::class);
$veditor->aiFeaturesUsing(fn ($user) => $user?->is_admin ? null : ['transform', 'review']);
$veditor->beforeAiRequestUsing(fn (string $feature, array $data) =>
    RateLimiter::attempt('veditor-ai:' . auth()->id(), 200, fn () => true, 86400) ?: 'Daily AI limit reached.');

Without a framework, the endpoint is a single file. This code comes from the plain PHP integration documentation:

<?php
// veditor-ai.php – only for users who may edit content
require __DIR__ . '/vendor/autoload.php';

use VEditor\AiApi;
use VEditor\HtmlSanitizer;
use VEditor\License;

session_start();
$request = [
    'post' => $_SERVER['REQUEST_METHOD'] === 'POST',
    'csrfValid' => hash_equals($_SESSION['csrf_token'] ?? '', (string) ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? '')),
    'body' => AiApi::readBody(veditor_config()), // null = too large (HTTP 413)
    'host' => License::requestHost(),
];
session_write_close();
// The same styles as on save, otherwise HTML returned by AI loses their classes.
$styles = [];
$sanitizer = (new HtmlSanitizer())->allowStyles($styles);

if (AiApi::wantsStream($request['body'])) {
    AiApi::sendStream(veditor_config(), $request, $sanitizer);
    exit;
}

[$status, $data] = AiApi::handle(veditor_config(), $request, $sanitizer);
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

Note two details. session_write_close() releases the session lock before the long request to the model, so the same user’s other tabs do not have to wait. And the sanitizer gets the same styles as when the article is saved – otherwise the classes from the “Style” list will disappear from the AI result. You must add the check that the user is logged in and can edit content before this code.

Step 3: the editor in the browser

On the client side, you specify the endpoint address and the CSRF token. In plain JavaScript:

await VEditor.create('#content', {
    ai: { url: '/veditor/ai', csrfToken: token, autocomplete: false },
});

In Laravel, the @veditor directive passes these options for you. AI buttons appear only when ai.url is set and the licence covers the AI edition; on local and test addresses a free trial key is enough. If the editor cannot load the AI settings from ai.url, the buttons stay hidden and the console shows “AI settings could not be loaded.” – the first thing to check when “AI doesn’t work”.

Step 4: streaming through a proxy

With streaming, the editor sees the text as the model writes it. Technically, this is a text/event-stream response with successive data: {json} lines. In VEditor, fragments of raw text arrive first, and at the end an event with the HTML cleaned on the server. The HTTP status of the stream is always 200, and errors arrive as events.

The most common problem: a proxy collects the whole response and sends it all at once. AiApi::sendStream() sends the X-Accel-Buffering: no header for nginx and disables mod_deflate in Apache with mod_php. With PHP-FPM, disable compression for the AI endpoint yourself, and if there is a CDN in front of the server, disable buffering in it for this path. PHP’s output_buffering can also buffer.

Step 5: handling the errors that will definitely happen

The API sometimes responds slowly or rejects the request (no credit, wrong key). The editor should see a short message, and the details should go to the server log without the API key.

In the VEditor protocol, an error is the JSON { "error": "…", "params": { … }, "stop": true }, where stop: true means that retrying will not help (e.g. a wrong API key or no credit). The timeout for a single request is set by aiTimeout (60 seconds by default). Typical messages and their causes:

MessageCause
Invalid CSRF token. Reload the page.the token does not match the session (expired session, page served from cache)
AI functions require an AI Edition licence.no licence key on the server side, or a Pro key
This AI function is not available for your account.aiFeatures excludes the feature (HTTP 403)
The AI usage limit has been reached. Try again later.the limit hook refused (HTTP 429)

Pre-deployment test checklist

  • A request without login and without a CSRF token is rejected.
  • A user without permission cannot run an action with a hand-crafted HTTP request.
  • The API key does not appear in the page source, responses or error messages.
  • The stream works behind the target proxy and CDN, not just locally.
  • A result with lists, tables and links keeps its structure and passes sanitization.
  • The daily limit works and has a clear message.
  • The privacy policy describes sending content to OpenAI.

How it works in VEditor

VEditor has AI features in the AI edition. They work through your endpoint and your API key, and the vendor takes no part in requests or payments – you pay OpenAI directly. Prompts are only on the server, the browser sends the content, the action name, and a tone and language from allowlists, and the user’s own instruction goes into the model’s input data, never into the instructions. The result is cleaned on the server and once more by the editor’s schema, and then waits in a preview for the editor’s decision. Content goes to OpenAI only when a user runs an AI feature.

The same integration works with Anthropic or an OpenAI-compatible service – you change aiProvider, not the code (see OpenAI or Anthropic for editorial assistance). For the bigger picture, read the guide AI assistant in a CMS, and for editor integration beyond AI – integrating a WYSIWYG editor with PHP and JavaScript.

FAQ

Can I use the same OpenAI key for several sites?

Technically yes, but you lose cost transparency and the ability to revoke one site’s key without disabling the others.

Why do the AI buttons not appear in the editor?

Most often ai.url is missing, the licence does not cover the AI edition, the endpoint address returns an error, or no API key has been set on the server side. The message in the browser console usually tells you which case it is.

Can the AI endpoint run on a different domain from the CMS admin panel?

It can, but it complicates session cookies, CSRF and CORS. The simplest approach is to keep the endpoint in the same application as the panel.

How do I change the OpenAI model without deploying code?

Set the model in the server configuration – in Laravel through the VEDITOR_AI_MODEL variable. After the change, repeat the tests on your own texts, because a different model may handle formatting differently.

Is streaming required?

No, but it noticeably improves the editor’s experience with longer responses. In VEditor, the assistant, document translation and chat are streamed, and the other actions return plain JSON.

Try VEditor in practice

If you are building an OpenAI integration in Laravel or in plain PHP, the documentation chapters below contain the complete endpoint code and a description of the protocol.

AI in the content editor

AI assistant in a CMS — how does it work and what is it for?

An AI assistant in a CMS is a set of features built into the content editor that, at the editor’s request, send a piece of text to a language model and show a proposed change: shorter, corrected, translated or supplemented with metadata. A well-designed assistant works through the application ser…

Integrations and media

How to add a WYSIWYG editor to Laravel: a practical integration plan

A WYSIWYG editor in a Laravel application is more than a form field with a toolbar. You have to install it, configure it, put it in a view and – above all – save what the editor sends correctly. This article walks through the whole process using the veditor/laravel package as an example – from co…

Clean HTML, accessibility and SEO

How to clean HTML copied from Google Docs

HTML copied from Google Docs contains a style on almost every fragment of text, a <b id="docs-internal-guid-…"> wrapper around the whole thing, and dir, role and aria-level attributes. Cleaning it means removing that wrapper, turning styled span elements into strong and em, keeping headings, list…

Try it in your browser

The demo has the full toolbar and shows what the PHP sanitizer returns for your content.