-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
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
Changes from 15 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
911e298
feat(nuxt): Add Cloudflare Nitro plugin
s1gr1d 06f7a7c
sort imports
s1gr1d d5b7d81
import from core, not node
s1gr1d f11be16
better cloudflare plugin
s1gr1d 0800086
add some todo comments for trace propagation
s1gr1d efd33a4
Add continous tracing FR
s1gr1d f99497a
enable continuing from propagation context
s1gr1d 983752a
add tests
s1gr1d 761af2c
add todo
s1gr1d 55f1bd2
put option to requesthandler option
s1gr1d 95d162e
switch if statement
s1gr1d 5085e58
delete stuff
s1gr1d 3ccab0c
delete continueTraceFromPropagationContext
s1gr1d a86f1f0
reset code in cloudflare SDK
s1gr1d 56c1fc4
Merge branch 'develop' into sig/nuxt-cloudflare
s1gr1d e93abe2
fix type error
s1gr1d 5913937
delete `isDebug`
s1gr1d db78cd8
check for : in protocol
s1gr1d aa37922
Merge branch 'develop' into sig/nuxt-cloudflare
s1gr1d eac96b6
update yarn.lock
s1gr1d b9c9cc0
warn on double-init
s1gr1d a20ebef
Add WeakMap
s1gr1d File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; |
132 changes: 132 additions & 0 deletions
132
packages/nuxt/src/runtime/plugins/sentry-cloudflare.server.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
import type { ExecutionContext } 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; | ||
context: { | ||
cloudflare: { | ||
context: ExecutionContext; | ||
}; | ||
}; | ||
} | ||
|
||
function isEventType(event: unknown): event is CfEventType { | ||
return ( | ||
event !== null && | ||
typeof event === 'object' && | ||
'protocol' in event && | ||
'host' in event && | ||
'context' in event && | ||
typeof event.protocol === 'string' && | ||
typeof event.host === 'string' && | ||
typeof event.context === 'object' && | ||
event?.context !== null && | ||
'cloudflare' in event.context && | ||
typeof event.context.cloudflare === 'object' && | ||
event?.context.cloudflare !== null && | ||
'context' in event?.context?.cloudflare | ||
); | ||
} | ||
|
||
const TRACE_DATA_KEY = '__sentryTraceData'; | ||
|
||
/** | ||
* 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://examplePublicKey@o0.ingest.sentry.io/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://examplePublicKey@o0.ingest.sentry.io/0', | ||
* debug: nitroApp.h3App.options.debug | ||
* }))); | ||
* ``` | ||
*/ | ||
export const sentryCloudflareNitroPlugin = | ||
(optionsOrFn: CloudflareOptions | ((nitroApp: NitroApp) => CloudflareOptions)): NitroAppPlugin => | ||
(nitroApp: NitroApp): void => { | ||
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 { | ||
const requestHandlerOptions = { | ||
options: cloudflareOptions, | ||
request: { ...event, url: `${event.protocol}//${event.host}${pathname}` }, | ||
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 event context for later use in HTML meta-tags (enables correct connection of parent/child span relationships) | ||
// @ts-expect-error Storing a new key in the event context | ||
event.context[TRACE_DATA_KEY] = traceData; | ||
logger.log('Stored trace data in the event context.'); | ||
} | ||
|
||
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[TRACE_DATA_KEY] as ReturnType<typeof getTraceData> | undefined; | ||
|
||
if (storedTraceData && Object.keys(storedTraceData).length > 0) { | ||
logger.log('Using stored trace data from event context for meta tags.'); | ||
addSentryTracingMetaTags(html.head, storedTraceData); | ||
} else { | ||
addSentryTracingMetaTags(html.head); | ||
} | ||
}); | ||
|
||
nitroApp.hooks.hook('error', sentryCaptureErrorHook); | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of attaching to
event.context
, can we instead track this via aWeakMap
?So we hold a reference to
event.context
orevent
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do you mean using the event as a key?
That's a bit tricky as the event in
localFetch
is a full Cloudflare event which A LOT of data. And the event in therender:html
hook is only a string (e.g."[GET] /"
). So I cannot get the value out of the WeakMap anymore, as I don't have a key anymore. Or would you have an idea on how to do that?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I saw that
context.cf
is available in both and looks the same. Using a WeakMap now: a20ebef