AI summary

How the chat on my home page calls Claude from a static Astro site: one Pages Function, prompt caching, safe rendering and a ceiling on the bill.

  • The site stays static. One Pages Function 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 caching can reuse it.
  • Claude's reply is built into DOM nodes as plain text and never goes through innerHTML.
  • 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 static 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 static Astro on Cloudflare Pages, 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

Astro builds the site into static files. The chat posts to /api/chat, and Cloudflare Pages runs functions/api/chat.ts for it, because a file’s path inside functions/ becomes its URL. That file is a Pages Function, 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 Pages 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 Functions 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.

One question, from the form to the answerScrub through it, or press play.
  1. Browser

    The form posts the recent exchanges and the new question.

    POST /api/chat?locale=en
  2. Pages Function checks

    Origin, per-IP limit, body size and message shape. If one fails, Claude never sees the request.

  3. Claude request

    Everything the chat knows goes first, marked for caching. The page language and the conversation come after it.

    cache_control: { type: "ephemeral" }
  4. Text stream

    The Function forwards only Claude's text. A last event tells the browser the answer is complete.

  5. DOM nodes

    The browser builds DOM nodes from the text, with no innerHTML.

Keeping the prompt cacheable

There’s no vector database 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 caching. 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.

ts
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.

What goes before the cache breakpointThe first option is the real code. The other two are mistakes I'm avoiding.

As built

The same content gives the same bytes, and both languages share the prefix.

  • Instructions
  • Profile and articles, sorted by URL
  • cache_control breakpoint
  • Page language
  • Conversation

Build timestamp

Every build writes a different prefix, even when no article changed.

  • Instructions
  • Generated at 14:02 (added)
  • Profile and articles
  • cache_control breakpoint
  • Page language
  • Conversation

Language inside

English and Turkish visitors would need two separate cache entries.

  • Instructions
  • Profile and articles
  • Page language (changed)
  • cache_control breakpoint
  • Conversation

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 tokens 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 tokens.

Streaming to the browser

The Function calls client.messages.stream and forwards only the text:

ts
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 innerHTML: 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 innerHTML probably the most common way into XSS, 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 nodes. All text goes through createTextNode or textContent, which insert it as plain text, never as HTML. Links have to pass a check first:

ts
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:

ts
// 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 tokens 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 Origin header, and only my domains are allowed. A browser can’t fake that header, but curl can, 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 a Retry-After header that says how long to wait. If you’re the one calling an API like this, I wrote about handling a 429 and Retry-After in n8n.

That last one is weaker than it looks:

ts
// 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 WAF 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 KV: 50 messages per visitor and 400 in total. Workers KV 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 KV fails, the chat refuses instead of spending without a limit.
  • A monthly spend limit in the Claude Console. 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 R2 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 hash of the IP address. The hash 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 KV store that holds the counters, the WAF rule and the bucket are all created with Terraform. 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

  1. Anthropic: Prompt caching
  2. Anthropic: Streaming messages
  3. Anthropic: Pricing
  4. Anthropic: Thinking
  5. Anthropic: Steering thinking and cost
  6. Anthropic: Rate limits and spend limits
  7. Cloudflare: Pages Functions routing
  8. Cloudflare: Pages Functions pricing
  9. Cloudflare: Pages Functions bindings
  10. Cloudflare: Workers limits
  11. Cloudflare: How Workers works
  12. Cloudflare: Rate limiting rules
  13. Cloudflare: How the request rate is determined
  14. MDN: Element.innerHTML
  15. MDN: EventSource() constructor

Written by:

Full Stack Software EngineerSamsun, Türkiye

Full Stack Software Engineer. I started with client sites at an agency in 2019, then worked on embeds, a dashboard and analytics at a startup called Popupsmart.