Skip to main content
Share
Channels

How to Add ChatGPT to Your Website Without Exposing Your API Key

OpenAI says never to put an API key in browser code. The two safe ways to add ChatGPT to a website - your own server-side proxy, with working code, or a chatbot builder that trains on your pages and gives you a one-line embed.

Content & Engineering
Nov 27, 2026
9 min read
Last verified October 2026
how to add chatgpt to my websitehow to put chatgpt on your websiteai chatbot for website freechatgpt chatbot for websitetrain chatbot on website content
TL;DR

OpenAI says never to put an API key in browser code. The two safe ways to add ChatGPT to a website - your own server-side proxy, with working code, or a chatbot builder that trains on your pages and gives you a one-line embed.

Key Takeaways
  • 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.

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.

ApproachWhere the key livesEffortGood for
Key in front-end codeIn every visitor's browserLowestNever - do not do this
Your own server-side proxyYour server's environment or secret managerA small backend, plus abuse protectionDevelopers who want full control of prompts and UI
Chatbot builder with an embedThe builder's servers (or your key stored in its dashboard)Minutes, no codeSupport, 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_id to 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.

  1. Collect the content. Crawl your help pages, product pages and policies; add PDFs and documents. Strip navigation, footers and cookie banners.
  2. 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".
  3. Retrieve per question. For each visitor question, fetch the top few passages.
  4. 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".
  5. 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.

Try it yourself
Build your first chatbot free
Free plan, no credit card required. Live on your site in about 10 minutes.
Start building free

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:

  1. Create a chatbot in the AI chatbot builder, from a template or from scratch.
  2. 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.
  3. 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.
  4. Set boundaries. Tone, language, topics to stay within and what to do when the answer is not in your content.
  5. Add a handover step so visitors can reach a person in the shared inbox. Live chat and handover are included on every plan.
  6. 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:

RouteHow it happensAvoid it by
Site-builder custom code boxesA 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 visitorOnly paste embed snippets that contain no secret; anything with your key belongs on a server
Front-end environment variablesA variable with a public prefix (the kind a front-end framework exposes to the browser) is inlined into the bundleRead the key only in server code, API routes or serverless functions
Browser extensions and pluginsA WordPress plugin or browser-side widget asks for your key in a settings field and then calls OpenAI from the visitor's browserCheck where the plugin makes its requests; open the network tab and look for api.openai.com calls from the page
Mobile appsThe key is compiled into the app, where it can be extractedRoute through your backend; OpenAI names mobile apps alongside browsers
Git historyThe key was removed from the code but remains in an earlier commitRevoke 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.

Try the free chatbot builder
600 conversations a month, every channel, no credit card.
Start free

Proxy or builder: an honest comparison

Your own proxyChatbot builder
Key exposureNone, if done correctlyNone; the embed contains no key
Time to first working botHours to days, more for groundingMinutes from a template
Grounding on your siteYou build crawling, indexing and retrievalBuilt in: crawl a URL or upload documents
Abuse and cost protectionYou build rate limits and capsHandled by the platform; plan limits cap conversations
Human handoverYou build an inbox or integrate oneIncluded (live chat and shared inbox)
Other channelsSeparate work per channelSame bot on WhatsApp, Messenger, Instagram and more
Full control of UI and promptsCompleteWithin the builder's options
Best fitAI is the product, or you need custom behaviourAI 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.

Share this article:

Was this article helpful?

Ready to build your chatbot?

Join the businesses. Deploy on website, WhatsApp, and 11 more channels in minutes. Free forever plan available.

No credit cardNo coding13+ channels
Start Building Free

Get chatbot insights delivered weekly

Join 5,000+ professionals getting actionable AI chatbot strategies, industry benchmarks, and product updates.

🎯Automate this with a free chatbot

Build and deploy in 10 minutes. No coding needed.

❓FAQ

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.

🔍
Popular:

Either build a small server-side endpoint that calls the OpenAI API with a key stored in an environment variable, and call that endpoint from your page, or use a chatbot builder that runs the AI on its servers and gives you a one-line embed code. Never put the API key in the page's JavaScript.

No. OpenAI's key-safety guide says never deploy your key in client-side environments like browsers or mobile apps, because anyone can read it and make requests on your behalf. Route requests through your own backend, where the key stays secret.

No. Front-end build tools inline those values into the JavaScript bundle that every visitor downloads, so the key is still public. Environment variables only protect a key on the server.

Ground it: crawl your pages, index the text, retrieve the relevant passages for each question and tell the model to answer only from them. Chatbot builders such as Conferbot do this by crawling a website URL or uploaded documents into a knowledge base.

No. Conferbot has built-in AI that works without an OpenAI account. On Pro and up you can also use your own OpenAI key in the OpenAI step, or use Claude, Gemini, DeepSeek and other providers.

Yes. Conferbot's Free plan includes 600 conversations a month across two chatbots, with AI answers, a knowledge base built from your website and live chat handover, installed with a single embed line.

Revoke it in the OpenAI dashboard immediately; OpenAI states revocations take effect within a few seconds. Create a new key, store it server-side, check usage for unexpected requests, and remove the old key from your code history.

Rate limit by IP and session, cap input length and max_output_tokens, check the request origin, set a monthly spend limit on the OpenAI project and send a hashed safety_identifier per user. A public endpoint without these can be called in a loop at your expense.

About the Author

Content & Engineering

The Conferbot team writes about building, deploying, and improving AI chatbots.

View all articles
Skip the blank canvas
Start from one of 250+ free chatbot templates for lead generation, support, e-commerce, and 20+ industries - customize and launch in minutes.
Browse free templates

Related Articles

Omnichannel Platform

One Chatbot,
Every Channel

Your chatbot works seamlessly across WhatsApp, Messenger, Slack, and 6 more platforms. Build once, deploy everywhere.

View All Channels
Conferbot
online
Hi! How can I help you today?
I need pricing info
Conferbot
Active now
Welcome! What are you looking for?
Book a demo
Sure! Pick a time slot:
#support
Conferbot
New ticket from Sarah: "Can't access dashboard"
Auto-resolved. Password reset link sent.