-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
feat(nextjs): Auto-wrap edge-routes and middleware #6746
Changes from 7 commits
6f4b028
416a7c8
a7c103d
487eee2
918e831
2791323
a1bf405
b7f5511
7889dbc
26f154d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
/* | ||
* This file is a template for the code which will be substituted when our webpack loader handles middleware files. | ||
* | ||
* We use `__SENTRY_WRAPPING_TARGET__` as a placeholder for the path to the file being wrapped. Because it's not a real package, | ||
* this causes both TS and ESLint to complain, hence the pragma comments below. | ||
*/ | ||
|
||
// @ts-ignore See above | ||
// eslint-disable-next-line import/no-unresolved | ||
import * as origModule from '__SENTRY_WRAPPING_TARGET__'; | ||
// eslint-disable-next-line import/no-extraneous-dependencies | ||
import * as Sentry from '@sentry/nextjs'; | ||
|
||
import type { EdgeRouteHandler } from '../../edge/types'; | ||
|
||
type NextApiModule = | ||
| { | ||
// ESM export | ||
default?: EdgeRouteHandler; | ||
middleware?: EdgeRouteHandler; | ||
} | ||
// CJS export | ||
| EdgeRouteHandler; | ||
|
||
const userApiModule = origModule as NextApiModule; | ||
|
||
// Default to undefined. It's possible for Next.js users to not define any exports/handlers in an API route. If that is | ||
// the case Next.js wil crash during runtime but the Sentry SDK should definitely not crash so we need tohandle it. | ||
let userProvidedNamedHandler: EdgeRouteHandler | undefined = undefined; | ||
let userProvidedDefaultHandler: EdgeRouteHandler | undefined = undefined; | ||
|
||
if ('middleware' in userApiModule && typeof userApiModule.middleware === 'function') { | ||
// Handle when user defines via named ESM export: `export { middleware };` | ||
userProvidedNamedHandler = userApiModule.middleware; | ||
} else if ('default' in userApiModule && typeof userApiModule.default === 'function') { | ||
// Handle when user defines via ESM export: `export default myFunction;` | ||
userProvidedDefaultHandler = userApiModule.default; | ||
} else if (typeof userApiModule === 'function') { | ||
// Handle when user defines via CJS export: "module.exports = myFunction;" | ||
userProvidedDefaultHandler = userApiModule; | ||
} | ||
|
||
export const middleware = userProvidedNamedHandler ? Sentry.withSentryMiddleware(userProvidedNamedHandler) : undefined; | ||
export default userProvidedDefaultHandler ? Sentry.withSentryMiddleware(userProvidedDefaultHandler) : undefined; | ||
|
||
// Re-export anything exported by the page module we're wrapping. When processing this code, Rollup is smart enough to | ||
// not include anything whose name matchs something we've explicitly exported above. | ||
// @ts-ignore See above | ||
// eslint-disable-next-line import/no-unresolved | ||
export * from '__SENTRY_WRAPPING_TARGET__'; |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -99,23 +99,61 @@ export function constructWebpackConfigFunction( | |
|
||
if (isServer) { | ||
if (userSentryOptions.autoInstrumentServerFunctions !== false) { | ||
const pagesDir = newConfig.resolve?.alias?.['private-next-pages'] as string; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why this change? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We looked at this really obscure field with a typecast here, and I am not sure if it is even part of the Next.js public API. Behavior around the |
||
let pagesDirPath: string; | ||
if ( | ||
fs.existsSync(path.join(projectDir, 'pages')) && | ||
fs.lstatSync(path.join(projectDir, 'pages')).isDirectory() | ||
) { | ||
pagesDirPath = path.join(projectDir, 'pages'); | ||
} else { | ||
pagesDirPath = path.join(projectDir, 'src', 'pages'); | ||
} | ||
|
||
const middlewareJsPath = path.join(pagesDirPath, '..', 'middleware.js'); | ||
const middlewareTsPath = path.join(pagesDirPath, '..', 'middleware.ts'); | ||
|
||
// Default page extensions per https://github.com/vercel/next.js/blob/f1dbc9260d48c7995f6c52f8fbcc65f08e627992/packages/next/server/config-shared.ts#L161 | ||
const pageExtensions = userNextConfig.pageExtensions || ['tsx', 'ts', 'jsx', 'js']; | ||
const dotPrefixedPageExtensions = pageExtensions.map(ext => `.${ext}`); | ||
const pageExtensionRegex = pageExtensions.map(escapeStringForRegex).join('|'); | ||
|
||
// It is very important that we insert our loader at the beginning of the array because we expect any sort of transformations/transpilations (e.g. TS -> JS) to already have happened. | ||
newConfig.module.rules.unshift({ | ||
test: new RegExp(`^${escapeStringForRegex(pagesDir)}.*\\.(${pageExtensionRegex})$`), | ||
test: resourcePath => { | ||
// We generally want to apply the loader to all API routes, pages and to the middleware file. | ||
|
||
// `resourcePath` may be an absolute path or a path relative to the context of the webpack config | ||
let absoluteResourcePath: string; | ||
if (path.isAbsolute(resourcePath)) { | ||
absoluteResourcePath = resourcePath; | ||
} else { | ||
absoluteResourcePath = path.join(projectDir, resourcePath); | ||
} | ||
const normalizedAbsoluteResourcePath = path.normalize(absoluteResourcePath); | ||
|
||
if ( | ||
// Match everything inside pages/ with the appropriate file extension | ||
normalizedAbsoluteResourcePath.startsWith(pagesDirPath) && | ||
dotPrefixedPageExtensions.some(ext => normalizedAbsoluteResourcePath.endsWith(ext)) | ||
) { | ||
return true; | ||
} else if ( | ||
// Match middleware.js and middleware.ts | ||
normalizedAbsoluteResourcePath === middlewareJsPath || | ||
normalizedAbsoluteResourcePath === middlewareTsPath | ||
) { | ||
return userSentryOptions.autoInstrumentMiddleware ?? true; | ||
} else { | ||
return false; | ||
} | ||
}, | ||
use: [ | ||
{ | ||
loader: path.resolve(__dirname, 'loaders/wrappingLoader.js'), | ||
options: { | ||
pagesDir, | ||
pagesDir: pagesDirPath, | ||
pageExtensionRegex, | ||
excludeServerRoutes: userSentryOptions.excludeServerRoutes, | ||
isEdgeRuntime: buildContext.nextRuntime === 'edge', | ||
}, | ||
}, | ||
], | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
// We cannot make any assumptions about what users define as their handler except maybe that it is a function | ||
export interface EdgeRouteHandler { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
(...args: any[]): any; | ||
} |
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.
l: should we call this
__SENTRY_WRAPPING_TARGET_FILE__
to be a little more clear?