Skip to content

feat(nuxt): Add Cloudflare Nitro plugin #15597

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 22 commits into from
Jun 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions packages/core/src/utils/meta.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { SerializedTraceData } from '../types-hoist/tracing';
import { getTraceData } from './traceData';

/**
Expand All @@ -21,8 +22,8 @@ import { getTraceData } from './traceData';
* ```
*
*/
export function getTraceMetaTags(): string {
return Object.entries(getTraceData())
export function getTraceMetaTags(traceData?: SerializedTraceData): string {
return Object.entries(traceData || getTraceData())
.map(([key, value]) => `<meta name="${key}" content="${value}"/>`)
.join('\n');
}
16 changes: 16 additions & 0 deletions packages/core/test/lib/utils/meta.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,20 @@ describe('getTraceMetaTags', () => {

expect(getTraceMetaTags()).toBe('');
});

it('uses provided traceData instead of calling getTraceData()', () => {
const getTraceDataSpy = vi.spyOn(TraceDataModule, 'getTraceData');

const customTraceData = {
'sentry-trace': 'ab12345678901234567890123456789012-1234567890abcdef-1',
baggage:
'sentry-environment=test,sentry-public_key=public12345,sentry-trace_id=ab12345678901234567890123456789012,sentry-sample_rate=0.5',
};

expect(getTraceMetaTags(customTraceData))
.toBe(`<meta name="sentry-trace" content="ab12345678901234567890123456789012-1234567890abcdef-1"/>
<meta name="baggage" content="sentry-environment=test,sentry-public_key=public12345,sentry-trace_id=ab12345678901234567890123456789012,sentry-sample_rate=0.5"/>`);

expect(getTraceDataSpy).not.toHaveBeenCalled();
});
});
5 changes: 5 additions & 0 deletions packages/nuxt/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@
"types": "./build/module/types.d.ts",
"import": "./build/module/module.mjs",
"require": "./build/module/module.cjs"
},
"./module/plugins": {
"types": "./build/module/runtime/plugins/index.d.ts",
"import": "./build/module/runtime/plugins/index.js"
}
},
"publishConfig": {
Expand All @@ -45,6 +49,7 @@
"@nuxt/kit": "^3.13.2",
"@sentry/browser": "9.33.0",
"@sentry/core": "9.33.0",
"@sentry/cloudflare": "9.33.0",
"@sentry/node": "9.33.0",
"@sentry/rollup-plugin": "^3.5.0",
"@sentry/vite-plugin": "^3.5.0",
Expand Down
47 changes: 47 additions & 0 deletions packages/nuxt/src/runtime/hooks/captureErrorHook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { captureException, getClient, getCurrentScope } from '@sentry/core';
// eslint-disable-next-line import/no-extraneous-dependencies
import { H3Error } from 'h3';
import type { CapturedErrorContext } from 'nitropack';
import { extractErrorContext, flushIfServerless } from '../utils';

/**
* Hook that can be added in a Nitro plugin. It captures an error and sends it to Sentry.
*/
export async function sentryCaptureErrorHook(error: Error, errorContext: CapturedErrorContext): Promise<void> {
const sentryClient = getClient();
const sentryClientOptions = sentryClient?.getOptions();

if (
sentryClientOptions &&
'enableNitroErrorHandler' in sentryClientOptions &&
sentryClientOptions.enableNitroErrorHandler === false
) {
return;
}

// Do not handle 404 and 422
if (error instanceof H3Error) {
// Do not report if status code is 3xx or 4xx
if (error.statusCode >= 300 && error.statusCode < 500) {
return;
}
}

const { method, path } = {
method: errorContext.event?._method ? errorContext.event._method : '',
path: errorContext.event?._path ? errorContext.event._path : null,
};

if (path) {
getCurrentScope().setTransactionName(`${method} ${path}`);
}

const structuredContext = extractErrorContext(errorContext);

captureException(error, {
captureContext: { contexts: { nuxt: structuredContext } },
mechanism: { handled: false },
});

await flushIfServerless();
}
2 changes: 2 additions & 0 deletions packages/nuxt/src/runtime/plugins/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// fixme: Can this be exported like this?
export { sentryCloudflareNitroPlugin } from './sentry-cloudflare.server';
155 changes: 155 additions & 0 deletions packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import type { ExecutionContext, IncomingRequestCfProperties } from '@cloudflare/workers-types';
import type { CloudflareOptions } from '@sentry/cloudflare';
import { setAsyncLocalStorageAsyncContextStrategy, wrapRequestHandler } from '@sentry/cloudflare';
import { getDefaultIsolationScope, getIsolationScope, getTraceData, logger } from '@sentry/core';
import type { H3Event } from 'h3';
import type { NitroApp, NitroAppPlugin } from 'nitropack';
import type { NuxtRenderHTMLContext } from 'nuxt/app';
import { sentryCaptureErrorHook } from '../hooks/captureErrorHook';
import { addSentryTracingMetaTags } from '../utils';

interface CfEventType {
protocol: string;
host: string;
method: string;
headers: Record<string, string>;
context: {
cf: {
httpProtocol?: string;
country?: string;
// ...other CF properties
};
cloudflare: {
context: ExecutionContext;
request?: Record<string, unknown>;
env?: Record<string, unknown>;
};
};
}

function isEventType(event: unknown): event is CfEventType {
if (event === null || typeof event !== 'object') return false;

return (
// basic properties
'protocol' in event &&
'host' in event &&
typeof event.protocol === 'string' &&
typeof event.host === 'string' &&
// context property
'context' in event &&
typeof event.context === 'object' &&
event.context !== null &&
// context.cf properties
'cf' in event.context &&
typeof event.context.cf === 'object' &&
event.context.cf !== null &&
// context.cloudflare properties
'cloudflare' in event.context &&
typeof event.context.cloudflare === 'object' &&
event.context.cloudflare !== null &&
'context' in event.context.cloudflare
);
}

/**
* Sentry Cloudflare Nitro plugin for when using the "cloudflare-pages" preset in Nuxt.
* This plugin automatically sets up Sentry error monitoring and performance tracking for Cloudflare Pages projects.
*
* Instead of adding a `sentry.server.config.ts` file, export this plugin in the `server/plugins` directory
* with the necessary Sentry options to enable Sentry for your Cloudflare Pages project.
*
*
* @example Basic usage
* ```ts
* // nitro/plugins/sentry.ts
* import { defineNitroPlugin } from '#imports'
* import { sentryCloudflareNitroPlugin } from '@sentry/nuxt/module/plugins'
*
* export default defineNitroPlugin(sentryCloudflareNitroPlugin({
* dsn: 'https://[email protected]/0',
* tracesSampleRate: 1.0,
* }));
* ```
*
* @example Dynamic configuration with nitroApp
* ```ts
* // nitro/plugins/sentry.ts
* import { defineNitroPlugin } from '#imports'
* import { sentryCloudflareNitroPlugin } from '@sentry/nuxt/module/plugins'
*
* export default defineNitroPlugin(sentryCloudflareNitroPlugin(nitroApp => ({
* dsn: 'https://[email protected]/0',
* debug: nitroApp.h3App.options.debug
* })));
* ```
*/
export const sentryCloudflareNitroPlugin =
(optionsOrFn: CloudflareOptions | ((nitroApp: NitroApp) => CloudflareOptions)): NitroAppPlugin =>
(nitroApp: NitroApp): void => {
const traceDataMap = new WeakMap<object, ReturnType<typeof getTraceData>>();

nitroApp.localFetch = new Proxy(nitroApp.localFetch, {
async apply(handlerTarget, handlerThisArg, handlerArgs: [string, unknown]) {
setAsyncLocalStorageAsyncContextStrategy();

const cloudflareOptions = typeof optionsOrFn === 'function' ? optionsOrFn(nitroApp) : optionsOrFn;
const pathname = handlerArgs[0];
const event = handlerArgs[1];

if (!isEventType(event)) {
logger.log("Nitro Cloudflare plugin did not detect a Cloudflare event type. Won't patch Cloudflare handler.");
return handlerTarget.apply(handlerThisArg, handlerArgs);
} else {
// Usually, the protocol already includes ":"
const url = `${event.protocol}${event.protocol.endsWith(':') ? '' : ':'}//${event.host}${pathname}`;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: it doesn't seem like we are using pathname more than once, we may as well use the handler argument directly 😉

Suggested change
const url = `${event.protocol}${event.protocol.endsWith(':') ? '' : ':'}//${event.host}${pathname}`;
const url = `${event.protocol}${event.protocol.endsWith(':') ? '' : ':'}//${event.host}${handlerArgs[0]}`;

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's very valid but I added the variables on purpose so it's easier to read and understand :)
It's not very clear that this first array element is the pathname and with the variable it's more obvious.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I totally get you here.
It's especially relevant in case we want to use the path name in the future. Again I was just being nitpicky here 😁

const request = new Request(url, {
method: event.method,
headers: event.headers,
cf: event.context.cf,
}) as Request<unknown, IncomingRequestCfProperties<unknown>>;

const requestHandlerOptions = {
options: cloudflareOptions,
request,
context: event.context.cloudflare.context,
};

return wrapRequestHandler(requestHandlerOptions, () => {
const isolationScope = getIsolationScope();
const newIsolationScope =
isolationScope === getDefaultIsolationScope() ? isolationScope.clone() : isolationScope;

const traceData = getTraceData();
if (traceData && Object.keys(traceData).length > 0) {
// Storing trace data in the WeakMap using event.context.cf as key for later use in HTML meta-tags
traceDataMap.set(event.context.cf, traceData);
logger.log('Stored trace data for later use in HTML meta-tags: ', traceData);
}

logger.log(
`Patched Cloudflare handler (\`nitroApp.localFetch\`). ${
isolationScope === newIsolationScope ? 'Using existing' : 'Created new'
} isolation scope.`,
);

return handlerTarget.apply(handlerThisArg, handlerArgs);
});
}
},
});

// @ts-expect-error - 'render:html' is a valid hook name in the Nuxt context
nitroApp.hooks.hook('render:html', (html: NuxtRenderHTMLContext, { event }: { event: H3Event }) => {
const storedTraceData = event?.context?.cf ? traceDataMap.get(event.context.cf) : undefined;

if (storedTraceData && Object.keys(storedTraceData).length > 0) {
logger.log('Using stored trace data for HTML meta-tags: ', storedTraceData);
addSentryTracingMetaTags(html.head, storedTraceData);
} else {
addSentryTracingMetaTags(html.head);
}
});

nitroApp.hooks.hook('error', sentryCaptureErrorHook);
};
83 changes: 5 additions & 78 deletions packages/nuxt/src/runtime/plugins/sentry.server.ts
Original file line number Diff line number Diff line change
@@ -1,96 +1,23 @@
import {
flush,
getDefaultIsolationScope,
getIsolationScope,
GLOBAL_OBJ,
logger,
vercelWaitUntil,
withIsolationScope,
} from '@sentry/core';
import * as SentryNode from '@sentry/node';
import { getDefaultIsolationScope, getIsolationScope, logger, withIsolationScope } from '@sentry/core';
// eslint-disable-next-line import/no-extraneous-dependencies
import { type EventHandler, H3Error } from 'h3';
import { type EventHandler } from 'h3';
// eslint-disable-next-line import/no-extraneous-dependencies
import { defineNitroPlugin } from 'nitropack/runtime';
import type { NuxtRenderHTMLContext } from 'nuxt/app';
import { addSentryTracingMetaTags, extractErrorContext } from '../utils';
import { sentryCaptureErrorHook } from '../hooks/captureErrorHook';
import { addSentryTracingMetaTags, flushIfServerless } from '../utils';

export default defineNitroPlugin(nitroApp => {
nitroApp.h3App.handler = patchEventHandler(nitroApp.h3App.handler);

nitroApp.hooks.hook('error', async (error, errorContext) => {
const sentryClient = SentryNode.getClient();
const sentryClientOptions = sentryClient?.getOptions();

if (
sentryClientOptions &&
'enableNitroErrorHandler' in sentryClientOptions &&
sentryClientOptions.enableNitroErrorHandler === false
) {
return;
}

// Do not handle 404 and 422
if (error instanceof H3Error) {
// Do not report if status code is 3xx or 4xx
if (error.statusCode >= 300 && error.statusCode < 500) {
return;
}
}

const { method, path } = {
method: errorContext.event?._method ? errorContext.event._method : '',
path: errorContext.event?._path ? errorContext.event._path : null,
};

if (path) {
SentryNode.getCurrentScope().setTransactionName(`${method} ${path}`);
}

const structuredContext = extractErrorContext(errorContext);

SentryNode.captureException(error, {
captureContext: { contexts: { nuxt: structuredContext } },
mechanism: { handled: false },
});

await flushIfServerless();
});
nitroApp.hooks.hook('error', sentryCaptureErrorHook);

// @ts-expect-error - 'render:html' is a valid hook name in the Nuxt context
nitroApp.hooks.hook('render:html', (html: NuxtRenderHTMLContext) => {
addSentryTracingMetaTags(html.head);
});
});

async function flushIfServerless(): Promise<void> {
const isServerless =
!!process.env.FUNCTIONS_WORKER_RUNTIME || // Azure Functions
!!process.env.LAMBDA_TASK_ROOT || // AWS Lambda
!!process.env.VERCEL ||
!!process.env.NETLIFY;

// @ts-expect-error This is not typed
if (GLOBAL_OBJ[Symbol.for('@vercel/request-context')]) {
vercelWaitUntil(flushWithTimeout());
} else if (isServerless) {
await flushWithTimeout();
}
}

async function flushWithTimeout(): Promise<void> {
const sentryClient = SentryNode.getClient();
const isDebug = sentryClient ? sentryClient.getOptions().debug : false;

try {
isDebug && logger.log('Flushing events...');
await flush(2000);
isDebug && logger.log('Done flushing events');
} catch (e) {
isDebug && logger.log('Error while flushing events:\n', e);
}
}

function patchEventHandler(handler: EventHandler): EventHandler {
return new Proxy(handler, {
async apply(handlerTarget, handlerThisArg, handlerArgs: Parameters<EventHandler>) {
Expand Down
Loading
Loading