@honeybadger-io/nextjs 5.11.6 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +5 -42
  2. package/dist/capture-request-error.d.ts +35 -0
  3. package/dist/capture-request-error.test.d.ts +2 -0
  4. package/dist/capture-router-transition-start.d.ts +21 -0
  5. package/dist/capture-router-transition-start.test.d.ts +2 -0
  6. package/dist/client.d.ts +2 -0
  7. package/dist/copy-config-files.js +106 -34
  8. package/dist/copy-config-files.js.map +1 -1
  9. package/dist/edge.d.ts +2 -1
  10. package/dist/flush.d.ts +24 -0
  11. package/dist/honeybadger-nextjs-client.cjs.js +39 -0
  12. package/dist/honeybadger-nextjs-client.cjs.js.map +1 -0
  13. package/dist/honeybadger-nextjs-client.esm.js +31 -0
  14. package/dist/honeybadger-nextjs-client.esm.js.map +1 -0
  15. package/dist/honeybadger-nextjs-edge.cjs.js +333 -239
  16. package/dist/honeybadger-nextjs-edge.cjs.js.map +1 -1
  17. package/dist/honeybadger-nextjs-edge.esm.js +330 -239
  18. package/dist/honeybadger-nextjs-edge.esm.js.map +1 -1
  19. package/dist/honeybadger-nextjs.cjs.js +852 -386
  20. package/dist/honeybadger-nextjs.cjs.js.map +1 -1
  21. package/dist/honeybadger-nextjs.esm.js +846 -385
  22. package/dist/honeybadger-nextjs.esm.js.map +1 -1
  23. package/dist/index.d.ts +5 -2
  24. package/dist/insights-instrumentation.d.ts +30 -2
  25. package/dist/insights.d.ts +72 -0
  26. package/dist/insights.test.d.ts +2 -0
  27. package/dist/query-filters.test.d.ts +2 -0
  28. package/dist/setup.d.ts +11 -0
  29. package/dist/setup.test.d.ts +2 -0
  30. package/dist/source-maps.d.ts +55 -0
  31. package/dist/source-maps.test.d.ts +2 -0
  32. package/dist/types.d.ts +20 -8
  33. package/package.json +34 -12
  34. package/src/capture-request-error.test.ts +261 -0
  35. package/src/capture-request-error.ts +107 -0
  36. package/src/capture-router-transition-start.test.ts +44 -0
  37. package/src/capture-router-transition-start.ts +37 -0
  38. package/src/client.ts +4 -0
  39. package/src/copy-config-files.test.ts +250 -16
  40. package/src/copy-config-files.ts +117 -34
  41. package/src/edge.ts +12 -1
  42. package/src/flush.ts +58 -0
  43. package/src/index.ts +7 -2
  44. package/src/insights-instrumentation.ts +104 -11
  45. package/src/insights.test.ts +192 -0
  46. package/src/insights.ts +225 -0
  47. package/src/query-filters.test.ts +67 -0
  48. package/src/setup.test.ts +214 -0
  49. package/src/setup.ts +172 -0
  50. package/src/source-maps.test.ts +803 -0
  51. package/src/source-maps.ts +515 -0
  52. package/src/types.ts +38 -21
  53. package/templates/_error.js +14 -10
  54. package/templates/_error_app_router.js +1 -1
  55. package/templates/_error_app_router.tsx +1 -1
  56. package/templates/honeybadger.server.config.js +5 -16
  57. package/templates/instrumentation-client.js +21 -0
  58. package/templates/instrumentation.js +29 -0
  59. package/dist/webpack.d.ts +0 -3
  60. package/dist/with-honeybadger.d.ts +0 -32
  61. package/dist/with-honeybadger.test.d.ts +0 -2
  62. package/src/webpack.ts +0 -228
  63. package/src/with-honeybadger.test.ts +0 -527
  64. package/src/with-honeybadger.ts +0 -286
  65. package/templates/honeybadger.browser.config.js +0 -13
  66. package/templates/honeybadger.edge.config.js +0 -13
@@ -0,0 +1,261 @@
1
+ import Honeybadger from '@honeybadger-io/js'
2
+ import { captureRequestError } from './capture-request-error'
3
+ import type { RequestErrorContext, RequestErrorRequest } from './capture-request-error'
4
+
5
+ // Mutable so a test can install or remove the active span. @opentelemetry/api is an
6
+ // optional peer that `activeSpanIds` imports on demand, so this stands in for it.
7
+ const otelMocks: { spanContext?: { traceId: string; spanId: string } } = {}
8
+ jest.mock('@opentelemetry/api', () => ({
9
+ trace: {
10
+ getActiveSpan: () =>
11
+ otelMocks.spanContext ? { spanContext: () => otelMocks.spanContext } : undefined,
12
+ },
13
+ }))
14
+
15
+ // Mutable so a test can install or remove `after` without reloading the module:
16
+ // scheduleFlush reads nextServer.after at call time through the namespace.
17
+ const nextServerMocks: { after?: (cb: () => unknown) => void } = {}
18
+ jest.mock('next/server', () => {
19
+ const actual = jest.requireActual('next/server') as Record<string, unknown>
20
+ return {
21
+ ...actual,
22
+ get after() {
23
+ return nextServerMocks.after
24
+ },
25
+ }
26
+ })
27
+
28
+ function request(headers: RequestErrorRequest['headers'] = {}): RequestErrorRequest {
29
+ return { path: '/api/hello?x=1', method: 'POST', headers }
30
+ }
31
+
32
+ function errorContext(overrides: Partial<RequestErrorContext> = {}): RequestErrorContext {
33
+ return {
34
+ routerKind: 'App Router',
35
+ routePath: '/api/hello',
36
+ routeType: 'route',
37
+ ...overrides,
38
+ }
39
+ }
40
+
41
+ describe('captureRequestError', () => {
42
+ let notifyAsync: jest.SpyInstance
43
+ let flushAsync: jest.SpyInstance
44
+ let setEventContext: jest.SpyInstance
45
+
46
+ const noticeContext = () => notifyAsync.mock.calls[0][1].context as Record<string, unknown>
47
+
48
+ beforeEach(() => {
49
+ otelMocks.spanContext = undefined
50
+ nextServerMocks.after = undefined
51
+ Honeybadger.configure({ apiKey: 'test-key' })
52
+ notifyAsync = jest.spyOn(Honeybadger, 'notifyAsync').mockResolvedValue(undefined as never)
53
+ flushAsync = jest.spyOn(Honeybadger, 'flushAsync').mockResolvedValue(true as never)
54
+ setEventContext = jest.spyOn(Honeybadger, 'setEventContext')
55
+ })
56
+
57
+ afterEach(() => {
58
+ jest.restoreAllMocks()
59
+ })
60
+
61
+ it('reports the error with the request and route context', async () => {
62
+ const error = new Error('boom')
63
+
64
+ await captureRequestError(error, request(), errorContext())
65
+
66
+ expect(notifyAsync).toHaveBeenCalledTimes(1)
67
+ expect(notifyAsync.mock.calls[0][0]).toBe(error)
68
+ expect(noticeContext()).toMatchObject({
69
+ path: '/api/hello',
70
+ method: 'POST',
71
+ router_kind: 'App Router',
72
+ route_path: '/api/hello',
73
+ route_type: 'route',
74
+ })
75
+ })
76
+
77
+ // `filters` never apply to context, so the query string must not be repeated there. The
78
+ // full path goes on `url`, which core runs through `filterUrl` when building the payload.
79
+ it('keeps the query string out of the context and puts the full path on the url', async () => {
80
+ await captureRequestError(new Error('boom'), request(), errorContext())
81
+
82
+ expect(noticeContext().path).toEqual('/api/hello')
83
+ expect(notifyAsync.mock.calls[0][1].url).toEqual('/api/hello?x=1')
84
+ })
85
+
86
+ it('reports a path that has no query string unchanged', async () => {
87
+ await captureRequestError(new Error('boom'), { ...request(), path: '/api/hello' }, errorContext())
88
+
89
+ expect(noticeContext().path).toEqual('/api/hello')
90
+ expect(notifyAsync.mock.calls[0][1].url).toEqual('/api/hello')
91
+ })
92
+
93
+ it('schedules a flush so the report survives a frozen invocation', async () => {
94
+ await captureRequestError(new Error('boom'), request(), errorContext())
95
+
96
+ expect(flushAsync).toHaveBeenCalled()
97
+ })
98
+
99
+ it('prefers Next.js after() to deliver the report off the response path', async () => {
100
+ const afterCallbacks: Array<() => unknown> = []
101
+ nextServerMocks.after = (cb) => { afterCallbacks.push(cb) }
102
+
103
+ await captureRequestError(new Error('boom'), request(), errorContext())
104
+
105
+ expect(afterCallbacks).toHaveLength(1)
106
+ // deferred, not run inline
107
+ expect(flushAsync).not.toHaveBeenCalled()
108
+ await afterCallbacks[0]()
109
+ expect(flushAsync).toHaveBeenCalled()
110
+ })
111
+
112
+ // Regression guard. Writing ids to the event context here landed on a store shared by
113
+ // the whole process or isolate, because this runs outside any Honeybadger.run(), so the
114
+ // ids leaked into later requests' events.
115
+ it('never writes to the shared event context', async () => {
116
+ await captureRequestError(
117
+ new Error('boom'),
118
+ request({ 'x-request-id': 'req-1', 'x-correlation-id': 'corr-1' }),
119
+ errorContext()
120
+ )
121
+
122
+ expect(setEventContext).not.toHaveBeenCalled()
123
+ })
124
+
125
+ describe('Next.js control-flow errors', () => {
126
+ // redirect(), notFound(), forbidden() and unauthorized() are implemented by throwing,
127
+ // and the framework catches them upstream. Reporting them would turn every redirect
128
+ // into a fault.
129
+ it.each([
130
+ ['NEXT_REDIRECT;replace;/login;307;', 'redirect()'],
131
+ ['NEXT_NOT_FOUND', 'notFound()'],
132
+ ['NEXT_HTTP_ERROR_FALLBACK;403', 'forbidden()'],
133
+ ])('ignores %s (%s)', async (digest) => {
134
+ const error = Object.assign(new Error('control flow'), { digest })
135
+
136
+ await captureRequestError(error, request(), errorContext())
137
+
138
+ expect(notifyAsync).not.toHaveBeenCalled()
139
+ })
140
+
141
+ it('still reports a genuine error that carries a React digest', async () => {
142
+ // React tags real errors with an opaque hash, which must not be mistaken for a
143
+ // framework signal.
144
+ const error = Object.assign(new Error('boom'), { digest: '1234567890' })
145
+
146
+ await captureRequestError(error, request(), errorContext())
147
+
148
+ expect(notifyAsync).toHaveBeenCalledTimes(1)
149
+ })
150
+
151
+ it('reports errors whose digest is not a string', async () => {
152
+ const error = Object.assign(new Error('boom'), { digest: 42 })
153
+
154
+ await captureRequestError(error, request(), errorContext())
155
+
156
+ expect(notifyAsync).toHaveBeenCalledTimes(1)
157
+ })
158
+ })
159
+
160
+ describe('request and correlation ids', () => {
161
+ it('reuses the ids from the request headers', async () => {
162
+ await captureRequestError(
163
+ new Error('boom'),
164
+ request({ 'x-request-id': 'req-1', 'x-correlation-id': 'corr-1' }),
165
+ errorContext()
166
+ )
167
+
168
+ expect(noticeContext()).toMatchObject({ request_id: 'req-1', correlation_id: 'corr-1' })
169
+ })
170
+
171
+ it('generates a request id when no header carries one', async () => {
172
+ await captureRequestError(new Error('boom'), request(), errorContext())
173
+
174
+ const { request_id: requestId, correlation_id: correlationId } = noticeContext()
175
+ expect(typeof requestId).toBe('string')
176
+ expect(requestId).toBeTruthy()
177
+ // With nothing to correlate against, the correlation id falls back to the request id.
178
+ expect(correlationId).toBe(requestId)
179
+ })
180
+
181
+ it('reuses a correlation id without a request id header', async () => {
182
+ await captureRequestError(
183
+ new Error('boom'),
184
+ request({ 'x-correlation-id': 'corr-1' }),
185
+ errorContext()
186
+ )
187
+
188
+ const { request_id: requestId, correlation_id: correlationId } = noticeContext()
189
+ expect(correlationId).toBe('corr-1')
190
+ expect(requestId).not.toBe('corr-1')
191
+ })
192
+
193
+ it('handles header names case-insensitively and array values', async () => {
194
+ await captureRequestError(
195
+ new Error('boom'),
196
+ request({ 'X-Request-ID': ['req-first', 'req-second'] }),
197
+ errorContext()
198
+ )
199
+
200
+ expect(noticeContext().request_id).toBe('req-first')
201
+ })
202
+ })
203
+
204
+ // The ids the user asked for: request_id unique per request, correlation_id reused from a
205
+ // header when present, and the span and trace ids alongside both.
206
+ describe('OpenTelemetry ids', () => {
207
+ const span = { traceId: '29496aaa5aa2a425827813e30a29eba5', spanId: '1d52951d61351ebc' }
208
+
209
+ it('carries the active span and trace ids', async () => {
210
+ otelMocks.spanContext = span
211
+
212
+ await captureRequestError(new Error('boom'), request(), errorContext())
213
+
214
+ expect(noticeContext()).toMatchObject({ trace_id: span.traceId, span_id: span.spanId })
215
+ })
216
+
217
+ // Next.js still has the request span active in this hook, and it is the same span the
218
+ // Insights processor maps to `request.handled` — so seeding both from it is what lets a
219
+ // fault be joined to its request's events.
220
+ it('falls back to the span ids for request_id and correlation_id', async () => {
221
+ otelMocks.spanContext = span
222
+
223
+ await captureRequestError(new Error('boom'), request(), errorContext())
224
+
225
+ expect(noticeContext()).toMatchObject({
226
+ request_id: span.spanId,
227
+ correlation_id: span.traceId,
228
+ })
229
+ })
230
+
231
+ it('still prefers the headers over the span', async () => {
232
+ otelMocks.spanContext = span
233
+
234
+ await captureRequestError(
235
+ new Error('boom'),
236
+ request({ 'x-request-id': 'from-header', 'x-correlation-id': 'correlate-me' }),
237
+ errorContext()
238
+ )
239
+
240
+ expect(noticeContext()).toMatchObject({
241
+ request_id: 'from-header',
242
+ correlation_id: 'correlate-me',
243
+ // ...and the span ids are still reported, so the trace remains reachable.
244
+ trace_id: span.traceId,
245
+ span_id: span.spanId,
246
+ })
247
+ })
248
+
249
+ // @opentelemetry/api is optional, and no span is active unless a provider is registered.
250
+ it('omits both when no span is active', async () => {
251
+ otelMocks.spanContext = undefined
252
+
253
+ await captureRequestError(new Error('boom'), request(), errorContext())
254
+
255
+ const context = noticeContext()
256
+ expect(context.trace_id).toBeUndefined()
257
+ expect(context.span_id).toBeUndefined()
258
+ expect(context.request_id).toEqual(expect.any(String))
259
+ })
260
+ })
261
+ })
@@ -0,0 +1,107 @@
1
+ import Honeybadger from '@honeybadger-io/js';
2
+ import { scheduleFlush } from './flush';
3
+ import { activeSpanIds, seedNodeRequestEventContext } from './insights-instrumentation';
4
+ import type { NodeHeaders } from './insights-instrumentation';
5
+
6
+ /**
7
+ * The shape Next.js passes to `onRequestError`. Declared locally rather than imported
8
+ * from `next` so this module carries no type-only dependency on the router types, which
9
+ * differ across the supported Next.js range. `headers` is a Node-style bag, which is
10
+ * exactly `NodeHeaders`, so the existing header reader and the `request_id` /
11
+ * `correlation_id` precedence are reused as-is.
12
+ */
13
+ export type RequestErrorRequest = {
14
+ path: string
15
+ method: string
16
+ headers: NodeHeaders
17
+ }
18
+
19
+ export type RequestErrorContext = {
20
+ routerKind: string
21
+ routePath: string
22
+ routeType: string
23
+ renderSource?: string
24
+ revalidateReason?: string
25
+ renderType?: string
26
+ }
27
+
28
+ /**
29
+ * Next.js uses thrown errors for control flow: `redirect()`, `notFound()`,
30
+ * `forbidden()` and `unauthorized()` all throw an error carrying a `digest`
31
+ * string (`NEXT_REDIRECT;...`, `NEXT_NOT_FOUND`, `NEXT_HTTP_ERROR_FALLBACK;...`).
32
+ * These are not real failures — the framework catches them upstream to produce
33
+ * the redirect/404/etc. — so we must let them pass without reporting, otherwise
34
+ * every redirect shows up as an error in Honeybadger.
35
+ *
36
+ * We match on the `NEXT_` prefix rather than an exhaustive list so that any
37
+ * present or future framework control-flow digest is covered. This is safe:
38
+ * genuine errors that React tags with a `digest` use an opaque hash, and other
39
+ * Next.js bailout signals (e.g. `BAILOUT_TO_CLIENT_SIDE_RENDERING`,
40
+ * `DYNAMIC_SERVER_USAGE`) are not `NEXT_`-prefixed, so neither is skipped.
41
+ */
42
+ function isNextControlFlowError(error: unknown): boolean {
43
+ const digest = (error as { digest?: unknown } | null | undefined)?.digest
44
+ return typeof digest === 'string' && digest.startsWith('NEXT_')
45
+ }
46
+
47
+ /**
48
+ * The path with any query string removed.
49
+ *
50
+ * Next.js reports `path` with the query attached (`/blog?name=foo`), and this value is
51
+ * written to the user's context, which `filters` never touch.
52
+ */
53
+ function requestPath(path: string): string {
54
+ return typeof path === 'string' ? path.split('?')[0] : path
55
+ }
56
+
57
+ /**
58
+ * Reports errors passed to Next.js's `onRequestError` instrumentation hook.
59
+ *
60
+ * Wire it up in `instrumentation.ts`:
61
+ *
62
+ * ```ts
63
+ * export const onRequestError = captureRequestError
64
+ * ```
65
+ *
66
+ * Reaches Server Components, Route Handlers, Server Actions and middleware, and receives
67
+ * the real error rather than the generic message Next.js hands to an error component.
68
+ */
69
+ export async function captureRequestError(
70
+ error: unknown,
71
+ request: RequestErrorRequest,
72
+ context: RequestErrorContext
73
+ ): Promise<void> {
74
+ if (isNextControlFlowError(error)) {
75
+ return
76
+ }
77
+
78
+ // Same header precedence *and* the same span as the Insights path, so a fault and the
79
+ // events from the request it failed in carry matching ids. Next.js still has the request
80
+ // span active when it calls this hook, and it is the very span the Insights processor
81
+ // maps to `request.handled` — so with no id headers present all four ids are identical on
82
+ // both, and the fault joins its request's events and trace.
83
+ //
84
+ // Deliberately not written to the event context: outside a `Honeybadger.run()` that
85
+ // lands on a store shared by the whole process or isolate, so the ids would leak into
86
+ // later requests' events. `onRequestError` also fires after the request has already
87
+ // failed, so it is too late to decorate that request's own events anyway.
88
+ const ids = seedNodeRequestEventContext(request.headers, await activeSpanIds())
89
+
90
+ await Honeybadger.notifyAsync(error as Error, {
91
+ // The full path, query string included, goes on `url` so the configured `filters` are
92
+ // applied to it -- `filterUrl` runs over this field when the payload is built. Context
93
+ // is deliberately never filtered, since it is the user's own bag, so the copy below is
94
+ // reduced to the bare path rather than repeating an unfiltered query string there.
95
+ url: request.path,
96
+ context: {
97
+ ...ids,
98
+ path: requestPath(request.path),
99
+ method: request.method,
100
+ router_kind: context.routerKind,
101
+ route_path: context.routePath,
102
+ route_type: context.routeType,
103
+ },
104
+ })
105
+
106
+ await scheduleFlush({ useAfter: true })
107
+ }
@@ -0,0 +1,44 @@
1
+ import Honeybadger from '@honeybadger-io/js'
2
+ import { captureRouterTransitionStart } from './capture-router-transition-start'
3
+
4
+ describe('captureRouterTransitionStart', () => {
5
+ let addBreadcrumb: jest.SpyInstance
6
+
7
+ beforeEach(() => {
8
+ addBreadcrumb = jest.spyOn(Honeybadger, 'addBreadcrumb').mockReturnValue(Honeybadger)
9
+ })
10
+
11
+ afterEach(() => {
12
+ jest.restoreAllMocks()
13
+ })
14
+
15
+ const opts = () => addBreadcrumb.mock.calls[0][1]
16
+ const message = () => addBreadcrumb.mock.calls[0][0]
17
+
18
+ it('records the navigation as a breadcrumb', () => {
19
+ captureRouterTransitionStart('/dashboard', 'push')
20
+
21
+ expect(addBreadcrumb).toHaveBeenCalledTimes(1)
22
+ expect(message()).toEqual('Navigated to /dashboard')
23
+ expect(opts()).toEqual({
24
+ category: 'navigation',
25
+ metadata: { url: '/dashboard', navigationType: 'push' },
26
+ })
27
+ })
28
+
29
+ // The message is not filtered anywhere -- `filterBreadcrumbs` only reaches metadata -- so
30
+ // the query string must not be interpolated into it. The full url stays in the metadata,
31
+ // where the configured `filters` are applied when the payload is built.
32
+ it('keeps the query string out of the message and leaves it in the metadata', () => {
33
+ captureRouterTransitionStart('/checkout?token=abc&step=2', 'replace')
34
+
35
+ expect(message()).toEqual('Navigated to /checkout')
36
+ expect(opts().metadata.url).toEqual('/checkout?token=abc&step=2')
37
+ })
38
+
39
+ it('carries the navigation type through', () => {
40
+ captureRouterTransitionStart('/back', 'traverse')
41
+
42
+ expect(opts().metadata.navigationType).toEqual('traverse')
43
+ })
44
+ })
@@ -0,0 +1,37 @@
1
+ // Deliberately @honeybadger-io/js, not @honeybadger-io/react. The react package re-exports
2
+ // this exact singleton, but reaching it through there also pulls in the error-boundary class
3
+ // component — and this module sits in the main barrel that `instrumentation.ts` imports on
4
+ // the server, where React Server Components reject a class component outright under
5
+ // Turbopack.
6
+ import Honeybadger from '@honeybadger-io/js';
7
+
8
+ /**
9
+ * Navigation types Next.js reports for an App Router transition.
10
+ */
11
+ export type RouterTransitionType = 'push' | 'replace' | 'traverse'
12
+
13
+ /**
14
+ * Records App Router navigations as breadcrumbs, so a fault carries the trail of routes
15
+ * the user visited before it.
16
+ *
17
+ * Wire it up in `instrumentation-client.ts`:
18
+ *
19
+ * ```ts
20
+ * export const onRouterTransitionStart = captureRouterTransitionStart
21
+ * ```
22
+ *
23
+ * Exported as a ready-made handler rather than left as a function for the template to
24
+ * declare, so the generated file works unchanged as both `.js` and `.ts` — an assignment
25
+ * has no parameters to annotate, so there is no implicit `any` for `noImplicitAny` to
26
+ * reject.
27
+ */
28
+ export function captureRouterTransitionStart(url: string, navigationType: RouterTransitionType): void {
29
+ // The message carries the path alone and the full URL goes in the metadata, where the
30
+ // configured `filters` are applied to its query string when the payload is built. This is
31
+ // the same split the browser integration already uses for its XHR and fetch breadcrumbs,
32
+ // whose messages are built from `localURLPathname`.
33
+ Honeybadger.addBreadcrumb(`Navigated to ${url.split('?')[0]}`, {
34
+ category: 'navigation',
35
+ metadata: { url, navigationType },
36
+ })
37
+ }
package/src/client.ts ADDED
@@ -0,0 +1,4 @@
1
+ // Browser bundle: only what `instrumentation-client` needs. Kept separate so a client
2
+ // bundle does not pull in the server hooks — `flush` imports `next/server` at the top
3
+ // level, which would otherwise ship NextRequest/NextResponse to every visitor.
4
+ export * from './capture-router-transition-start'