Skip to content

Commit 6dc8aab

Browse files
authored
fix(cloudflare): Guard context.waitUntil call in request handler (#13549)
Guard the call for `context.waitUntil` in the CF request handler wrapper. Our public API requires `context` to be present, however, in certain cases like Astro during build (prerendering), `context` becomes `undefined`.
1 parent 70f938b commit 6dc8aab

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

packages/cloudflare/src/request.ts

+8-2
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,13 @@ export function wrapRequestHandler(
3131
handler: (...args: unknown[]) => Response | Promise<Response>,
3232
): Promise<Response> {
3333
return withIsolationScope(async isolationScope => {
34-
const { options, request, context } = wrapperOptions;
34+
const { options, request } = wrapperOptions;
35+
36+
// In certain situations, the passed context can become undefined.
37+
// For example, for Astro while prerendering pages at build time.
38+
// see: https://github.com/getsentry/sentry-javascript/issues/13217
39+
const context = wrapperOptions.context as ExecutionContext | undefined;
40+
3541
const client = init(options);
3642
isolationScope.setClient(client);
3743

@@ -89,7 +95,7 @@ export function wrapRequestHandler(
8995
captureException(e, { mechanism: { handled: false, type: 'cloudflare' } });
9096
throw e;
9197
} finally {
92-
context.waitUntil(flush(2000));
98+
context?.waitUntil(flush(2000));
9399
}
94100
},
95101
);

packages/cloudflare/test/request.test.ts

+9
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,15 @@ describe('withSentry', () => {
4545
expect(context.waitUntil).toHaveBeenLastCalledWith(expect.any(Promise));
4646
});
4747

48+
test("doesn't error if context is undefined", () => {
49+
expect(() =>
50+
wrapRequestHandler(
51+
{ options: MOCK_OPTIONS, request: new Request('https://example.com'), context: undefined as any },
52+
() => new Response('test'),
53+
),
54+
).not.toThrow();
55+
});
56+
4857
test('creates a cloudflare client and sets it on the handler', async () => {
4958
const initAndBindSpy = vi.spyOn(SentryCore, 'initAndBind');
5059
await wrapRequestHandler(

0 commit comments

Comments
 (0)