How do I add an AI chatbot to WordPress without exposing my API key?
Keep the API key on the server: store it in wp-config.php and have your chatbot call your own WordPress REST endpoint, which calls the model from PHP. Visitors never see the key.
Good WordPress chatbot API key security starts with one rule: the key never reaches the browser. Store it on the server, for example as a constant in wp-config.php, and have the chatbot talk to your own WordPress REST endpoint, which calls the model from PHP. Anyone inspecting your site finds nothing to steal.
Dongee AI Router is a prepaid gateway that gives you an OpenAI-compatible API to several AI models. With it, you create a key just for that site and restrict it to certain models. Because it is prepaid from 3 USD, spending never goes beyond your balance.
Updated November 25, 2026 · Dongee Team
Why is it dangerous to put the key in your site's JavaScript?
Everything sent to the browser is public. If a tutorial or a plugin puts the key in a JS file or in a variable printed in the HTML, anyone can find it in two minutes with the browser's developer tools (the Network or Sources tab). A bot crawling websites finds it even faster.
With that key, someone else can spend your balance on their own projects, use it for other things in your name or leave your chatbot without service. If you have already published something like that, follow this guide to detect exposed keys in an app built with AI, revoke the key and create a new one.
How does the secure architecture work?
The idea is to put your WordPress in the middle. The browser never talks directly to the model's API:
- Chat widget (JavaScript): collects the visitor's message and sends it to your own site.
- Your WordPress REST endpoint: checks the nonce, the message length and the usage limits.
- Model API (Dongee AI Router): WordPress calls it from PHP with the key stored on the server.
- Response: the endpoint returns only the text of the answer to the widget.
The key only exists on the server. The browser sees your endpoint URL and nothing else.
How do I set it up step by step?
- Activate Dongee AI Router and create a key just for this site. From your client area, activate Dongee AI Router, top up your balance and create a key exclusively for this chatbot. Restrict it to one or two models, as explained in how to limit an API key to certain models. If it ever leaks, it can only use those models and only as far as your balance goes.
- Store the base URL and the key in wp-config.php. Add these lines before the line that tells you to stop editing. You can see the base URL and the model names in your client area. Never paste the key into the theme, into a plugin you plan to share or into a repository.
define('DONGEE_AI_BASE_URL', 'BASE_URL_FROM_YOUR_CLIENT_AREA');
define('DONGEE_AI_KEY', 'YOUR_KEY_FOR_THIS_SITE_ONLY');- Create a minimal plugin with the REST route. In your WordPress plugins folder, create a file, for example chat-ia-seguro.php, with this content, and activate it:
<?php
/*
Plugin Name: Secure AI Chat
Description: REST endpoint that calls the model from the server.
*/
if (!defined('ABSPATH')) exit;
add_action('rest_api_init', function () {
register_rest_route('chatia/v1', '/mensaje', [
'methods' => 'POST',
'callback' => 'chatia_responder',
'permission_callback' => function ($req) {
return (bool) wp_verify_nonce($req->get_header('X-WP-Nonce'), 'wp_rest');
},
]);
});
function chatia_responder(WP_REST_Request $req) {
$texto = sanitize_textarea_field((string) $req->get_param('mensaje'));
if ($texto === '' || mb_strlen($texto) > 500) {
return new WP_REST_Response(['respuesta' => 'Write a message of up to 500 characters.'], 400);
}
// Per-visitor limit (step 5)
$id_limite = 'chatia_' . md5($_SERVER['REMOTE_ADDR'] ?? '');
$usados = (int) get_transient($id_limite);
if ($usados >= 20) {
return new WP_REST_Response(['respuesta' => 'You reached the message limit for today.'], 429);
}
set_transient($id_limite, $usados + 1, DAY_IN_SECONDS);
$res = wp_remote_post(rtrim(DONGEE_AI_BASE_URL, '/') . '/chat/completions', [
'timeout' => 30,
'headers' => [
'Authorization' => 'Bearer ' . DONGEE_AI_KEY,
'Content-Type' => 'application/json',
],
'body' => wp_json_encode([
'model' => 'model-name',
'max_tokens' => 400,
'messages' => [
['role' => 'system', 'content' => 'You are the assistant for this website. Answer briefly and in English.'],
['role' => 'user', 'content' => $texto],
],
]),
]);
if (is_wp_error($res) || wp_remote_retrieve_response_code($res) !== 200) {
return new WP_REST_Response(['respuesta' => 'The assistant is not available right now. Please use the contact form.'], 503);
}
$datos = json_decode(wp_remote_retrieve_body($res), true);
$respuesta = $datos['choices'][0]['message']['content'] ?? '';
if ($respuesta === '') {
return new WP_REST_Response(['respuesta' => 'Could not answer right now. Please try again later.'], 503);
}
return ['respuesta' => $respuesta];
}
add_action('wp_enqueue_scripts', function () {
wp_register_script('chatia', false, [], null, true);
wp_enqueue_script('chatia');
wp_add_inline_script('chatia', 'window.chatIA = ' . wp_json_encode([
'url' => rest_url('chatia/v1/mensaje'),
'nonce' => wp_create_nonce('wp_rest'),
]) . ';');
});Notice that only the endpoint URL and the nonce are sent to the browser, never the key.
- Make the widget call your endpoint. Your chat interface, whether you built it yourself or it comes from an interface-only plugin, should send messages like this:
async function enviarAlChat(mensaje) {
const res = await fetch(chatIA.url, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': chatIA.nonce },
body: JSON.stringify({ mensaje })
});
const datos = await res.json();
return datos.respuesta || 'Could not answer right now.';
}- Limit usage. The code already cuts off messages longer than 500 characters and allows 20 messages per visitor per day using transients. Adjust those numbers to your case. The nonce for anonymous visitors slows down use from other sites, but it is not full authentication: the limits are your real protection. If you use page caching, remember that the nonce expires, so exclude pages with the chat from the cache or refresh the nonce.
- Test in staging before production. Run your tests on a copy of the site. If you use Dongee WordPress PRO hosting, you get staging and backups with 1-click restore from the plan's tools.
- Check usage. During the first few days, check how much the chatbot's key spends and with which model. This guide explains how to see token usage by key and by model.
What if I use a ready-made chatbot plugin?
It can be a good option if it covers the basics. Before installing one, check the following:
- Where it stores the key: it must be stored on the server (in the database or in a constant), never in the JavaScript.
- That it does not print it in the HTML: open your site, view the page source and search for the beginning of the key. If it shows up, discard the plugin.
- Configurable base URL: to use an OpenAI-compatible API such as AI Router, the plugin must let you change the base URL. Not all of them do.
- Per-user limits: look for options to limit messages, length and model.
If you are looking for ideas, any list of chatbot plugins for WordPress can be a starting point. Treat it as a list of options you still need to evaluate against the points above.
Which option is best?
| Option | Where the key lives | Effort | Spending control | Best for |
|---|---|---|---|---|
| Key in JavaScript | In the browser (public) | Low | None: anyone can use it | Nobody. It is insecure. |
| Plugin that stores the key on the server | WordPress database or configuration | Low | Depends on what the plugin offers | People who want something quick, with no coding |
| Your own WordPress endpoint | wp-config.php | Medium | High: you set the limits, the model and the messages | Developers who want control without another server |
| Separate backend (for example, a Node app on Dongee Live, Dongee's platform for publishing apps) | The app's environment variables | Medium-high | High, and separate from WordPress | People who will use the same assistant on several sites or apps |
In every case, AI Router's prepaid model sets a ceiling: if the balance runs out, requests stop and no debt is created.
What mistakes should you avoid?
- Putting the key in the theme or in a JS file: even if it is minified, it is still public.
- Leaving the endpoint open with no nonce or limits: anyone could use it as if it were a free API.
- Sending the full history with every message: tokens multiply. Send only the last few turns or a summary.
- Using the most expensive model for everything: a low-cost model handles frequently asked questions well. Save the most powerful one for the cases that need it.
- Not handling an empty balance: show a fallback message with a link to your contact page. This guide explains what happens when your AI API balance runs out.
Frequently asked questions
Do I need special hosting?
No. It works on any WordPress site with PHP that can make outgoing HTTPS requests. If you want to test without risk, WordPress PRO includes staging and backups with 1-click restore.
Does Dongee store the conversations?
Dongee AI Router does not store conversations. Your plugin could, if you program it to. In that case, tell your visitors and follow the privacy rules that apply to you (for example, GDPR or CCPA, where relevant).
How much does it cost?
AI Router is prepaid from 3 USD and has no monthly fee. Each model has its own price, and new accounts receive a welcome credit for testing.
Can I use several models?
Yes. A single key can access several models if you allow it. You program the logic for choosing the model in each case in your endpoint.
What happens if the balance runs out?
Requests stop and no debt is created. Your endpoint should detect the error and show a fallback message, as the code above does.
With the key on the server, an endpoint with limits and a prepaid balance, your chatbot is useful to your visitors and offers nothing to steal. If you have questions while setting it up, Dongee's 24/7 human support in your language (the platform translates on the fly) can help you review it by chat or WhatsApp.
Comenta lo que quieras
Unete a la charla
Solo ingresa tu email