Skip to content

Log context on Workers

Preserve request log context in waitUntil callbacks with captureLogStore and runWithLogStore.

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

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.

  1. Call captureLogStore() inside the handler before returning the response.
  2. Wrap the deferred callback in runWithLogStore(store, () => { ... }).
  3. Pass the resulting promise to waitUntil from cloudflare: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.

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.