AI summary
How the chat on my home page calls Claude from a staticA static site is only ready-made files (HTML, CSS, JavaScript). The host sends them as they are, and none of your code runs on the server. AstroA web framework that turns your pages into static files at build time. site: one Pages FunctionA small piece of server code that Cloudflare Pages runs for one URL path of your site. The rest of the site stays plain files., prompt cachingAnthropic keeps the processed start of a prompt for a few minutes. A later request that starts with exactly the same text pays much less for that part., safe rendering and a ceiling on the bill.
- The site stays staticA static site is only ready-made files (HTML, CSS, JavaScript). The host sends them as they are, and none of your code runs on the server.. One Pages FunctionA small piece of server code that Cloudflare Pages runs for one URL path of your site. The rest of the site stays plain files. at /api/chat holds the API key and talks to Claude.
- A build script writes everything the chat may know in a fixed order and with no timestamps, so prompt cachingAnthropic keeps the processed start of a prompt for a few minutes. A later request that starts with exactly the same text pays much less for that part. can reuse it.
- Claude's reply is built into DOM nodesThe elements and pieces of text that make up a page in the browser. Code can create them one by one instead of writing an HTML string. as plain text and never goes through innerHTMLA browser property that takes a string and turns it into page elements, including any tags hidden in the string..
- There are several limits against abuse, but only the monthly spend limit puts a ceiling on the bill.
Calling Claude needs an API key, and the key has to stay secret. A staticA static site is only ready-made files (HTML, CSS, JavaScript). The host sends them as they are, and none of your code runs on the server. site has nowhere to keep it: every file of the site goes to the visitor’s browser, so a key put there is visible to anyone.
The key has to live on the server as an environment variable. My site is staticA static site is only ready-made files (HTML, CSS, JavaScript). The host sends them as they are, and none of your code runs on the server. AstroA web framework that turns your pages into static files at build time. on Cloudflare PagesCloudflare's hosting for sites. You give it the built files and it serves them from Cloudflare's network., so the chat on my home page needs one small piece of server code that reads the key and calls Claude. Everything else can stay plain HTML.
That piece of server code is a public endpoint. Every answer is on my bill, and whatever comes back gets shown on my page. So most of the work went into three things: keeping the prompt cacheable, not trusting the answer, and putting a ceiling on the bill.
The chat is live, but it hasn’t had enough traffic to measure. This article describes what the code does, so you won’t find response times, how often the cache helped or a cost per conversation here.
Why a Pages Function keeps the site static
AstroA web framework that turns your pages into static files at build time. builds the site into staticA static site is only ready-made files (HTML, CSS, JavaScript). The host sends them as they are, and none of your code runs on the server. files. The chat posts to /api/chat, and Cloudflare PagesCloudflare's hosting for sites. You give it the built files and it serves them from Cloudflare's network. runs functions/api/chat.ts for it, because a file’s path inside functions/ becomes its URL. That file is a Pages FunctionA small piece of server code that Cloudflare Pages runs for one URL path of your site. The rest of the site stays plain files., and only that path runs server code. Requests that don’t run a Function are free and unlimited on Pages.
The API key lives in Cloudflare PagesCloudflare's hosting for sites. You give it the built files and it serves them from Cloudflare's network. as an encrypted environment variable, which Pages calls a secret. The Function reads it only through context.env, so the key never ends up in the code sent to the browser.
Pages FunctionsA small piece of server code that Cloudflare Pages runs for one URL path of your site. The rest of the site stays plain files. run on Cloudflare Workers, Cloudflare’s service for running code on its own servers. The free Workers plan allows 10 ms of CPU time per request, and time spent waiting on the network doesn’t count.
The Function streams the answer: it passes each piece of text to the browser as soon as Claude writes it. Streaming takes a while, but most of that time should be waiting on the network, which doesn’t count toward the 10 ms. I don’t have logs to check that guess yet. If CPU-limit errors show up, I’ll move the project to the paid plan.
- Browser
The form posts the recent exchanges and the new question.
POST /api/chat?locale=en - Pages Function checks
Origin, per-IP limit, body size and message shape. If one fails, Claude never sees the request.
- Claude request
Everything the chat knows goes first, marked for caching. The page language and the conversation come after it.
cache_control: { type: "ephemeral" } - Text stream
The Function forwards only Claude's text. A last event tells the browser the answer is complete.
- DOM nodes
The browser builds DOM nodes from the text, with no innerHTML.
Keeping the prompt cacheable
There’s no vector databaseA database that finds text by meaning. Chatbots often use one to pick a few relevant documents before asking the model. here, and no model to train like the layered FAQ bot I wrote about earlier. scripts/build-assistant-context.mjs writes everything the chat may know into one generated file, the knowledge block: the instructions, the public facts from my profile, and every published article without its code blocks and markup. Long articles are cut at about 14,000 characters so no single article takes over the prompt. Every request sends the whole thing.
That only makes sense with prompt cachingAnthropic keeps the processed start of a prompt for a few minutes. A later request that starts with exactly the same text pays much less for that part.. Anthropic keeps the processed start of a prompt for a short time, and the next request that starts with the same text pays much less for that part.
The cache only matches if the start of the prompt is the same. Anthropic’s docs ask for “100 percent identical prompt segments” up to the block marked with cache_control. That mark is the cache breakpoint. Everything before it, the prefix, is what gets cached.
So the script’s job is to produce the same bytes from the same content. Articles are sorted by URL, line endings are normalized, and nothing writes a build timestamp.
system: [
{
type: "text",
text: ASSISTANT_CONTEXT,
cache_control: { type: "ephemeral" },
},
{ type: "text", text: pageLanguage[locale] },
],The page language sits after the breakpoint on purpose. What comes after it doesn’t affect the match, so English and Turkish visitors can share one cache entry.
A cache entry lives for five minutes and each use refreshes it, so after a quiet gap the next request writes it again. Whether that pays off on a site this quiet got its own article.
Each request logs cacheRead and cacheWrite: how many prompt tokensThe small chunks of text a model reads and writes, often a word or part of a word. Anthropic bills by the token. came from the cache and how many were written to it. In my tests on the live chat, later requests came back with cacheRead above zero, so the prefix is matching.
The build warns when the block gets too big, because the model I use, Haiku 5.5, costs more once a prompt passes 100,000 tokensThe small chunks of text a model reads and writes, often a word or part of a word. Anthropic bills by the token..
Streaming to the browser
The Function calls client.messages.stream and forwards only the text:
for await (const event of upstream) {
if (
event.type === "content_block_delta" &&
event.delta.type === "text_delta"
) {
wroteText = true;
send({ type: "text", text: event.delta.text });
}
}Browsers have a built-in API for reading a server stream, EventSource, but it can’t send a POST body. So fetch reads the response and splits it into three event types of my own: text, done and error. If the stream closes without done, the browser shows an interrupted message instead of treating a partial answer as finished.
Model output never reaches innerHTML
A visitor can steer what the model writes, so I treat the reply as untrusted text.
The tempting shortcut is innerHTMLA browser property that takes a string and turns it into page elements, including any tags hidden in the string.: it takes a string and turns any tags in it into real page elements. If a reply contains <img src=x onerror="...">, the browser runs the code in onerror.
Mozilla’s MDN docs call innerHTMLA browser property that takes a string and turns it into page elements, including any tags hidden in the string. probably the most common way into XSSCross-site scripting. Someone gets their own script to run on your page, where it can read what the visitor sees or act as them., and a chat that shows Markdown is exactly where you’d be tempted to use it.
src/scripts/chat/markdown.ts never hands the browser an HTML string. It parses a small part of Markdown itself and creates each element and piece of text on its own, as DOM nodesThe elements and pieces of text that make up a page in the browser. Code can create them one by one instead of writing an HTML string.. All text goes through createTextNode or textContent, which insert it as plain text, never as HTML. Links have to pass a check first:
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
if (url.username || url.password) return null;Images aren’t shown at all, only their alt text. An image loads without a click, so a URL written by the model could carry data away in its query string:
// Images are never loaded: a model-written URL could carry data away.
if (isImage || insideLink) parent.append(doc.createTextNode(label));Why Haiku on a public endpoint
Anyone can call this endpoint without an account. The job is also narrow: short answers from one block of text. So the default is claude-haiku-5-5, the cheapest model on Anthropic’s price list, and the CLAUDE_MODEL environment variable can override it without a code change.
max_tokens is the most tokensThe small chunks of text a model reads and writes, often a word or part of a word. Anthropic bills by the token. Claude may write in one answer. I set it to 1024 as a deliberate cost cap. Haiku 5.5 thinks before it answers by default, and that thinking counts toward the cap. So the effort setting, which controls how much the model thinks, is low.
The answers I’ve tested so far were short and correct, but that’s a handful of questions and not a real measure of quality.
Abuse limits, and which one caps the bill
The Function rejects these before it spends anything:
- Origin. The browser names the site a request comes from in the
Originheader, and only my domains are allowed. A browser can’t fake that header, butcurlcan, so this stops other websites and doesn’t stop scripts. - Shape. JSON only, with limits on body size, message count and message length. Claude’s earlier replies come back from the browser with each request, so a visitor can make them up, and they’re capped too.
- Per IP. A limit per minute and per hour, keyed on
CF-Connecting-IP, the header where Cloudflare puts the visitor’s IP. Past it, the Function answers with HTTP 429 (Too Many Requests) and aRetry-Afterheader that says how long to wait. If you’re the one calling an API like this, I wrote about handling a 429 andRetry-Afterin n8n.
That last one is weaker than it looks:
// A first layer only: this state lives in one isolate, so it resets and is not
// shared across Cloudflare locations. Pair it with a WAF rate-limit rule.
const clients = new Map<string, number[]>();Cloudflare runs the Function in isolates: small, walled-off copies of the JavaScript engine, each with its own memory. Cloudflare can shut an isolate down at any time, and a new one starts with an empty counter. I kept the limit because it costs nothing and can slow one client hitting one isolate. It doesn’t protect the bill.
Three other layers do that:
- A Cloudflare WAFWeb Application Firewall. Cloudflare's filter in front of your site that can block or limit requests before they reach your code. rate-limiting rule on
/api/chat. It blocks a burst before the Function runs. Its counters are per data center, so it’s still not a global limit. - Daily counters in Workers KVCloudflare's key-value store. A Function can read and write small values in it, and they survive between requests.: 50 messages per visitor and 400 in total. Workers KVCloudflare's key-value store. A Function can read and write small values in it, and they survive between requests. can’t add one to a counter in a single safe step, so two requests at the same moment can overwrite each other and the counts are approximate. If Workers KVCloudflare's key-value store. A Function can read and write small values in it, and they survive between requests. fails, the chat refuses instead of spending without a limit.
- A monthly spend limit in the Claude ConsoleAnthropic's web dashboard for an API account, where you manage keys, billing and limits.. Once usage reaches it, the API rejects requests until the limit is raised or the next month starts. Of everything here, it’s the only number that puts a ceiling on the bill.
Saving the conversations
Each turn is appended to one JSON file per conversation in a private R2Cloudflare's file storage. Files sit in buckets, named containers you create for them. bucket, so I can read what people ask and improve the answers. The file holds the questions and answers, approximate location from Cloudflare, the network provider, the browser, the language and a hashA short fingerprint computed from a value. The same input always gives the same hash, but you can't turn the hash back into the input. of the IP address. The hashA short fingerprint computed from a value. The same input always gives the same hash, but you can't turn the hash back into the input. changes every day, and the raw IP isn’t stored.
A lifecycle rule on the bucket deletes everything after 90 days, and the privacy page says all of this.
The Workers KVCloudflare's key-value store. A Function can read and write small values in it, and they survive between requests. store that holds the counters, the WAFWeb Application Firewall. Cloudflare's filter in front of your site that can block or limit requests before they reach your code. rule and the bucket are all created with TerraformA tool that creates cloud resources from config files, so the setup lives in code instead of in dashboard clicks.. I wrote up that setup separately.
This chat only answers in text. If you’d rather let an AI model use your page’s features directly, see what WebMCP is.
References
- Anthropic: Prompt caching
- Anthropic: Streaming messages
- Anthropic: Pricing
- Anthropic: Thinking
- Anthropic: Steering thinking and cost
- Anthropic: Rate limits and spend limits
- Cloudflare: Pages Functions routing
- Cloudflare: Pages Functions pricing
- Cloudflare: Pages Functions bindings
- Cloudflare: Workers limits
- Cloudflare: How Workers works
- Cloudflare: Rate limiting rules
- Cloudflare: How the request rate is determined
- MDN: Element.innerHTML
- MDN: EventSource() constructor
