@honeybadger-io/nextjs 5.11.6 → 6.0.0

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 (62) 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/client.d.ts +2 -0
  6. package/dist/copy-config-files.js +106 -34
  7. package/dist/copy-config-files.js.map +1 -1
  8. package/dist/edge.d.ts +2 -1
  9. package/dist/flush.d.ts +24 -0
  10. package/dist/honeybadger-nextjs-client.cjs.js +35 -0
  11. package/dist/honeybadger-nextjs-client.cjs.js.map +1 -0
  12. package/dist/honeybadger-nextjs-client.esm.js +27 -0
  13. package/dist/honeybadger-nextjs-client.esm.js.map +1 -0
  14. package/dist/honeybadger-nextjs-edge.cjs.js +320 -240
  15. package/dist/honeybadger-nextjs-edge.cjs.js.map +1 -1
  16. package/dist/honeybadger-nextjs-edge.esm.js +317 -240
  17. package/dist/honeybadger-nextjs-edge.esm.js.map +1 -1
  18. package/dist/honeybadger-nextjs.cjs.js +835 -387
  19. package/dist/honeybadger-nextjs.cjs.js.map +1 -1
  20. package/dist/honeybadger-nextjs.esm.js +829 -386
  21. package/dist/honeybadger-nextjs.esm.js.map +1 -1
  22. package/dist/index.d.ts +5 -2
  23. package/dist/insights-instrumentation.d.ts +30 -2
  24. package/dist/insights.d.ts +72 -0
  25. package/dist/insights.test.d.ts +2 -0
  26. package/dist/setup.d.ts +11 -0
  27. package/dist/setup.test.d.ts +2 -0
  28. package/dist/source-maps.d.ts +55 -0
  29. package/dist/source-maps.test.d.ts +2 -0
  30. package/dist/types.d.ts +20 -8
  31. package/package.json +33 -11
  32. package/src/capture-request-error.test.ts +245 -0
  33. package/src/capture-request-error.ts +92 -0
  34. package/src/capture-router-transition-start.ts +33 -0
  35. package/src/client.ts +4 -0
  36. package/src/copy-config-files.test.ts +250 -16
  37. package/src/copy-config-files.ts +117 -34
  38. package/src/edge.ts +12 -1
  39. package/src/flush.ts +58 -0
  40. package/src/index.ts +7 -2
  41. package/src/insights-instrumentation.ts +104 -11
  42. package/src/insights.test.ts +192 -0
  43. package/src/insights.ts +225 -0
  44. package/src/setup.test.ts +214 -0
  45. package/src/setup.ts +172 -0
  46. package/src/source-maps.test.ts +803 -0
  47. package/src/source-maps.ts +515 -0
  48. package/src/types.ts +38 -21
  49. package/templates/_error.js +14 -10
  50. package/templates/_error_app_router.js +1 -1
  51. package/templates/_error_app_router.tsx +1 -1
  52. package/templates/honeybadger.server.config.js +5 -16
  53. package/templates/instrumentation-client.js +21 -0
  54. package/templates/instrumentation.js +29 -0
  55. package/dist/webpack.d.ts +0 -3
  56. package/dist/with-honeybadger.d.ts +0 -32
  57. package/dist/with-honeybadger.test.d.ts +0 -2
  58. package/src/webpack.ts +0 -228
  59. package/src/with-honeybadger.test.ts +0 -527
  60. package/src/with-honeybadger.ts +0 -286
  61. package/templates/honeybadger.browser.config.js +0 -13
  62. package/templates/honeybadger.edge.config.js +0 -13
@@ -0,0 +1,245 @@
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?x=1',
70
+ method: 'POST',
71
+ router_kind: 'App Router',
72
+ route_path: '/api/hello',
73
+ route_type: 'route',
74
+ })
75
+ })
76
+
77
+ it('schedules a flush so the report survives a frozen invocation', async () => {
78
+ await captureRequestError(new Error('boom'), request(), errorContext())
79
+
80
+ expect(flushAsync).toHaveBeenCalled()
81
+ })
82
+
83
+ it('prefers Next.js after() to deliver the report off the response path', async () => {
84
+ const afterCallbacks: Array<() => unknown> = []
85
+ nextServerMocks.after = (cb) => { afterCallbacks.push(cb) }
86
+
87
+ await captureRequestError(new Error('boom'), request(), errorContext())
88
+
89
+ expect(afterCallbacks).toHaveLength(1)
90
+ // deferred, not run inline
91
+ expect(flushAsync).not.toHaveBeenCalled()
92
+ await afterCallbacks[0]()
93
+ expect(flushAsync).toHaveBeenCalled()
94
+ })
95
+
96
+ // Regression guard. Writing ids to the event context here landed on a store shared by
97
+ // the whole process or isolate, because this runs outside any Honeybadger.run(), so the
98
+ // ids leaked into later requests' events.
99
+ it('never writes to the shared event context', async () => {
100
+ await captureRequestError(
101
+ new Error('boom'),
102
+ request({ 'x-request-id': 'req-1', 'x-correlation-id': 'corr-1' }),
103
+ errorContext()
104
+ )
105
+
106
+ expect(setEventContext).not.toHaveBeenCalled()
107
+ })
108
+
109
+ describe('Next.js control-flow errors', () => {
110
+ // redirect(), notFound(), forbidden() and unauthorized() are implemented by throwing,
111
+ // and the framework catches them upstream. Reporting them would turn every redirect
112
+ // into a fault.
113
+ it.each([
114
+ ['NEXT_REDIRECT;replace;/login;307;', 'redirect()'],
115
+ ['NEXT_NOT_FOUND', 'notFound()'],
116
+ ['NEXT_HTTP_ERROR_FALLBACK;403', 'forbidden()'],
117
+ ])('ignores %s (%s)', async (digest) => {
118
+ const error = Object.assign(new Error('control flow'), { digest })
119
+
120
+ await captureRequestError(error, request(), errorContext())
121
+
122
+ expect(notifyAsync).not.toHaveBeenCalled()
123
+ })
124
+
125
+ it('still reports a genuine error that carries a React digest', async () => {
126
+ // React tags real errors with an opaque hash, which must not be mistaken for a
127
+ // framework signal.
128
+ const error = Object.assign(new Error('boom'), { digest: '1234567890' })
129
+
130
+ await captureRequestError(error, request(), errorContext())
131
+
132
+ expect(notifyAsync).toHaveBeenCalledTimes(1)
133
+ })
134
+
135
+ it('reports errors whose digest is not a string', async () => {
136
+ const error = Object.assign(new Error('boom'), { digest: 42 })
137
+
138
+ await captureRequestError(error, request(), errorContext())
139
+
140
+ expect(notifyAsync).toHaveBeenCalledTimes(1)
141
+ })
142
+ })
143
+
144
+ describe('request and correlation ids', () => {
145
+ it('reuses the ids from the request headers', async () => {
146
+ await captureRequestError(
147
+ new Error('boom'),
148
+ request({ 'x-request-id': 'req-1', 'x-correlation-id': 'corr-1' }),
149
+ errorContext()
150
+ )
151
+
152
+ expect(noticeContext()).toMatchObject({ request_id: 'req-1', correlation_id: 'corr-1' })
153
+ })
154
+
155
+ it('generates a request id when no header carries one', async () => {
156
+ await captureRequestError(new Error('boom'), request(), errorContext())
157
+
158
+ const { request_id: requestId, correlation_id: correlationId } = noticeContext()
159
+ expect(typeof requestId).toBe('string')
160
+ expect(requestId).toBeTruthy()
161
+ // With nothing to correlate against, the correlation id falls back to the request id.
162
+ expect(correlationId).toBe(requestId)
163
+ })
164
+
165
+ it('reuses a correlation id without a request id header', async () => {
166
+ await captureRequestError(
167
+ new Error('boom'),
168
+ request({ 'x-correlation-id': 'corr-1' }),
169
+ errorContext()
170
+ )
171
+
172
+ const { request_id: requestId, correlation_id: correlationId } = noticeContext()
173
+ expect(correlationId).toBe('corr-1')
174
+ expect(requestId).not.toBe('corr-1')
175
+ })
176
+
177
+ it('handles header names case-insensitively and array values', async () => {
178
+ await captureRequestError(
179
+ new Error('boom'),
180
+ request({ 'X-Request-ID': ['req-first', 'req-second'] }),
181
+ errorContext()
182
+ )
183
+
184
+ expect(noticeContext().request_id).toBe('req-first')
185
+ })
186
+ })
187
+
188
+ // The ids the user asked for: request_id unique per request, correlation_id reused from a
189
+ // header when present, and the span and trace ids alongside both.
190
+ describe('OpenTelemetry ids', () => {
191
+ const span = { traceId: '29496aaa5aa2a425827813e30a29eba5', spanId: '1d52951d61351ebc' }
192
+
193
+ it('carries the active span and trace ids', async () => {
194
+ otelMocks.spanContext = span
195
+
196
+ await captureRequestError(new Error('boom'), request(), errorContext())
197
+
198
+ expect(noticeContext()).toMatchObject({ trace_id: span.traceId, span_id: span.spanId })
199
+ })
200
+
201
+ // Next.js still has the request span active in this hook, and it is the same span the
202
+ // Insights processor maps to `request.handled` — so seeding both from it is what lets a
203
+ // fault be joined to its request's events.
204
+ it('falls back to the span ids for request_id and correlation_id', async () => {
205
+ otelMocks.spanContext = span
206
+
207
+ await captureRequestError(new Error('boom'), request(), errorContext())
208
+
209
+ expect(noticeContext()).toMatchObject({
210
+ request_id: span.spanId,
211
+ correlation_id: span.traceId,
212
+ })
213
+ })
214
+
215
+ it('still prefers the headers over the span', async () => {
216
+ otelMocks.spanContext = span
217
+
218
+ await captureRequestError(
219
+ new Error('boom'),
220
+ request({ 'x-request-id': 'from-header', 'x-correlation-id': 'correlate-me' }),
221
+ errorContext()
222
+ )
223
+
224
+ expect(noticeContext()).toMatchObject({
225
+ request_id: 'from-header',
226
+ correlation_id: 'correlate-me',
227
+ // ...and the span ids are still reported, so the trace remains reachable.
228
+ trace_id: span.traceId,
229
+ span_id: span.spanId,
230
+ })
231
+ })
232
+
233
+ // @opentelemetry/api is optional, and no span is active unless a provider is registered.
234
+ it('omits both when no span is active', async () => {
235
+ otelMocks.spanContext = undefined
236
+
237
+ await captureRequestError(new Error('boom'), request(), errorContext())
238
+
239
+ const context = noticeContext()
240
+ expect(context.trace_id).toBeUndefined()
241
+ expect(context.span_id).toBeUndefined()
242
+ expect(context.request_id).toEqual(expect.any(String))
243
+ })
244
+ })
245
+ })
@@ -0,0 +1,92 @@
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
+ * Reports errors passed to Next.js's `onRequestError` instrumentation hook.
49
+ *
50
+ * Wire it up in `instrumentation.ts`:
51
+ *
52
+ * ```ts
53
+ * export const onRequestError = captureRequestError
54
+ * ```
55
+ *
56
+ * Reaches Server Components, Route Handlers, Server Actions and middleware, and receives
57
+ * the real error rather than the generic message Next.js hands to an error component.
58
+ */
59
+ export async function captureRequestError(
60
+ error: unknown,
61
+ request: RequestErrorRequest,
62
+ context: RequestErrorContext
63
+ ): Promise<void> {
64
+ if (isNextControlFlowError(error)) {
65
+ return
66
+ }
67
+
68
+ // Same header precedence *and* the same span as the Insights path, so a fault and the
69
+ // events from the request it failed in carry matching ids. Next.js still has the request
70
+ // span active when it calls this hook, and it is the very span the Insights processor
71
+ // maps to `request.handled` — so with no id headers present all four ids are identical on
72
+ // both, and the fault joins its request's events and trace.
73
+ //
74
+ // Deliberately not written to the event context: outside a `Honeybadger.run()` that
75
+ // lands on a store shared by the whole process or isolate, so the ids would leak into
76
+ // later requests' events. `onRequestError` also fires after the request has already
77
+ // failed, so it is too late to decorate that request's own events anyway.
78
+ const ids = seedNodeRequestEventContext(request.headers, await activeSpanIds())
79
+
80
+ await Honeybadger.notifyAsync(error as Error, {
81
+ context: {
82
+ ...ids,
83
+ path: request.path,
84
+ method: request.method,
85
+ router_kind: context.routerKind,
86
+ route_path: context.routePath,
87
+ route_type: context.routeType,
88
+ },
89
+ })
90
+
91
+ await scheduleFlush({ useAfter: true })
92
+ }
@@ -0,0 +1,33 @@
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
+ Honeybadger.addBreadcrumb(`Navigated to ${url}`, {
30
+ category: 'navigation',
31
+ metadata: { url, navigationType },
32
+ })
33
+ }
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'