Context and waitUntil
Keep HTTP log context in waitUntil callbacks on Cloudflare Workers with captureLogStore and runWithLogStore.
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.
Prerequisites
Section titled “Prerequisites”- Enable context in config:
{ "log": { "enableContext": true }}Or set FLARE__log__enableContext=true.
- Enable
nodejs_compatinwrangler.toml(required for Flare on Workers generally).
Capture context before waitUntil
Section titled “Capture context before waitUntil”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.
Use with DI in a handler
Section titled “Use with DI in a handler”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();API behavior
Section titled “API behavior”| Function | Behavior |
|---|---|
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.
What appears on records
Section titled “What appears on records”When log.enableContext is true:
| Context | When on record.context |
|---|---|
source: "flare:host" | During host.build() on every runtime |
source: "flare:http" with requestId, method, url | During each incoming HTTP request |
When the restored store includes state, it also appears on record.state.
Related
Section titled “Related”- Logging overview
- flare.json reference
- Host: Workers
app.export()andWorkerExportedHandle