JavaScript · Web security

Build a Website Chatbot Without Exposing API Keys

A chatbot that runs in a browser should never contain a private API key. This page includes a small local demo and explains the safe shape of a real AI integration.

Quick answer: Keep provider credentials on a server. Browser code is visible to visitors, so a key placed in HTML or JavaScript can be copied and misused.

Try the local chatbot demo

This demo responds to a few sample questions with simple browser rules. It does not connect to ChatGPT or send your message anywhere.

  1. Hello! Ask me why API keys should stay on a server.

Local example only · No account or API key is used.

Why browser-side API keys are unsafe

HTML, CSS, and JavaScript sent to a browser can be inspected by visitors. Hiding a value in a minified file or a public repository does not protect it. If a private credential is included in front-end code, another person may copy it and use the account or quota attached to it.

Use a server-side endpoint for requests that need a secret. The browser sends the user’s message to your server; the server validates the request, reads the credential from protected configuration, calls the provider, and returns only the response needed by the page.

Safe request flow

  1. Browser: Collect the message and send it to your own application endpoint.
  2. Server: Validate the message, apply authentication and rate limits, and read the secret from protected server configuration.
  3. Provider: Make the request from the server, where the secret is not shipped to the browser.
  4. Browser: Display the response as text. Treat returned content as untrusted input.
If a key has ever been committed to a repository or published in a webpage, remove it from the code and revoke or rotate it with the provider.

Frequently asked questions

Does this demo use ChatGPT?

No. It uses a few fixed rules in the browser to demonstrate the chat interface. It makes no network request and does not use an AI model.

Can I put an API key in a JavaScript file?

No. A JavaScript file delivered to a visitor is public. Keep private credentials on a server and call the provider from there.

Can I build a chat interface with HTML, CSS, and JavaScript?

Yes. Those technologies can create the interface and manage browser interactions. A real AI service also needs a secure server-side component to protect credentials and control requests.

Does a server endpoint automatically make a chatbot secure?

No. Validate input, limit request rates, protect private endpoints, avoid logging secrets, and handle errors without exposing internal details.