Official Sentry SDK for various serverless solutions including AWS Lambda and Google Cloud Functions
—
All core Sentry capabilities for error tracking, performance monitoring, context management, and SDK configuration. The @sentry/serverless package re-exports all functionality from @sentry/node, providing the complete Sentry experience for serverless environments.
Initialize the Sentry SDK with configuration options.
/**
* Initialize the Sentry SDK
* @param options - Configuration options for the SDK
*/
function init(options?: NodeOptions): void;
interface NodeOptions {
/** Data Source Name - your Sentry project URL */
dsn?: string;
/** Application environment (e.g., 'production', 'development') */
environment?: string;
/** Application release version */
release?: string;
/** Sample rate for error events (0.0 to 1.0) */
sampleRate?: number;
/** Sample rate for performance/tracing events (0.0 to 1.0) */
tracesSampleRate?: number;
/** Whether to attach stack traces to messages */
attachStacktrace?: boolean;
/** Array of integrations to use */
integrations?: Integration[];
/** Whether to send sessions */
autoSessionTracking?: boolean;
/** Custom transport function */
transport?: Transport;
/** Custom stack parser */
stackParser?: StackParser;
}
// Base Sentry types
interface Integration {
name: string;
setupOnce?(): void;
setup?(client: Client): void;
}
interface Client {
captureException(exception: any, hint?: EventHint, scope?: Scope): string;
captureMessage(message: string, level?: SeverityLevel, hint?: EventHint, scope?: Scope): string;
captureEvent(event: Event, hint?: EventHint, scope?: Scope): string;
flush(timeout?: number): Promise<boolean>;
close(timeout?: number): Promise<boolean>;
}
interface Options {
dsn?: string;
environment?: string;
release?: string;
integrations?: Integration[];
[key: string]: any;
}Capture and send exceptions and messages to Sentry.
/**
* Capture and send an exception to Sentry
* @param exception - The exception to capture
* @param scope - Optional scope modifier function
* @returns Event ID of the captured exception
*/
function captureException(
exception: any,
scope?: (scope: Scope) => Scope
): string;
/**
* Capture and send a message to Sentry
* @param message - The message to capture
* @param level - Severity level of the message
* @param scope - Optional scope modifier function
* @returns Event ID of the captured message
*/
function captureMessage(
message: string,
level?: SeverityLevel,
scope?: (scope: Scope) => Scope
): string;
/**
* Capture and send an event to Sentry
* @param event - The event object to send
* @param scope - Optional scope modifier function
* @returns Event ID of the captured event
*/
function captureEvent(
event: Event,
scope?: (scope: Scope) => Scope
): string;
type SeverityLevel = 'fatal' | 'error' | 'warning' | 'log' | 'info' | 'debug';Usage Examples:
import { captureException, captureMessage, captureEvent } from "@sentry/serverless";
// Capture an exception
try {
riskyOperation();
} catch (error) {
captureException(error);
}
// Capture a message with context
captureMessage("User login failed", "warning", (scope) => {
scope.setTag("feature", "authentication");
scope.setUser({ id: "123", email: "user@example.com" });
return scope;
});
// Capture a custom event
captureEvent({
message: "Custom business logic event",
level: "info",
tags: {
module: "payment-processor",
action: "payment-completed"
}
});Create and manage performance spans and transactions.
/**
* Start a new span and execute a function within its context
* @param context - Span context configuration
* @param fn - Function to execute within the span
* @returns Result of the function execution
*/
function startSpan<T>(context: SpanContext, fn: (span: Span) => T): T;
/**
* Start a span with manual control over its lifecycle
* @param context - Span context configuration
* @param fn - Function to execute with manual span control
* @returns Result of the function execution
*/
function startSpanManual<T>(context: SpanContext, fn: (span: Span) => T): T;
/**
* Start an inactive span that doesn't affect the active span context
* @param context - Span context configuration
* @returns The created span
*/
function startInactiveSpan(context: SpanContext): Span;
/**
* Execute code with a specific span as the active span
* @param span - The span to make active
* @param fn - Function to execute with the active span
* @returns Result of the function execution
*/
function withActiveSpan<T>(span: Span | null, fn: () => T): T;
/**
* Get the currently active span
* @returns The active span or undefined
*/
function getActiveSpan(): Span | undefined;
interface SpanContext {
/** Name of the span */
name: string;
/** Operation type (e.g., 'http.client', 'db.query') */
op?: string;
/** Span attributes */
attributes?: Record<string, any>;
/** Parent span ID */
parentSpanId?: string;
/** Trace ID */
traceId?: string;
/** Whether this span should only be created if there's a parent */
onlyIfParent?: boolean;
}Usage Examples:
import { startSpan, startSpanManual, getActiveSpan } from "@sentry/serverless";
// Automatic span management
const result = await startSpan(
{ name: "database-query", op: "db.query" },
async (span) => {
span.setTag("table", "users");
span.setData("query", "SELECT * FROM users WHERE active = true");
return await db.query("SELECT * FROM users WHERE active = true");
}
);
// Manual span management
const data = await startSpanManual(
{ name: "complex-operation", op: "task" },
async (span) => {
try {
const step1 = await performStep1();
span.setTag("step1_status", "success");
const step2 = await performStep2(step1);
span.setTag("step2_status", "success");
return step2;
} catch (error) {
span.setTag("error", true);
span.setStatus("internal_error");
throw error;
} finally {
span.end();
}
}
);
// Check for active span
const activeSpan = getActiveSpan();
if (activeSpan) {
activeSpan.setTag("has_active_span", true);
}Manage Sentry scopes and context data.
/**
* Execute code within an isolated scope
* @param callback - Function to execute with the isolated scope
* @returns Result of the callback function
*/
function withScope<T>(callback: (scope: Scope) => T): T;
/**
* Execute code within an isolated isolation scope
* @param callback - Function to execute with the isolation scope
* @returns Result of the callback function
*/
function withIsolationScope<T>(callback: (scope: Scope) => T): T;
/**
* Get the current scope
* @returns The current scope
*/
function getCurrentScope(): Scope;
/**
* Get the global scope
* @returns The global scope
*/
function getGlobalScope(): Scope;
/**
* Get the isolation scope
* @returns The isolation scope
*/
function getIsolationScope(): Scope;
// Convenience functions for setting context
function setContext(key: string, context: Context): void;
function setExtra(key: string, extra: any): void;
function setExtras(extras: Record<string, any>): void;
function setTag(key: string, value: string): void;
function setTags(tags: Record<string, string>): void;
function setUser(user: User): void;
interface Scope {
/** Set a tag on the scope */
setTag(key: string, value: string): void;
/** Set multiple tags on the scope */
setTags(tags: Record<string, string>): void;
/** Set extra data on the scope */
setExtra(key: string, extra: any): void;
/** Set multiple extra data on the scope */
setExtras(extras: Record<string, any>): void;
/** Set context on the scope */
setContext(key: string, context: Context): void;
/** Set user information on the scope */
setUser(user: User | null): void;
/** Add a breadcrumb to the scope */
addBreadcrumb(breadcrumb: Breadcrumb): void;
/** Add an event processor to the scope */
addEventProcessor(callback: EventProcessor): void;
}
interface User {
id?: string | number;
username?: string;
email?: string;
ip_address?: string;
[key: string]: any;
}
interface Context {
[key: string]: any;
}Usage Examples:
import {
withScope,
getCurrentScope,
setUser,
setTag,
setContext,
captureException
} from "@sentry/serverless";
// Isolated scope for specific operation
withScope((scope) => {
scope.setTag("operation", "user-registration");
scope.setUser({ id: "123", email: "user@example.com" });
scope.setContext("registration", { step: "email-verification" });
try {
registerUser(userData);
} catch (error) {
captureException(error); // Will include the scope context
}
});
// Global context setting
setUser({ id: "456", email: "admin@example.com" });
setTag("service", "user-service");
setContext("deployment", { version: "1.2.3", region: "us-west-2" });
// Working with current scope
const scope = getCurrentScope();
scope.addBreadcrumb({
message: "Started processing request",
category: "request",
level: "info",
timestamp: Date.now() / 1000
});Add breadcrumb trails to track user actions and application state.
/**
* Add a breadcrumb to the current scope
* @param breadcrumb - The breadcrumb to add
*/
function addBreadcrumb(breadcrumb: Breadcrumb): void;
interface Breadcrumb {
/** Breadcrumb message */
message?: string;
/** Breadcrumb category */
category?: string;
/** Breadcrumb level */
level?: BreadcrumbLevel;
/** Breadcrumb timestamp */
timestamp?: number;
/** Breadcrumb type */
type?: string;
/** Additional data */
data?: Record<string, any>;
}
type BreadcrumbLevel = 'fatal' | 'error' | 'warning' | 'info' | 'debug';Manage SDK state and configuration.
/**
* Check if the SDK is initialized
* @returns True if the SDK is initialized
*/
function isInitialized(): boolean;
/**
* Get the current Sentry client
* @returns The current client or undefined
*/
function getClient(): Client | undefined;
/**
* Set the current client
* @param client - The client to set as current
*/
function setCurrentClient(client: Client): void;
/**
* Flush pending events
* @param timeout - Maximum time to wait for flush in milliseconds
* @returns Promise that resolves when flush is complete
*/
function flush(timeout?: number): Promise<boolean>;
/**
* Close the SDK and flush all pending events
* @param timeout - Maximum time to wait for close in milliseconds
* @returns Promise that resolves when close is complete
*/
function close(timeout?: number): Promise<boolean>;
/**
* Get the last captured event ID
* @returns The event ID of the last captured event
*/
function lastEventId(): string | undefined;Manage SDK integrations for enhanced functionality.
/**
* Add an integration after SDK initialization
* @param integration - The integration to add
*/
function addIntegration(integration: Integration): void;
/**
* Get the default integrations for Node.js
* @param options - Configuration options
* @returns Array of default integrations
*/
function getDefaultIntegrations(options: Options): Integration[];
/**
* Auto-discover Node.js performance monitoring integrations
* @returns Array of performance integrations
*/
function autoDiscoverNodePerformanceMonitoringIntegrations(): Integration[];
// Built-in integrations
function consoleIntegration(options?: ConsoleOptions): Integration;
function httpIntegration(options?: HttpOptions): Integration;
function onUncaughtExceptionIntegration(options?: UncaughtExceptionOptions): Integration;
function onUnhandledRejectionIntegration(options?: UnhandledRejectionOptions): Integration;
function localVariablesIntegration(options?: LocalVariablesOptions): Integration;
function contextLinesIntegration(options?: ContextLinesOptions): Integration;
function anrIntegration(options?: ANROptions): Integration;Control how events are sent to Sentry.
/**
* Create a custom transport
* @param options - Transport configuration
* @returns Transport instance
*/
function createTransport(options: TransportOptions): Transport;
/**
* Create the default Node.js transport
* @param options - Transport configuration
* @returns Transport instance
*/
function makeNodeTransport(options: TransportOptions): Transport;
/**
* Continue a trace from headers
* @param headers - Headers containing trace information
* @param callback - Function to execute within the continued trace
* @returns Result of the callback
*/
function continueTrace<T>(
headers: { sentryTrace?: string; baggage?: string },
callback: () => T
): T;Track user sessions for release health monitoring.
/**
* Start a new session
* @param context - Session context
*/
function startSession(context?: SessionContext): void;
/**
* Capture the current session
*/
function captureSession(): void;
/**
* End the current session
*/
function endSession(): void;
interface SessionContext {
user?: User;
release?: string;
environment?: string;
}This comprehensive core functionality provides all the essential Sentry capabilities needed for error monitoring, performance tracking, and application observability in serverless environments.
Install with Tessl CLI
npx tessl i tessl/npm-sentry--serverless