@sentry/node
- Version 11.8.0
- Published
- 1.51 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
- buildLaunchDarklyFlagUsedHandler()
- childProcessIntegration()
- consoleIntegration()
- contextLinesIntegration()
- createGetModuleFromFilename()
- createSentryWinstonTransport()
- disableAnrDetectionForCallback()
- eveInstrumentation()
- fsIntegration()
- getAutoPerformanceIntegrations()
- getDefaultIntegrations()
- getDefaultIntegrationsWithoutPerformance()
- getSentryRelease()
- httpIntegration()
- httpServerIntegration()
- httpServerSpansIntegration()
- init()
- initOpenTelemetry()
- initWithoutDefaultIntegrations()
- launchDarklyIntegration()
- localVariablesIntegration()
- makeNodeTransport()
- modulesIntegration()
- nativeNodeFetchIntegration()
- nodeContextIntegration()
- nodeRuntimeMetricsIntegration()
- onUncaughtExceptionIntegration()
- onUnhandledRejectionIntegration()
- openFeatureIntegration()
- processSessionIntegration()
- setupHapiErrorHandler()
- setupKoaErrorHandler()
- spotlightIntegration()
- statsigIntegration()
- systemErrorIntegration()
- unleashIntegration()
- workerThreadsIntegration()
Classes
Interfaces
Namespaces
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 cron
const cron: { instrumentCron: typeof instrumentCron; instrumentNodeCron: typeof instrumentNodeCron; instrumentNodeSchedule: typeof instrumentNodeSchedule;};Methods to instrument cron libraries for Sentry check-ins
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 NODE_VERSION
const NODE_VERSION: { major: number; minor: number; patch: number };variable pinoIntegration
const pinoIntegration: (( userOptions?: DeepPartial<PinoOptions> | undefined) => import('@sentry/core').Integration & { name: string }) & { trackLogger(logger: unknown): void; untrackLogger(logger: unknown): void;};Integration for Pino logging library. Captures Pino logs as Sentry logs and optionally captures some log levels as events.
By default, all Pino loggers will be captured. To ignore a specific logger, use
pinoIntegration.untrackLogger(logger).If you disable automatic instrumentation with
autoInstrument: false, you can mark specific loggers to be tracked withpinoIntegration.trackLogger(logger).Requires Pino >=v8.0.0
Functions
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 createGetModuleFromFilename
createGetModuleFromFilename: ( basePath?: string, isWindows?: boolean) => (filename: string | undefined) => string | undefined;Creates a function that gets the module name from a filename
function createSentryWinstonTransport
createSentryWinstonTransport: <TransportStreamInstance extends object>( TransportClass: new (options?: any) => TransportStreamInstance, sentryWinstonOptions?: WinstonTransportOptions) => typeof TransportClass;Creates a new Sentry Winston transport that fowards logs to Sentry.
Supports Winston 3.x.x.
Parameter TransportClass
The Winston transport class to extend.
Returns
The extended transport class.
Example 1
const winston = require('winston');const Transport = require('winston-transport');const SentryWinstonTransport = Sentry.createSentryWinstonTransport(Transport);const logger = winston.createLogger({transports: [new SentryWinstonTransport()],});
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 so gen_ai inputs/outputs are recorded by default (eve stamps every AI SDK call withrecordInputs/recordOutputs: false); - tags each turn's AI spans with a Sentry conversation id viaturn.started/step.attempt.startedevents — 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 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.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: () => { name: 'Modules'; processEvent(event: any): any; getModules: typeof _getModules;};Add node modules / packages to the event. For this, multiple sources are used: - They can be injected at build time into the __SENTRY_SERVER_MODULES__ variable (e.g. in Next.js) - They are extracted from the dependencies & devDependencies in the package.json file - They are extracted from the require.cache (CJS only)
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 setupHapiErrorHandler
setupHapiErrorHandler: (server: unknown) => Promise<void>;Add a Hapi plugin to capture errors to Sentry.
Parameter server
The Hapi server to attach the error handler to
Deprecated
The error handler is now registered automatically when the Hapi server starts (via the orchestrion
@hapi/hapiinstrumentation), so calling this is no longer necessary. It remains a safe, idempotent operation when the handler is already attached, and is kept for setups where auto-registration is unavailable. This will be removed in a future major version.
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.
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
Namespaces
namespace logger
module 'build/types/logs/exports.d.ts' {}Capture a log with the
tracelevel.You can either pass a message and attributes or a message template, params and attributes.
Example 1
Sentry.logger.trace('Starting database connection', {database: 'users',connectionId: 'conn_123'});Example 2
With template strings
Sentry.logger.trace('Database connection %s established for %s',['successful', 'users'],{ connectionId: 'conn_123' });
function debug
debug: (...args: CaptureLogArgs) => void;Capture a log with the
debuglevel.You can either pass a message and attributes or a message template, params and attributes.
Example 1
Sentry.logger.debug('Cache miss for user profile', {userId: 'user_123',cacheKey: 'profile:user_123'});Example 2
With template strings
Sentry.logger.debug('Cache %s for %s: %s',['miss', 'user profile', 'key not found'],{ userId: 'user_123' });
function error
error: (...args: CaptureLogArgs) => void;Capture a log with the
errorlevel.You can either pass a message and attributes or a message template, params and attributes.
Example 1
Sentry.logger.error('Failed to process payment', {orderId: 'order_123',errorCode: 'PAYMENT_FAILED',amount: 99.99});Example 2
With template strings
Sentry.logger.error('Payment processing failed for order %s: %s',['order_123', 'insufficient funds'],{ amount: 99.99 });
function fatal
fatal: (...args: CaptureLogArgs) => void;Capture a log with the
fatallevel.You can either pass a message and attributes or a message template, params and attributes.
Example 1
Sentry.logger.fatal('Database connection pool exhausted', {database: 'users',activeConnections: 100,maxConnections: 100});Example 2
With template strings
Sentry.logger.fatal('Database %s: %s connections active',['connection pool exhausted', '100/100'],{ database: 'users' });
function info
info: (...args: CaptureLogArgs) => void;Capture a log with the
infolevel.You can either pass a message and attributes or a message template, params and attributes.
Example 1
Sentry.logger.info('User profile updated', {userId: 'user_123',updatedFields: ['email', 'preferences']});Example 2
With template strings
Sentry.logger.info('User %s updated their %s',['John Doe', 'profile settings'],{ userId: 'user_123' });
function trace
trace: (...args: CaptureLogArgs) => void;Capture a log with the
tracelevel.You can either pass a message and attributes or a message template, params and attributes.
Example 1
Sentry.logger.trace('Starting database connection', {database: 'users',connectionId: 'conn_123'});Example 2
With template strings
Sentry.logger.trace('Database connection %s established for %s',['successful', 'users'],{ connectionId: 'conn_123' });
function warn
warn: (...args: CaptureLogArgs) => void;Capture a log with the
warnlevel.You can either pass a message and attributes or a message template, params and attributes.
Example 1
Sentry.logger.warn('Rate limit approaching', {endpoint: '/api/users',currentRate: '95/100',resetTime: '2024-03-20T10:00:00Z'});Example 2
With template strings
Sentry.logger.warn('Rate limit %s for %s: %s',['approaching', '/api/users', '95/100 requests'],{ resetTime: '2024-03-20T10:00:00Z' });
Package Files (41)
- build/types/cron/index.d.ts
- build/types/eve.d.ts
- build/types/index.d.ts
- build/types/integrations/anr/index.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/pino.d.ts
- build/types/integrations/processSession.d.ts
- build/types/integrations/spotlight.d.ts
- build/types/integrations/systemError.d.ts
- build/types/integrations/tracing/hapi.d.ts
- build/types/integrations/tracing/index.d.ts
- build/types/integrations/tracing/koa.d.ts
- build/types/integrations/winston.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/module.d.ts
Dependencies (7)
Dev Dependencies (1)
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 2566 ms. - Missing or incorrect documentation? Open an issue for this package.
