diff --git a/backend/src/index.ts b/backend/src/index.ts index df0f103..8ccf279 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -1,4 +1,4 @@ -import 'dotenv/config'; +import './instrument'; import healthRouter, { setHealthRuntimeState } from './routes/health'; import authRouter from './routes/auth'; @@ -42,7 +42,6 @@ import { withTransaction, type PoolClient } from './core'; import { bootstrapAllSchemas } from './schema-bootstrap'; import { ensureDemoAccountsSeeded } from './services/DemoAccountService'; import { ApiError, log, serializeError } from './core/errors'; -import { initBackendErrorTracking } from './core/errorTracking'; import { getPermissionsForRole, normalizeUserRole, @@ -99,7 +98,6 @@ const allowedOrigins = buildAllowedCorsOrigins(env.CORS_ORIGIN); const app = express(); app.use(securityHeaders); -initBackendErrorTracking(); initEmailJobs(); installDatabaseApm(pool); startApmMonitoring(); diff --git a/backend/src/instrument.ts b/backend/src/instrument.ts new file mode 100644 index 0000000..ab0e146 --- /dev/null +++ b/backend/src/instrument.ts @@ -0,0 +1,8 @@ +// Loaded first by index.ts. Sentry must initialize before express, http and pg are required so its +// OpenTelemetry instrumentation can patch them; otherwise errors still reach Sentry through the +// error handler, but request tracing records nothing. The build is CommonJS, so import order is +// load order. +import 'dotenv/config'; +import { initBackendErrorTracking } from './core/errorTracking'; + +initBackendErrorTracking(); diff --git a/src/lib/errorTracking.ts b/src/lib/errorTracking.ts index 72e928a..70134b7 100644 --- a/src/lib/errorTracking.ts +++ b/src/lib/errorTracking.ts @@ -54,11 +54,21 @@ export function getCurrentFrontendErrorTrackingConfig() { export function initFrontendErrorTracking(config = getCurrentFrontendErrorTrackingConfig()) { if (!config.enabled || initialized) return; + const tracingEnabled = config.tracesSampleRate > 0; Sentry.init({ dsn: config.dsn, environment: config.environment, release: config.release, - tracesSampleRate: config.tracesSampleRate, + // Page loads, navigations and fetches become traces only when a sample rate is set. + ...(tracingEnabled + ? { + integrations: [Sentry.browserTracingIntegration()], + tracesSampleRate: config.tracesSampleRate, + // Continue the trace into the API so one request shows up across web and backend. The + // backend's CORS reflects requested headers, so sentry-trace and baggage are allowed. + tracePropagationTargets: ['localhost', /^https:\/\/api\.kaffepos\.my\.id\//], + } + : {}), }); initialized = true; }