The one rule, and the two safe ways to follow it
Never paste an OpenAI key into website JavaScript. Add ChatGPT through a server-side proxy, or through a chatbot builder that keeps the key on its servers, trains on your pages and gives you a one-line embed.
Last verified: October 2026 against OpenAI's best practices for API key safety, the API authentication reference and the Responses API reference.
OpenAI is unambiguous about this. Its key-safety guide says: "Never deploy your key in client-side environments like browsers or mobile apps." Exposing it there, the guide continues, lets malicious users take the key and make requests on your behalf, which may lead to unexpected charges or compromise of account data, so "Requests should always be routed through your own backend server where you can keep your API key secure." The API reference repeats it: do not expose your key in any client-side code such as browsers or apps; load it from an environment variable or key management service on the server.
Anything in your page's JavaScript is public. Minifying it, putting it in a separate file or "hiding" it in an environment variable that your build tool inlines into the bundle does not change that: anyone can open the browser's developer tools and read the request headers. So the real question is not how to hide the key in the browser, but where the server that holds it lives.
| Approach | Where the key lives | Effort | Good for |
|---|---|---|---|
| Key in front-end code | In every visitor's browser | Lowest | Never - do not do this |
| Your own server-side proxy | Your server's environment or secret manager | A small backend, plus abuse protection | Developers who want full control of prompts and UI |
| Chatbot builder with an embed | The builder's servers (or your key stored in its dashboard) | Minutes, no code | Support, sales and FAQ bots trained on your site |
Option 1: a server-side proxy you build
The pattern is simple: the browser talks to your endpoint, and only your server talks to OpenAI. Here is a minimal Node.js version using OpenAI's official SDK and the Responses API. The model name comes from an environment variable so you can change it without a deploy.
// server.js - Node 18+, npm install express openai
import express from "express";
import OpenAI from "openai";
const app = express();
app.use(express.json({ limit: "10kb" })); // refuse oversized bodies
const client = new OpenAI(); // reads OPENAI_API_KEY from the environment
app.post("/api/chat", async (req, res) => {
const message = String(req.body?.message || "").slice(0, 2000); // cap input length
if (!message) return res.status(400).json({ error: "empty message" });
try {
const response = await client.responses.create({
model: process.env.OPENAI_MODEL,
instructions: "You are the support assistant for Acme. Answer only questions about Acme's products. If unsure, offer to connect the visitor with the team.",
input: message,
max_output_tokens: 400, // cap cost per reply
});
res.json({ reply: response.output_text });
} catch (err) {
res.status(502).json({ error: "assistant unavailable" }); // never return raw error details
}
});
app.listen(3000);And the browser side, which contains no secret at all:
const r = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: input.value }),
});
const { reply } = await r.json();The instructions parameter is, in the Responses API reference's words, a system or developer message inserted into the model's context, and max_output_tokens sets an upper bound on the tokens generated for a response. Both are your first line of cost and behaviour control.
A proxy moves the problem; it does not remove it
Your key is now safe, but your /api/chat endpoint is public, and anyone can call it in a loop and spend your money through it. A production proxy also needs:
- Rate limiting per IP and per session, so one visitor cannot send thousands of requests.
- An origin check so other sites cannot embed your endpoint (this stops casual reuse, not determined abuse).
- Input and output caps, as in the example, plus a monthly spend limit with hard enforcement on the OpenAI project, which OpenAI's key-safety guide recommends.
- A per-user identifier. The Responses API accepts a
safety_identifier, a stable ID for each of your users that helps OpenAI detect policy abuse; OpenAI recommends hashing a username or email rather than sending it in clear. - Conversation memory. The example is stateless. For multi-turn chat, keep the history on your server, or use the API's
previous_response_idto chain responses.
The guide to chatbot API rate limiting covers the pacing patterns in more detail.
Making it answer from your website, not from the internet
A bare model answers from its general training. Ask it about your returns policy and it will produce a plausible-sounding policy that may not be yours. Website chatbots that work well are grounded: before each answer, the system finds the relevant passages of your own content and gives them to the model with an instruction to answer only from them.
- Collect the content. Crawl your help pages, product pages and policies; add PDFs and documents. Strip navigation, footers and cookie banners.
- Split and index it. Break the text into passages of a few paragraphs and index them for search, usually with embeddings so that "how do I cancel" finds "subscription cancellation policy".
- Retrieve per question. For each visitor question, fetch the top few passages.
- Answer with sources. Pass the passages to the model with instructions such as "answer only from the provided text; if the answer is not there, say so and offer a person".
- Keep it fresh. Re-crawl when your site changes, or answers drift out of date.
Each step is straightforward and together they are a real project: a crawler, an index, a retrieval step, prompt assembly and a refresh job, on top of the proxy. That is the main reason teams that are not building an AI product choose option 2.
Option 2: a chatbot builder with a one-line embed
A chatbot builder does all of the above on its servers and gives you a snippet to paste into your site. Done this way, the only thing in your page is the widget loader; there is no API key in it.
With Conferbot's website chatbot the steps are:
- Create a chatbot in the AI chatbot builder, from a template or from scratch.
- Add your content. The AI knowledge base takes a website URL to crawl, uploaded documents (PDF, Word, text) or pasted text, and can re-crawl on a schedule so answers follow your site.
- Choose the model. Conferbot can route AI answers to OpenAI GPT, Anthropic Claude, Google Gemini, DeepSeek and 17 other providers. You can use Conferbot's built-in AI without an OpenAI account, or, on Pro and up, use your own OpenAI key in the builder's OpenAI step, a native integration - it is stored in Conferbot, not in your website code. See OpenAI and other model integrations.
- Set boundaries. Tone, language, topics to stay within and what to do when the answer is not in your content.
- Add a handover step so visitors can reach a person in the shared inbox. Live chat and handover are included on every plan.
- Publish and embed. Go to Publish, Get Embed Code, and paste the single line of JavaScript before the closing
</body>tag, or use the plugin for WordPress, Shopify, Wix and other platforms. The script loads asynchronously, so it does not block your page.
Conferbot's Free plan includes 600 conversations a month across two chatbots, with the built-in AI. The OpenAI step with your own key is a native integration on Pro and up, and OpenAI bills that usage to your account separately.
Five ways keys end up public anyway
Most leaked keys were not pasted into a page on purpose. They got there through one of these routes:
| Route | How it happens | Avoid it by |
|---|---|---|
| Site-builder custom code boxes | A tutorial says to paste a fetch() call with Authorization: Bearer sk-... into a "custom code" or "header scripts" field. That field is published to every visitor | Only paste embed snippets that contain no secret; anything with your key belongs on a server |
| Front-end environment variables | A variable with a public prefix (the kind a front-end framework exposes to the browser) is inlined into the bundle | Read the key only in server code, API routes or serverless functions |
| Browser extensions and plugins | A WordPress plugin or browser-side widget asks for your key in a settings field and then calls OpenAI from the visitor's browser | Check where the plugin makes its requests; open the network tab and look for api.openai.com calls from the page |
| Mobile apps | The key is compiled into the app, where it can be extracted | Route through your backend; OpenAI names mobile apps alongside browsers |
| Git history | The key was removed from the code but remains in an earlier commit | Revoke and replace it; deleting it from the latest commit is not enough |
A quick audit for any live site: load the page, open the browser's developer tools, filter network requests for openai, and search the page source and loaded scripts for sk-. If either turns something up, treat the key as leaked.
Proxy or builder: an honest comparison
| Your own proxy | Chatbot builder | |
|---|---|---|
| Key exposure | None, if done correctly | None; the embed contains no key |
| Time to first working bot | Hours to days, more for grounding | Minutes from a template |
| Grounding on your site | You build crawling, indexing and retrieval | Built in: crawl a URL or upload documents |
| Abuse and cost protection | You build rate limits and caps | Handled by the platform; plan limits cap conversations |
| Human handover | You build an inbox or integrate one | Included (live chat and shared inbox) |
| Other channels | Separate work per channel | Same bot on WhatsApp, Messenger, Instagram and more |
| Full control of UI and prompts | Complete | Within the builder's options |
| Best fit | AI is the product, or you need custom behaviour | AI supports your business: support, sales, FAQs |
Many teams do both: a builder for the customer-facing widget, and their own backend for internal tools. What no one should do is the third option at the top of this page.
Key hygiene, whichever route you pick
OpenAI's key-safety guide and production best practices add habits that apply to any server holding a key:
- Use environment variables or a secret manager, never a key in source code. OpenAI calls committing keys to a repository a common way they leak.
- One key per person. OpenAI's first rule is a unique key for each team member (sharing keys is against its Terms of Use). Separate keys per environment also let you revoke one without breaking the rest.
- Set an expiry and rotate. OpenAI recommends an expiration date on project keys and a regular rotation: create the replacement, deploy it, then revoke the old key once the new one works. Administrators can enforce a maximum key lifetime.
- Set spend limits and watch usage. OpenAI recommends monthly spend limits for the organization or projects, with hard enforcement. A sudden spike on the Usage page is often the first sign a key has leaked.
If a key has already leaked
Revoke it in the OpenAI dashboard at once. The authentication reference states that revocations take effect within a few seconds. Create a new key, store it server-side, deploy, and check your usage for requests you did not make. Then remove the old key from your code and its history; a key deleted only in the latest commit is still in the repository.
Same bot, other channels
A Conferbot website chatbot can also answer on the other channels Conferbot connects to - one builder for every major chat platform, with a free plan and developer-grade references for each: WhatsApp · Messenger · Instagram · Telegram · Slack · Discord · LINE · Microsoft Teams, plus the mobile SDK.
Start free with Conferbot - no credit card, 600 conversations a month.
Was this article helpful?
Build and deploy in 10 minutes. No coding needed.
How to Add ChatGPT to Your Website Without Exposing Your API Key FAQ
Everything you need to know about chatbots for how to add chatgpt to your website without exposing your api key.
About the Author
The Conferbot team writes about building, deploying, and improving AI chatbots.
View all articles