Claude API Chatbot Widget for Your Website: A Guide
If you want a chat bubble in the corner of your site that answers visitor questions using Claude, you need two things: a small frontend widget that renders the conversation, and a backend endpoint that talks to the Claude API securely. This article covers both pieces end to end, with working code you can adapt.
The short answer to "how do I add a Claude API chatbot widget to my website" is: never call Claude directly from browser JavaScript. You need a server (or a hosted API layer) in between to hold your API key, handle streaming, and apply rate limits. Everything below assumes that architecture, because it's the only one that works safely in production.
The architecture in one diagram
A Claude-powered chat widget has three moving parts:
- Frontend widget — HTML/CSS/JS embedded on the page, renders messages, sends user input, displays streamed replies.
- Backend endpoint — receives the widget's request, adds your API key and system prompt, calls Claude, streams the response back.
- Claude API (or a gateway like SubToAPI) — does the actual model call and returns tokens.
The backend step is non-negotiable. If you put a Claude API key in frontend JavaScript, anyone who opens dev tools can copy it and start spending your credits. A thin backend route — even a single serverless function — solves this.
Setting up the backend endpoint
You can call Claude's API directly, or route through a provider like SubToAPI that gives you an HTTPS endpoint with its own scoped application keys (sub_live_...), so you're not exposing your root Anthropic key in server config shared across projects. Either way, the pattern is the same: a POST endpoint that forwards the conversation.
// server.js — minimal Express proxy endpoint
app.post("/api/chat", async (req, res) => {
const { messages } = req.body;
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 1024,
system: "You are a helpful support assistant for Acme Inc. Answer briefly and link to docs when relevant.",
messages
})
});
const data = await response.json();
res.json(data);
});
This is enough for a non-streaming widget. Check the quickstart and the messages reference for the full request/response shape, including how max_tokens, system, and messages interact.
The widget itself
The widget only needs three things: a toggle button, a message list, and an input box. Keep the markup minimal so it doesn't clash with the host page's CSS — use a shadow DOM or tightly scoped class names if you're embedding this on third-party sites.
<div id="claude-widget">
<div id="claude-messages"></div>
<form id="claude-form">
<input id="claude-input" placeholder="Ask a question..." />
<button type="submit">Send</button>
</form>
</div>
<script>
const messages = [];
const list = document.getElementById("claude-messages");
const form = document.getElementById("claude-form");
const input = document.getElementById("claude-input");
form.addEventListener("submit", async (e) => {
e.preventDefault();
const userText = input.value.trim();
if (!userText) return;
messages.push({ role: "user", content: userText });
render("user", userText);
input.value = "";
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages })
});
const data = await res.json();
const reply = data.content[0].text;
messages.push({ role: "assistant", content: reply });
render("assistant", reply);
});
function render(role, text) {
const bubble = document.createElement("div");
bubble.className = `claude-msg claude-${role}`;
bubble.textContent = text;
list.appendChild(bubble);
list.scrollTop = list.scrollHeight;
}
</script>
Drop this snippet near the end of <body> on any page, and you've got a functional widget. From here, the improvements that actually matter for user experience are streaming and a well-scoped system prompt.
Streaming for a responsive feel
Waiting several seconds for a full response feels broken on a chat widget — users expect text to appear progressively, the way it does in Claude's own interface. This means your backend endpoint should stream chunks through to the browser instead of waiting for the full completion.
app.post("/api/chat", async (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
const upstream = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 1024,
stream: true,
messages: req.body.messages
})
});
for await (const chunk of upstream.body) {
res.write(chunk);
}
res.end();
});
On the frontend, read the response with ReadableStream or EventSource and append tokens to the last bubble as they arrive. See streaming for the exact event format and how to parse content_block_delta events.
Giving the widget a purpose
A generic "ask me anything" widget is rarely what a business wants on its homepage. Scope the bot with a system prompt that defines its role, tone, and boundaries ("only answer questions about our pricing and docs, otherwise direct the user to support@..."). If the widget needs to look up order status, pull pricing from a database, or escalate to a human, that's where tool use comes in — define a function Claude can call, and handle the tool result server-side before sending the final answer back to the widget.
Deployment checklist
Before shipping the widget live:
- API key lives only in server environment variables, never in frontend bundles
- Rate limit the
/api/chatendpoint per IP or session to prevent abuse - Set a conservative
max_tokensso a single conversation can't run away in cost - Log token usage per conversation if you need to track spend per customer or team
- Add a visible loading/typing indicator while streaming starts
If you'd rather not manage Claude accounts, billing, and key rotation yourself, SubToAPI turns your existing Claude access into a standard HTTPS API with its own keys, so the backend code above works out of the box — sign up and grab a key in a few minutes at /signup.
Questions
Can I call the Claude API directly from browser JavaScript for my widget? No. Doing so exposes your API key to anyone viewing page source or network requests. Always route requests through a backend endpoint you control.
How do I stop the chatbot from answering off-topic questions? Constrain it with a specific system prompt describing its scope, and optionally check the user's input against a topic filter before forwarding it to Claude.
Does the widget need a database to remember conversation history? Not for a single session — keep the message array in the browser and send the full history with each request. For persistence across page reloads or devices, store the conversation server-side keyed to a session or user ID.