Log context on Workers
Preserve request log context in waitUntil callbacks with captureLogStore and runWithLogStore.
AI generated, pending review
On Cloudflare Workers, deferred work started with waitUntil runs after the response closes. By then the request’s log context is gone, so logs from that work lose requestId, method, and URL fields.
Snapshot the context while the handler is still live, then re-enter it inside the deferred callback.
- Call
captureLogStore()inside the handler before returning the response. - Wrap the deferred callback in
runWithLogStore(store, () => { ... }). - Pass the resulting promise to
waitUntilfromcloudflare:workers.
import { FlareHost, FlareResponse, 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.get("/reports", (ctx) => { const store = captureLogStore();
waitUntil( runWithLogStore(store, async () => { host.logger.info("report started", { path: ctx.req.path }); // slow work after the response host.logger.info("report finished"); }), );
return new FlareResponse(202, { queued: true });});
const app = host.build();export default app.export();When store is undefined (for example log.enableContext is off), runWithLogStore runs the callback without entering a store. The call is safe either way.
Why this is Workers-only
Section titled “Why this is Workers-only”On Node the request keeps running in the same process, so log context follows async work without an extra step. See Logging for how context propagation works during normal request handling.
Related
Section titled “Related”- Context and waitUntil: deeper lifecycle notes
- Cloudflare overview:
nodejs_compatrequirement - Deploy: worker entrypoint