Official Sentry SDK for various serverless solutions including AWS Lambda and Google Cloud Functions
—
Complete Google Cloud Functions support with HTTP function wrapping, event function handling, cloud event processing, and performance tracing capabilities specifically designed for the GCP serverless environment.
Initialize the Sentry GCP Functions SDK with platform-specific configurations and integrations.
/**
* Initialize Sentry for Google Cloud Functions
* @param options - Configuration options for the SDK
*/
function init(options?: NodeOptions): void;Usage Examples:
import { GCPFunction } from "@sentry/serverless";
// Basic initialization
GCPFunction.init({
dsn: "your-dsn-here",
});
// With performance tracing
GCPFunction.init({
dsn: "your-dsn-here",
tracesSampleRate: 1.0,
environment: "production",
});Wrap HTTP functions (Express-style request/response handlers) with error capture and performance tracing.
/**
* Wraps an HTTP function handler adding error capture and tracing capabilities
* @param fn - HTTP handler function
* @param wrapOptions - Optional configuration for wrapper behavior
* @returns Wrapped HTTP function with Sentry capabilities
*/
function wrapHttpFunction(
fn: HttpFunction,
wrapOptions?: Partial<HttpFunctionWrapperOptions>
): HttpFunction;
interface HttpFunction {
(req: Request, res: Response): any;
}
interface HttpFunctionWrapperOptions extends GCPWrapperOptions {
/** Configuration for adding request data to events */
addRequestDataToEventOptions?: AddRequestDataToEventOptions;
/** @deprecated Use addRequestDataToEventOptions instead */
parseRequestOptions?: ParseRequestOptions;
}
interface AddRequestDataToEventOptions {
include?: {
request?: ('cookies' | 'data' | 'headers' | 'method' | 'query_string' | 'url')[];
user?: ('id' | 'username' | 'email' | 'ip_address')[];
};
}
interface GCPWrapperOptions {
/** Timeout for flushing events before function terminates (default: 2000ms) */
flushTimeout: number;
}Usage Examples:
import { GCPFunction } from "@sentry/serverless";
// Basic HTTP function wrapping
exports.helloHttp = GCPFunction.wrapHttpFunction((req, res) => {
res.send("Hello World!");
});
// With request data capturing
exports.apiHandler = GCPFunction.wrapHttpFunction((req, res) => {
const { name } = req.body;
res.json({ message: `Hello ${name}!` });
}, {
addRequestDataToEventOptions: {
include: {
request: ['headers', 'method', 'url'],
user: ['id', 'email']
}
}
});
// Error handling example
exports.errorHandler = GCPFunction.wrapHttpFunction((req, res) => {
if (!req.body.data) {
throw new Error("Missing data parameter");
}
res.json({ success: true });
});Wrap background event functions with error capture and performance tracing.
/**
* Wraps an event function handler adding error capture and tracing capabilities
* @param fn - Event handler function (with or without callback)
* @param wrapOptions - Optional configuration for wrapper behavior
* @returns Wrapped event function with Sentry capabilities
*/
function wrapEventFunction(
fn: EventFunction | EventFunctionWithCallback,
wrapOptions?: Partial<EventFunctionWrapperOptions>
): EventFunctionWithCallback;
interface EventFunction {
(data: Record<string, any>, context: Context): any;
}
interface EventFunctionWithCallback {
(data: Record<string, any>, context: Context, callback: Function): any;
}
type EventFunctionWrapperOptions = GCPWrapperOptions;Usage Examples:
import { GCPFunction } from "@sentry/serverless";
// Basic event function (async)
exports.processEvent = GCPFunction.wrapEventFunction(async (data, context) => {
console.log(`Processing event: ${context.eventType}`);
await processEventData(data);
});
// Event function with callback
exports.processEventCallback = GCPFunction.wrapEventFunction((data, context, callback) => {
console.log(`Event ID: ${context.eventId}`);
processEventData(data)
.then(() => callback())
.catch(callback);
});
// Pub/Sub message processing
exports.processPubSubMessage = GCPFunction.wrapEventFunction((message, context) => {
const data = message.data ? Buffer.from(message.data, 'base64').toString() : 'No data';
console.log(`Received message: ${data}`);
// Process the message
return processMessage(JSON.parse(data));
});Wrap Cloud Event functions (CloudEvents specification) with error capture and performance tracing.
/**
* Wraps a cloud event function handler adding error capture and tracing capabilities
* @param fn - Cloud event handler function (with or without callback)
* @param wrapOptions - Optional configuration for wrapper behavior
* @returns Wrapped cloud event function with Sentry capabilities
*/
function wrapCloudEventFunction(
fn: CloudEventFunction | CloudEventFunctionWithCallback,
wrapOptions?: Partial<CloudEventFunctionWrapperOptions>
): CloudEventFunctionWithCallback;
interface CloudEventFunction {
(cloudevent: CloudEventsContext): any;
}
interface CloudEventFunctionWithCallback {
(cloudevent: CloudEventsContext, callback: Function): any;
}
type CloudEventFunctionWrapperOptions = GCPWrapperOptions;Usage Examples:
import { GCPFunction } from "@sentry/serverless";
// Basic cloud event function (async)
exports.handleCloudEvent = GCPFunction.wrapCloudEventFunction(async (cloudEvent) => {
console.log(`Event type: ${cloudEvent.type}`);
console.log(`Event source: ${cloudEvent.source}`);
// Process the cloud event
await processCloudEvent(cloudEvent);
});
// Cloud event function with callback
exports.handleCloudEventCallback = GCPFunction.wrapCloudEventFunction((cloudEvent, callback) => {
console.log(`Event ID: ${cloudEvent.id}`);
console.log(`Event time: ${cloudEvent.time}`);
processCloudEvent(cloudEvent)
.then(() => callback())
.catch(callback);
});
// Storage event processing
exports.processStorageEvent = GCPFunction.wrapCloudEventFunction((cloudEvent) => {
if (cloudEvent.type === 'google.cloud.storage.object.v1.finalized') {
const fileName = cloudEvent.data?.name;
console.log(`File uploaded: ${fileName}`);
return processUploadedFile(fileName);
}
});Get the default integrations configured for Google Cloud Functions environment.
/**
* Get the default integrations for the GCP SDK
* @param options - SDK options to configure integrations
* @returns Array of default integrations including Google Cloud integrations
*/
function getDefaultIntegrations(options: Options): Integration[];
/** @deprecated Use getDefaultIntegrations(options) instead */
const defaultIntegrations: Integration[];Usage Examples:
import { GCPFunction } from "@sentry/serverless";
// Get default integrations
const integrations = GCPFunction.getDefaultIntegrations({
// configuration options
});
// Use in custom initialization
GCPFunction.init({
dsn: "your-dsn-here",
integrations: [
...GCPFunction.getDefaultIntegrations({}),
// Add additional custom integrations
]
});interface CloudFunctionsContext {
/** Unique event identifier */
eventId?: string;
/** Event timestamp in ISO format */
timestamp?: string;
/** Type of the triggering event */
eventType?: string;
/** Resource that triggered the event */
resource?: string;
}
interface CloudEventsContext {
[key: string]: any;
/** Event type (e.g., 'com.example.string.sent') */
type?: string;
/** CloudEvents specification version */
specversion?: string;
/** Event producer identifier */
source?: string;
/** Unique event identifier */
id?: string;
/** Event timestamp */
time?: string;
/** Schema URL for the event data */
schemaurl?: string;
/** Content type of the event data */
contenttype?: string;
}
type Context = CloudFunctionsContext | CloudEventsContext;
// Express types re-exported for convenience
type Request = import('express').Request;
type Response = import('express').Response;The GCP Functions integration automatically enhances Sentry scopes with function-specific context:
// Automatically added to scope for event and cloud event functions
{
"gcp.function.context": {
"eventId": "1234567890",
"timestamp": "2023-01-01T12:00:00.000Z",
"eventType": "google.pubsub.topic.publish",
"resource": "projects/my-project/topics/my-topic"
}
}For HTTP functions, request data is automatically captured based on configuration:
// Automatically added for HTTP functions
{
"request": {
"method": "POST",
"url": "https://us-central1-project.cloudfunctions.net/my-function",
"headers": {
"content-type": "application/json",
"user-agent": "Mozilla/5.0..."
}
}
}The GCP Functions integration provides comprehensive error handling:
Automatic performance tracing capabilities:
import { GCPFunction, startSpan } from "@sentry/serverless";
exports.complexHandler = GCPFunction.wrapHttpFunction((req, res) => {
return startSpan({ name: "process-request", op: "function" }, async (span) => {
span.setTag("request-type", req.headers['content-type']);
const result = await processRequest(req.body);
res.json(result);
});
});The SDK includes automatic integrations for Google Cloud services:
These integrations automatically instrument Google Cloud client libraries to provide visibility into service calls made from your functions.
Install with Tessl CLI
npx tessl i tessl/npm-sentry--serverless