Joel Stevick

Production RAG, line by line · Post the question and open the answer's stream · stage 3 of 6

Ask form submit

When the visitor submits the Ask form, the page posts the question as JSON to /api/demo/ask with Accept: text/event-stream. fetch resolves as soon as the response headers arrive, and the rest of the same handler reads the server-sent event stream as the Worker writes it.

Runs in: Browser, the visitor's page: demo.html and its module script. New to Cloudflare? How these fit together
demo.html26 / 26 lines on this page explainedlines 419-444 of 505; the rest are on other stage pages
In the browser
runs in the visitor's browser, on the demo page
Ingestion
runs when a PDF's text is uploaded
Query time
runs when the Worker answers a question or a search_documents call from the MCP server, and in the request handling every route shares, in the Worker and in the site's functions, which uploads and removals pass through too
MCP request
runs on a request to the MCP server or its OAuth endpoints
Site request
runs on a site request that is not a question, an upload, an MCP call or the cron: a page load, a session read, the demo page's /api/grants calls, an admin read, a file's removal
Scheduled
runs in the Worker's daily cron job
Eval run
runs when the eval harness runs on a developer's machine
MCP host
runs in an MCP host outside the Worker: the search loop example, on a developer's machine (npm run search) or in its test
Module load
runs once, when the module is loaded
Type only
erased by the TypeScript compiler; never runs
Never runs
a comment, a licence or markup with no behaviour of its own

Pinned to joelstevick-demo-rag-pipeline at 6a9c6c7.

demo.html The demo page: the first part of the Ask form's submit handler in the module script (lines 419–444).

Ask form submit handler: post the question

handler · lines 419–444View on GitHub

Intercepts the Ask form and posts the question.

Calls Module scope The demo page

  $("ask").addEventListener("submit", async (event) => {    event.preventDefault();    const form = event.target;    const question = form.elements.question.value.trim();    const status = $("ask-status");    if (question === "") return;

Intercept the form, read the question In the browser

WhatA submit listener on #ask calls preventDefault so the browser does not navigate, then reads the input named question and trims it. When nothing is left, it returns without sending a request.

WhyThe page stays in place and makes the request itself. The input's maxlength="500" (line 80) and this trim mirror the Worker's ASK 1 check, so a question typed into the page never draws ASK 1's 400.

input maxlength = 500

    const button = form.querySelector("button");    button.disabled = true;    status.textContent = STAGES.retrieving;    const answers = $("answers");

Disable Ask, name the first stage In the browser

WhatThe submit button is disabled, and the status line (#ask-status, an aria-live region) reads "Searching your documents…" before any byte is sent. answers is the container the answer boxes go into.

WhyDisabling the button stops a double click from posting the question twice, which would reserve two of the demo account's ten questions. The finally block at the end of the handler re-enables it on every path. The handler sets the status text synchronously, so it shows at the next paint instead of a network round trip later, when the Worker's first stage event (retrieving) arrives.

STAGES.retrieving = "Searching your documents…"

    try {      // `Accept: text/event-stream` asks for the answer as a stream of events (one checked      // sentence at a time) rather than one JSON body at the end. `fetch` resolves as soon as the      // headers arrive; the body is then read below while the Worker is still writing it.      const response = await fetch("/api/demo/ask", {        method: "POST",        headers: { "Content-Type": "application/json", Accept: "text/event-stream" },        body: JSON.stringify({ question }),      });

POST with Accept: text/event-stream In the browser

WhatInside a try, fetch posts {"question": …} as JSON to /api/demo/ask with Accept: text/event-stream. The URL is the site's Pages Function on the same origin, so the demo cookie goes with the request. The await resolves when the status and headers arrive, while the body is still open.

WhyThe Accept header selects the Worker's server-sent event rendering of the ask over one JSON body at the end, and the site's Pages Function forwards the header unchanged. EventSource cannot be used because it only issues GET requests with no body, and the question is a POST body. fetch with a streamed response body delivers the same events without that restriction.

method: POSTContent-Type: application/jsonAccept: text/event-stream

      // Refusals before any answer (the limit, a bad question, signed out) come as JSON.      if (!(response.headers.get("Content-Type") ?? "").includes("text/event-stream")) {        const body = await response.json().catch(() => ({}));        if (response.status === 429) { status.textContent = ""; showOffer(); return; }        status.textContent = body.error || "Something went wrong. Please try again in a minute.";        return;      }

A refusal comes as JSON In the browser

WhatIf the response's Content-Type does not contain text/event-stream, the body is parsed as JSON, and an unparseable body reads as {}. A 429 clears the status line and calls showOffer, which sets left to 0, writes "0 questions left.", hides the form (#ask) and shows the offer (#offer). Any other status shows body.error, or a generic retry line.

WhyThe Worker answers in JSON whenever it refuses before streaming. ASK 1 returns 400 for an empty question or one over 500 characters. ASK 2 returns 429, with the body {error, left: 0}, when no question is left. The router returns 401 when the access key matches no demo account, before ASK 1 runs, so a signed-out visitor gets 401 whatever the question. The site's Pages Function returns its own 503 when the DEMO service binding is missing. The media type is the reliable signal, because every streamed reply is a 200 text/event-stream and every refusal is JSON. A 401's error is the bare text "signed out", shown as it is.

429 → showOffer()400: "Please ask a question of up to 500 characters."