Skip to content

Commit

Permalink
fix(cloudflare): Guard context.waitUntil call in request handler (#…
Browse files Browse the repository at this point in the history
…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`.
  • Loading branch information
Lms24 authored Sep 4, 2024
1 parent 70f938b commit 6dc8aab
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
10 changes: 8 additions & 2 deletions packages/cloudflare/src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,13 @@ export function wrapRequestHandler(
handler: (...args: unknown[]) => Response | Promise<Response>,
): Promise<Response> {
return withIsolationScope(async isolationScope => {
const { options, request, context } = wrapperOptions;
const { options, request } = wrapperOptions;

// In certain situations, the passed context can become undefined.
// For example, for Astro while prerendering pages at build time.
// see: https://github.com/getsentry/sentry-javascript/issues/13217
const context = wrapperOptions.context as ExecutionContext | undefined;

const client = init(options);
isolationScope.setClient(client);

Expand Down Expand Up @@ -89,7 +95,7 @@ export function wrapRequestHandler(
captureException(e, { mechanism: { handled: false, type: 'cloudflare' } });
throw e;
} finally {
context.waitUntil(flush(2000));
context?.waitUntil(flush(2000));
}
},
);
Expand Down
9 changes: 9 additions & 0 deletions packages/cloudflare/test/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ describe('withSentry', () => {
expect(context.waitUntil).toHaveBeenLastCalledWith(expect.any(Promise));
});

test("doesn't error if context is undefined", () => {
expect(() =>
wrapRequestHandler(
{ options: MOCK_OPTIONS, request: new Request('https://example.com'), context: undefined as any },
() => new Response('test'),
),
).not.toThrow();
});

test('creates a cloudflare client and sets it on the handler', async () => {
const initAndBindSpy = vi.spyOn(SentryCore, 'initAndBind');
await wrapRequestHandler(
Expand Down

0 comments on commit 6dc8aab

Please sign in to comment.