-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstrumentation.ts
More file actions
76 lines (68 loc) · 2.75 KB
/
instrumentation.ts
File metadata and controls
76 lines (68 loc) · 2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import * as Sentry from '@sentry/nextjs'
import { runStartupValidation } from './lib/rate-limit-validation'
import { logger } from './lib/logger'
export async function register() {
// Set E2E_TEST flag globally for client-side detection
if (process.env.E2E_TEST === 'true') {
if (typeof window !== 'undefined') {
(window as any).__E2E_TEST = true
}
if (typeof globalThis !== 'undefined') {
(globalThis as any).__E2E_TEST = true
}
}
// Initialize Sentry for both Node.js and Edge server runtimes
if (process.env.NEXT_RUNTIME === 'nodejs' || process.env.NEXT_RUNTIME === 'edge') {
Sentry.init({
dsn: process.env.SENTRY_DSN,
tracesSampleRate: 1.0,
environment: process.env.NODE_ENV,
})
}
// Validate rate limiter configuration on startup
// Skip during build phase to prevent Redis initialization crashes
// NEXT_PHASE is set by Next.js build process
const isBuildPhase = process.env.NEXT_PHASE === 'phase-production-build';
if (process.env.NEXT_RUNTIME === 'nodejs' && !isBuildPhase) {
try {
await runStartupValidation()
} catch (error) {
logger.error('Startup: Rate limiter validation failed', error as Error, {
action: 'startup_validation',
component: 'instrumentation'
})
// In production runtime (not build), only fail if Redis is explicitly required
const redisRequired = process.env.ENABLE_RATE_LIMITING !== 'false';
if (process.env.NODE_ENV === 'production' && redisRequired) {
logger.warn('Rate limiter validation failed but continuing with fallback', {
action: 'startup_validation_fallback'
})
// Don't throw - allow fallback to in-memory rate limiting
}
}
}
}
// Hook to capture request errors from nested React Server Components
// https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/#errors-from-nested-react-server-components
export function onRequestError(err: unknown) {
try {
// Attempt to capture request error with Sentry
// Wrap in extra try-catch because Sentry's captureRequestError can fail
// if it tries to access headers in a context where they are unavailable (Next.js 15 edge case)
try {
if (typeof Sentry.captureRequestError === 'function') {
// @ts-ignore
Sentry.captureRequestError(err)
} else {
Sentry.captureException(err instanceof Error ? err : new Error(String(err)))
}
} catch (sentryError) {
// Fallback to simple exception capture if request error capture fails
Sentry.captureException(err instanceof Error ? err : new Error(String(err)))
}
} catch (error) {
logger.error('Failed to capture request error in Sentry', error as Error, {
action: 'sentry_capture_error'
})
}
}