-
-
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 all 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
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'; |
155 changes: 155 additions & 0 deletions
155
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,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}`; | ||
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); | ||
}; |
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.
nit: it doesn't seem like we are using
pathname
more than once, we may as well use the handler argument directly 😉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.
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.
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 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 😁