How to stop a streaming free LLM API request when a user clicks Stop

To stop upstream work, carry cancellation across both HTTP hops: the browser aborts its request to your server, and the server passes an AbortSignal to the OpenAI-compatible SDK call. A button that only stops the browser reader does not itself prove that your server cancelled the separate provider request. OpenAI's Node example maps a premature response close to an abort signal; its normal-completion guard matters because close can also follow a successful response.

A Stop click aborts the browser request; the server detects the unfinished response closing and forwards an AbortSignal to the upstream free LLM API request.

Cancel the browser-to-server request

Keep the provider key on the server. The browser sends the user's message to an authenticated route and retains an AbortController only for that one in-flight request:

let activeRequest;

async function startChat(messages) {
  activeRequest = new AbortController();
  try {
    const response = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ messages }),
      signal: activeRequest.signal,
    });
    if (!response.ok) throw new Error(`Chat route returned ${response.status}`);
    return await readSseResponse(response);
  } finally {
    activeRequest = undefined;
  }
}

function stopChat() {
  activeRequest?.abort();
}

Disable Stop when there is no active request, and handle the expected abort separately from an API error. This button stops the browser's fetch. The server must still connect that disconnect to the upstream request it started.

Forward a client disconnect to the SDK

For an Express-style handler, watch the response socket and abort only when it closes before the response was normally ended. writableEnded prevents a successful stream from being misclassified as a cancelled one.

function watchClientDisconnect(res) {
  const controller = new AbortController();
  const onClose = () => {
    if (!res.writableEnded && !controller.signal.aborted) {
      controller.abort(new Error('Downstream client disconnected'));
    }
  };
  res.once('close', onClose);
  return {
    signal: controller.signal,
    cleanup: () => res.off('close', onClose),
  };
}

function waitForDrainOrClose(res) {
  return new Promise(resolve => {
    const done = () => {
      res.off('drain', done);
      res.off('close', done);
      resolve();
    };
    if (res.destroyed) return done();
    res.once('drain', done);
    res.once('close', done);
  });
}

app.post('/api/chat', async (req, res, next) => {
  const disconnect = watchClientDisconnect(res);
  try {
    const stream = openai.chat.completions.stream({
      model: 'free',
      messages: validateMessages(req.body.messages),
      stream: true,
      max_tokens: 128,
    }, { signal: disconnect.signal });

    res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
    res.setHeader('Cache-Control', 'no-cache');
    for await (const chunk of stream.toReadableStream()) {
      if (disconnect.signal.aborted || res.destroyed) break;
      if (!res.write(chunk)) await waitForDrainOrClose(res);
    }
    if (!disconnect.signal.aborted && !res.writableEnded) res.end();
  } catch (error) {
    if (!disconnect.signal.aborted) {
      if (res.headersSent) res.destroy(error);
      else next(error);
    }
  } finally {
    disconnect.cleanup();
  }
});

The openai client must be constructed on the server with a server-only key. For ChinaGenAI, the current OpenAI-compatible base URL is https://chinagenai.com/v1; the free label selects the site's automatic route. Read the current connection guide for the site key and request limits. Do not move the key into the browser to make cancellation easier.

Frameworks expose disconnect state differently. If a Fetch-style route provides a request signal, forward it to the model SDK. On Node's ServerResponse, a close event can mean either a completed response or a prematurely terminated connection, so check writableEnded before aborting. Remove listeners in finally; otherwise a long-lived server can retain callbacks after the request finishes.

Decide whether a disconnect means Stop

These are separate product behaviors:

Client event Server behavior Appropriate when
User presses Stop Abort the upstream SDK call and stop writing downstream chunks. The current answer should end now.
Tab closes or network drops Keep the producer only if the application can reconnect to the same saved stream. The user expects to resume this answer later.
User presses Stop in a resumable chat Send a separate authenticated cancel command for that stream ID. A disconnect alone must not kill a resumable producer.

For cancel-on-stop, a disconnect aborts upstream work; for resumable streaming, a reconnect keeps the producer alive and an explicit Stop command cancels it.

Do not use a simple disconnect-to-abort bridge for a resumable stream. The AI SDK documents that its stream-resume mode and abort behavior are incompatible; choose one lifecycle or implement an explicit cancellation endpoint that addresses the server-owned stream. Its stop() helper cancels the client request, while server-side code must forward an abort signal to the model operation.

Verify the two hops without spending quota

Use a loopback HTTP fixture with a fake upstream that emits two SSE chunks and then waits. The test should exercise the same browser-to-route and route-to-upstream boundaries, but it must use no real provider key or hostname.

  1. Start the fake upstream and local proxy; record when the upstream socket closes and when the proxy signal becomes aborted.
  2. Read the first synthetic chunk in the client, then call AbortController.abort().
  3. Require the proxy's close handler to set the upstream signal and the local upstream socket to close. Do not infer this result just because the browser's reader.read() rejected.
  4. Run a second fixture that ends normally. Confirm writableEnded is true and the abort counter stays at zero.
  5. If resumability is enabled, add a third case: drop one reader, reconnect using the same test stream ID, then exercise the explicit cancel command. The reconnect case should continue; the explicit Stop case should end the producer.

These checks prove the local control flow only. They do not prove a real provider accepted a request, stopped generation at a particular token, or refunded any allowance. A cancelled HTTP request is not a provider quota receipt. Check the provider's own billing and cancellation terms before making claims about usage.

For stream symptoms such as a missing terminal chunk, EOF or a reader waiting forever, use the separate stream-stall and timeout guide. For browser key placement and authentication, see the server-side key proxy guide.

Common questions

Does controller.abort() in the browser cancel the provider call?

It aborts the browser's fetch. The server route must notice the downstream disconnect and pass a signal to the SDK request it created; verify both events against a local mock.

Should every tab close cancel generation?

Only if losing the page is intended to end the answer. A resumable chat should preserve work across reconnects and expose a separate authenticated Stop action.

Does cancelling return free quota?

Do not assume so. The local test cannot establish provider accounting, and HTTP cancellation alone is not evidence of a refund.

Official references