Skip to content

Commit

Permalink
feat(nuxt): Add Http responseHook with waitUntil
Browse files Browse the repository at this point in the history
  • Loading branch information
s1gr1d committed Oct 15, 2024
1 parent 4c0c25c commit f6872ad
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions packages/nuxt/src/server/sdk.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { applySdkMetadata, getGlobalScope } from '@sentry/core';
import { init as initNode } from '@sentry/node';
import { applySdkMetadata, flush, getGlobalScope } from '@sentry/core';
import { httpIntegration, init as initNode } from '@sentry/node';
import type { Client, EventProcessor } from '@sentry/types';
import { logger } from '@sentry/utils';
import { logger, vercelWaitUntil } from '@sentry/utils';
import { DEBUG_BUILD } from '../common/debug-build';
import type { SentryNuxtServerOptions } from '../common/types';

Expand All @@ -14,6 +14,17 @@ export function init(options: SentryNuxtServerOptions): Client | undefined {
const sentryOptions = {
...options,
registerEsmLoaderHooks: mergeRegisterEsmLoaderHooks(options),
integrations: [
httpIntegration({
instrumentation: {
responseHook: () => {
// Makes it possible to end the tracing span before closing the Vercel lambda (https://vercel.com/docs/functions/functions-api-reference#waituntil)
vercelWaitUntil(flushSafelyWithTimeout());
},
},
}),
...(Array.isArray(options.integrations) ? options.integrations : []),
],
};

applySdkMetadata(sentryOptions, 'nuxt', ['nuxt', 'node']);
Expand Down Expand Up @@ -64,3 +75,16 @@ export function mergeRegisterEsmLoaderHooks(
}
return options.registerEsmLoaderHooks ?? { exclude: [/vue/] };
}

/**
* Flushes pending Sentry events with a 2-second timeout and in a way that cannot create unhandled promise rejections.
*/
export async function flushSafelyWithTimeout(): Promise<void> {
try {
DEBUG_BUILD && logger.log('Flushing events...');
await flush(2000);
DEBUG_BUILD && logger.log('Done flushing events');
} catch (e) {
DEBUG_BUILD && logger.log('Error while flushing events:\n', e);
}
}

0 comments on commit f6872ad

Please sign in to comment.