Skip to content

Context and waitUntil

Keep HTTP log context in waitUntil callbacks on Cloudflare Workers with captureLogStore and runWithLogStore.

AI generated, pending review Updated 10 days ago · Flare 0.3

On Cloudflare Workers, a callback passed to waitUntil runs after the response is sent, outside the request’s AsyncLocalStorage scope. Logs in that callback lose HTTP context (requestId, method, url) unless you restore it. This guide shows how to snapshot and re-enter the active log store.

  1. Enable context in config:
{
"log": { "enableContext": true }
}

Or set FLARE__log__enableContext=true.

  1. Enable nodejs_compat in wrangler.toml (required for Flare on Workers generally).

While the handler still runs inside the request scope, call captureLogStore():

import { captureLogStore, runWithLogStore } from "@flare-ts/core";
import { waitUntil } from "cloudflare:workers";
// Inside a handler with active request scope:
const store = captureLogStore();
waitUntil(
runWithLogStore(store, async () => {
// logs here carry the same context as the handler's logs
}),
);

Import waitUntil from cloudflare:workers. The runtime provides the current request’s context; Flare does not thread ExecutionContext through your handlers.

import {
FlareHost,
FlareResponse,
Logger,
captureLogStore,
runWithLogStore,
} from "@flare-ts/core";
import { cf } from "@flare-ts/core/cloudflare";
import { waitUntil } from "cloudflare:workers";
const host = new FlareHost(cf);
host.http.post(
"/orders",
{ inject: { log: Logger } },
(_ctx, scope) => {
const store = captureLogStore();
waitUntil(
runWithLogStore(store, async () => {
scope.log.info("async follow-up");
}),
);
return new FlareResponse(202, { accepted: true });
},
);
export default host.build().export();
FunctionBehavior
captureLogStore()Returns { context, state? } when context is active, or undefined when log.enableContext is off or no store exists
runWithLogStore(store, fn)Runs fn inside the captured store; returns whatever fn returns. When store is undefined, runs fn without entering a store

runWithLogStore with an async callback returns a Promise, which is what waitUntil expects.

When log.enableContext is true:

ContextWhen on record.context
source: "flare:host"During host.build() on every runtime
source: "flare:http" with requestId, method, urlDuring each incoming HTTP request

When the restored store includes state, it also appears on record.state.