@sentry/node
- Version 11.20.0
- Published
- 1.34 MB
- 7 dependencies
- MIT license
Install
npm i @sentry/nodeyarn add @sentry/nodepnpm add @sentry/nodeOverview
Sentry Node SDK using OpenTelemetry for performance instrumentation
Index
Variables
Functions
- addServerTimingTraceHeader()
- awsLambdaWebIntegration()
- buildLaunchDarklyFlagUsedHandler()
- childProcessIntegration()
- consoleIntegration()
- contextLinesIntegration()
- disableAnrDetectionForCallback()
- eveInstrumentation()
- fsIntegration()
- getAutoPerformanceIntegrations()
- getDefaultIntegrations()
- getDefaultIntegrationsWithoutPerformance()
- getHttpAgent()
- getSentryRelease()
- httpIntegration()
- httpServerIntegration()
- httpServerSpansIntegration()
- init()
- initOpenTelemetry()
- initWithoutDefaultIntegrations()
- launchDarklyIntegration()
- localVariablesIntegration()
- makeNodeTransport()
- modulesIntegration()
- nativeNodeFetchIntegration()
- nodeContextIntegration()
- nodeRuntimeMetricsIntegration()
- onUncaughtExceptionIntegration()
- onUnhandledRejectionIntegration()
- openFeatureIntegration()
- processSessionIntegration()
- serveTunnelIntegration()
- setupKoaErrorHandler()
- spotlightIntegration()
- statsigIntegration()
- systemErrorIntegration()
- unleashIntegration()
- workerThreadsIntegration()
Classes
Interfaces
Variables
variable anrIntegration
const anrIntegration: AnrReturn;Application Not Responding (ANR) integration for Node.js applications.
Example 1
Sentry.init({dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",integrations: [Sentry.anrIntegration({anrThreshold: 5000,captureStackTrace: true,pollInterval: 50,}),],});Deprecated
The ANR integration has been deprecated. Use
eventLoopBlockIntegrationfrom@sentry/node-nativeinstead.Detects when the Node.js main thread event loop is blocked for more than the configured threshold (5 seconds by default) and reports these as Sentry events.
ANR detection uses a worker thread to monitor the event loop in the main app thread. The main app thread sends a heartbeat message to the ANR worker thread every 50ms by default. If the ANR worker does not receive a heartbeat message for the configured threshold duration, it triggers an ANR event.
- Node.js 16.17.0 or higher - Only supported in the Node.js runtime (not browsers) - Not supported for Node.js clusters
Overhead should be minimal: - Main thread: Only polling the ANR worker over IPC every 50ms - Worker thread: Consumes around 10-20 MB of RAM - When ANR detected: Brief pause in debugger to capture stack trace (negligible compared to the blocking)
variable defaultStackParser
const defaultStackParser: StackParser;Node.js stack parser
variable growthbookIntegration
const growthbookIntegration: any;Re-export the core GrowthBook integration for Node.js usage. The core integration is runtime-agnostic and works in both browser and Node environments.
variable logger
const logger: { trace: typeof trace; debug: typeof debug; info: typeof info; warn: typeof warn; error: typeof error; fatal: typeof fatal; fmt: any;};The public logger API.
A plain object rather than a module namespace so its methods can be spied on in tests.
variable NODE_VERSION
const NODE_VERSION: { major: number; minor: number; patch: number };Functions
function addServerTimingTraceHeader
addServerTimingTraceHeader: (client: Client) => void;Sends the trace of the request in a
Server-Timingheader of a document response of the Node.js server, so the browser SDK continues it in the pageload span before any HTML arrived. Next.js flushes the headers with the first chunk of the document, inside the request span, so the value is computed then rather than when the request comes in. The hook fires for every request, also when incoming request spans are disabled, which the Next.js SDK does because Next.js starts the request span.
function awsLambdaWebIntegration
awsLambdaWebIntegration: () => import('@sentry/core').Integration & { name: string;};Enrich AWS Lambda Web Function spans and error contexts with platform metadata.
function buildLaunchDarklyFlagUsedHandler
buildLaunchDarklyFlagUsedHandler: () => unknown;This is a shim for the LaunchDarkly flag used handler.
function childProcessIntegration
childProcessIntegration: ( options?: Options | undefined) => import('@sentry/core').Integration & { name: 'ChildProcess' };Capture breadcrumbs and events for child processes. For worker thread events, use
workerThreadsIntegration()instead.
function consoleIntegration
consoleIntegration: ( options?: Partial<ConsoleIntegrationOptions> | undefined) => import('@sentry/core').Integration & { name: 'Console' };Node-specific console integration that captures breadcrumbs and handles the AWS Lambda runtime replacing console methods after our patch.
In Lambda, console methods are patched via
Object.definePropertyso that external replacements (by the Lambda runtime) are absorbed as the delegate while our wrapper stays in place. Outside Lambda, this delegates entirely to the coreconsoleIntegrationwhich uses the simplerfill-based patch.
function contextLinesIntegration
contextLinesIntegration: ( options?: ContextLinesOptions | undefined) => import('@sentry/core').Integration & { name: 'ContextLines' };Capture the lines before and after the frame's context.
function disableAnrDetectionForCallback
disableAnrDetectionForCallback: { <T>(callback: () => T): T; <T>(callback: () => Promise<T>): Promise<T>;};See Also
Deprecated
The ANR integration has been deprecated. Use
eventLoopBlockIntegrationfrom@sentry/node-nativeinstead.
function eveInstrumentation
eveInstrumentation: ( options?: EveInstrumentationOptions) => EveInstrumentationProvider;All-in-one Sentry setup for an [eve](https://eve.dev) agent, wired into a single
agent/instrumentation/*.tsprovider file.Example 1
// agent/instrumentation/sentry.tsimport * as Sentry from '@sentry/node';import { defineInstrumentation } from 'eve/instrumentation';export default defineInstrumentation(Sentry.eveInstrumentation({ dsn: '__DSN__' }));It: - runs
Sentry.initwith the given options at server startup (setup), adding eveIntegration; - asks eve for full gen_ai results (eveTracePolicy); Sentry filters content bydataCollection.genAIwhen it builds spans. On eve >= 1.0.0-rc.10 this also sets the AI SDK'srecordInputs/recordOutputsflags, which apply to every AI SDK telemetry integration in the app; - tags each turn's AI spans with a Sentry conversation id viaturn.startedandstep.attempt.started(eve < 0.84) /model.started(eve >= 0.84) events — the instrumentation-provider equivalent ofeveConversationHook. Provider event handlers receive the session id on the event (event.sessionId/event.scope.sessionId), unlike hook handlers, which read it from their context.
function fsIntegration
fsIntegration: ( options?: FsInstrumentationConfig | undefined) => import('@sentry/core').Integration & { name: 'FileSystem' };This integration will create spans for
fsAPI operations, like reading and writing files.**WARNING:** This integration may add significant overhead to your application. Especially in scenarios with a lot of file I/O, like for example when running a framework dev server, including this integration can massively slow down your application.
Parameter options
Configuration for this integration.
function getAutoPerformanceIntegrations
getAutoPerformanceIntegrations: () => Integration[];function getDefaultIntegrations
getDefaultIntegrations: (options: Options) => Integration[];Get the default integrations for the Node SDK.
function getDefaultIntegrationsWithoutPerformance
getDefaultIntegrationsWithoutPerformance: () => Integration[];Get default integrations, excluding performance.
function getHttpAgent
getHttpAgent: ( url: URL, options?: { proxy?: string | false; keepAlive?: boolean }) => http.Agent;Returns the agent for requests to
url: a proxy agent when a proxy applies, otherwise a plain keep-alive agent.Proxy prioritization: http =>
options.proxy|process.env.http_proxyProxy prioritization: https =>options.proxy|process.env.https_proxy|process.env.http_proxyHosts listed inprocess.env.no_proxyare never proxied, andoptions.proxy: falsedisables proxying entirely.
function getSentryRelease
getSentryRelease: (fallback?: string) => string | undefined;Returns a release dynamically from environment variables.
function httpIntegration
httpIntegration: ( options?: HttpOptions | undefined) => import('@sentry/core').Integration & { name: 'Http' };The http integration instruments Node's internal http and https modules. It creates breadcrumbs and spans for outgoing HTTP requests which will be attached to the currently active span.
function httpServerIntegration
httpServerIntegration: ( options?: HttpServerIntegrationOptions) => Integration & { name: 'Http.Server'; setupOnce: () => void };This integration handles request isolation, trace continuation and other core Sentry functionality around incoming http requests handled via the node
httpmodule, or via the compat API of thehttp2module.This version uses OpenTelemetry for context propagation and span management.
See Also
for the lightweight version without OpenTelemetry
function httpServerSpansIntegration
httpServerSpansIntegration: (options?: HttpServerSpansIntegrationOptions) => any;This integration emits spans for incoming requests handled via the node
httpmodule. It requires thehttpServerIntegrationto be present.
function init
init: (options?: NodeOptions | undefined) => NodeClient | undefined;Initialize Sentry for Node.
function initOpenTelemetry
initOpenTelemetry: (client: NodeClient) => void;Initialize OpenTelemetry for Node.
function initWithoutDefaultIntegrations
initWithoutDefaultIntegrations: ( options?: NodeOptions | undefined) => NodeClient | undefined;Initialize Sentry for Node, without any integrations added by default.
function launchDarklyIntegration
launchDarklyIntegration: ( _options?: unknown) => import('@sentry/core').Integration & { name: 'LaunchDarkly' };This is a shim for the LaunchDarkly integration. We need this in order to not throw runtime errors when accidentally importing this on the server through a meta framework like Next.js.
function localVariablesIntegration
localVariablesIntegration: ( options?: LocalVariablesIntegrationOptions) => Integration;function makeNodeTransport
makeNodeTransport: (options: NodeTransportOptions) => Transport;Creates a Transport that uses native the native 'http' and 'https' modules to send events to Sentry.
function modulesIntegration
modulesIntegration: () => import('@sentry/core').Integration & { name: 'Modules';};Adds the app's packages to the event. Versions injected at build time (e.g. by the Next.js SDK) are used as is. Otherwise, it uses exact installed versions where they resolve from the entry file, and declared ranges for the rest.
function nativeNodeFetchIntegration
nativeNodeFetchIntegration: ( options?: NodeFetchOptions | undefined) => import('@sentry/core').Integration & { name: 'NodeFetch' };Instrument outgoing fetch requests made through the native node
fetchAPI. This emits (depending on the integration options) spans and breadcrumbs, as well as injecting trace propagation headers into the request.
function nodeContextIntegration
nodeContextIntegration: ( options?: ContextOptions | undefined) => import('@sentry/core').Integration & { name: 'Context' };Capture context about the environment and the device that the client is running on, to events.
function nodeRuntimeMetricsIntegration
nodeRuntimeMetricsIntegration: ( options?: NodeRuntimeMetricsOptions | undefined) => import('@sentry/core').Integration & { name: 'NodeRuntimeMetrics' };Automatically collects Node.js runtime metrics and emits them to Sentry.
Example 1
Sentry.init({integrations: [Sentry.nodeRuntimeMetricsIntegration(),],});
function onUncaughtExceptionIntegration
onUncaughtExceptionIntegration: ( options?: Partial<OnUncaughtExceptionOptions> | undefined) => import('@sentry/core').Integration & { name: 'OnUncaughtException' };Add a global exception handler.
function onUnhandledRejectionIntegration
onUnhandledRejectionIntegration: ( options?: Partial<OnUnhandledRejectionOptions> | undefined) => import('@sentry/core').Integration & { name: string };function openFeatureIntegration
openFeatureIntegration: ( _options?: unknown) => import('@sentry/core').Integration & { name: 'OpenFeature' };This is a shim for the OpenFeature integration. We need this in order to not throw runtime errors when accidentally importing this on the server through a meta framework like Next.js.
function processSessionIntegration
processSessionIntegration: () => import('@sentry/core').Integration & { name: 'ProcessSession';};Records a Session for the current process to track release health.
Once the process starts serving requests that are tracked as request sessions, release health is reported through session aggregates instead, and the process session is discarded. This integration exists so that we capture some form of session health data even when the process is not serving requests.
function serveTunnelIntegration
serveTunnelIntegration: ( options?: import('@sentry/core').ServerTunnelOptions | undefined) => import('@sentry/core').Integration & { name: string };Lets your server forward the events of a browser SDK set up with
tunnel: trueto Sentry.With this integration on the server and
tunnel: truein the browserinit, the browser sends its events to your own server instead of Sentry, where ad-blockers can't drop them, and your server forwards them to Sentry.Every
node:httpserver answers the tunnel requests before the app sees them. To serve them from your own code instead, setintercept: falseand callhandleTunnelRequestIfMatched.By default only envelopes for the server's own DSN are forwarded.
Example 1
// ServerSentry.init({dsn: '__DSN__',integrations: [Sentry.serveTunnelIntegration()],});// BrowserSentry.init({dsn: '__DSN__',tunnel: true,});
function setupKoaErrorHandler
setupKoaErrorHandler: (app: { on: (event: 'error', listener: (...args: any[]) => void) => unknown;}) => void;Add a Koa error handler to capture errors to Sentry.
Parameter app
The Koa app instance
Example 1
const Sentry = require('@sentry/node');const Koa = require("koa");const app = new Koa();// Add your routes, etc.app.listen(3000);Deprecated
The error handler is now registered automatically when the Koa app starts (via the orchestrion
koainstrumentation), so calling this is no longer necessary. It remains a safe, idempotent operation, and is kept for setups where auto-registration is unavailable. This will be removed in a future major version.
function spotlightIntegration
spotlightIntegration: ( options?: Partial<SpotlightConnectionOptions> | undefined) => import('@sentry/core').Integration & { name: 'Spotlight' };Use this integration to send errors and transactions to Spotlight.
Learn more about spotlight at https://spotlightjs.com
function statsigIntegration
statsigIntegration: ( _options?: unknown) => import('@sentry/core').Integration & { name: 'Statsig' };This is a shim for the Statsig integration. We need this in order to not throw runtime errors when accidentally importing this on the server through a meta framework like Next.js.
function systemErrorIntegration
systemErrorIntegration: ( options?: Options | undefined) => import('@sentry/core').Integration & { name: 'NodeSystemError' };Captures context for Node.js SystemError errors.
function unleashIntegration
unleashIntegration: ( _options?: unknown) => import('@sentry/core').Integration & { name: 'Unleash' };This is a shim for the Unleash integration. We need this in order to not throw runtime errors when accidentally importing this on the server through a meta framework like Next.js.
function workerThreadsIntegration
workerThreadsIntegration: () => import('@sentry/core').Integration & { name: 'WorkerThreads';};Capture events and errors of worker threads. For child process events, use
childProcessIntegration()instead.
Classes
class NodeClient
class NodeClient extends ServerRuntimeClient<NodeClientOptions> {}A client for using Sentry with Node & OpenTelemetry.
constructor
constructor(options: NodeClientOptions);property asyncLocalStorageLookup
asyncLocalStorageLookup: any;property traceProvider
traceProvider: any;property tracer
readonly tracer: Tracer;Get the OTEL tracer.
method close
close: (timeout?: number | undefined) => PromiseLike<boolean>;method flush
flush: (timeout?: number) => PromiseLike<boolean>;method init
init: () => void;method startClientReportTracking
startClientReportTracking: () => void;Will start tracking client reports for this client.
NOTICE: This method will create an interval that is periodically called and attach a
process.on('beforeExit')hook. To clean up these resources, call.close()when you no longer intend to use the client. Not doing so will result in a memory leak.
class OpenFeatureIntegrationHook
class OpenFeatureIntegrationHookShim {}This is a shim for the OpenFeature integration hook.
Interfaces
interface NodeOptions
interface NodeOptions extends Options<NodeTransportOptions>, BaseNodeOptions {}Configuration options for the Sentry Node SDK
See Also
@sentry/core Options for more information.
property tunnel
tunnel?: string;A URL to send this server's own envelopes to instead of the Sentry ingest URL. To serve the managed tunnel for the browser, use
serveTunnelIntegration.
interface NodeRuntimeMetricsOptions
interface NodeRuntimeMetricsOptions {}property collect
collect?: { cpuUtilization?: boolean; memHeapUsed?: boolean; memRss?: boolean; eventLoopDelayP99?: boolean; eventLoopUtilization?: boolean; uptime?: boolean; cpuTime?: boolean; memHeapTotal?: boolean; memExternal?: boolean; eventLoopDelayMin?: boolean; eventLoopDelayMax?: boolean; eventLoopDelayMean?: boolean; eventLoopDelayP50?: boolean; eventLoopDelayP90?: boolean;};Which metrics to collect.
Default on (8 metrics): -
cpuUtilization— CPU utilization ratio -memRss— Resident Set Size (actual memory footprint) -memHeapUsed— V8 heap currently in use -memHeapTotal— total V8 heap allocated (headroom paired withmemHeapUsed) -eventLoopDelayP50— median event loop delay (baseline latency) -eventLoopDelayP99— 99th percentile event loop delay (tail latency / spikes) -eventLoopUtilization— fraction of time the event loop was active -uptime— process uptime (detect restarts/crashes)Default off (opt-in): -
cpuTime— raw user/system CPU time in seconds -memExternal— external/ArrayBuffer memory (relevant for native addons) -eventLoopDelayMin/eventLoopDelayMax/eventLoopDelayMean/eventLoopDelayP90
property collectionIntervalMs
collectionIntervalMs?: number;How often to collect metrics, in milliseconds. Minimum allowed value is 1000ms. 30000 1000
Package Files (39)
- build/types/eve.d.ts
- build/types/index.d.ts
- build/types/integrations/anr/index.d.ts
- build/types/integrations/awsLambdaWeb.d.ts
- build/types/integrations/childProcess.d.ts
- build/types/integrations/console.d.ts
- build/types/integrations/context.d.ts
- build/types/integrations/contextlines.d.ts
- build/types/integrations/featureFlagShims/growthbook.d.ts
- build/types/integrations/featureFlagShims/launchDarkly.d.ts
- build/types/integrations/featureFlagShims/openFeature.d.ts
- build/types/integrations/featureFlagShims/statsig.d.ts
- build/types/integrations/featureFlagShims/unleash.d.ts
- build/types/integrations/fs/index.d.ts
- build/types/integrations/http/httpServerIntegration.d.ts
- build/types/integrations/http/httpServerSpansIntegration.d.ts
- build/types/integrations/http/index.d.ts
- build/types/integrations/local-variables/index.d.ts
- build/types/integrations/modules.d.ts
- build/types/integrations/node-fetch/index.d.ts
- build/types/integrations/nodeRuntimeMetrics.d.ts
- build/types/integrations/onuncaughtexception.d.ts
- build/types/integrations/onunhandledrejection.d.ts
- build/types/integrations/processSession.d.ts
- build/types/integrations/serveTunnel.d.ts
- build/types/integrations/spotlight.d.ts
- build/types/integrations/systemError.d.ts
- build/types/integrations/tracing/index.d.ts
- build/types/integrations/tracing/koa.d.ts
- build/types/integrations/workerThreads.d.ts
- build/types/logs/exports.d.ts
- build/types/nodeVersion.d.ts
- build/types/sdk/api.d.ts
- build/types/sdk/client.d.ts
- build/types/sdk/index.d.ts
- build/types/sdk/initOtel.d.ts
- build/types/transports/http.d.ts
- build/types/types.d.ts
- build/types/utils/serverTimingHeader.d.ts
Dependencies (7)
Dev Dependencies (2)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@sentry/node.
- Markdown[](https://www.jsdocs.io/package/@sentry/node)
- HTML<a href="https://www.jsdocs.io/package/@sentry/node"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 4175 ms. - Missing or incorrect documentation? Open an issue for this package.
