Skip to main content
The Sentry AWS Lambda SDK provides error monitoring and performance tracking for serverless functions running on AWS Lambda with automatic integration and minimal configuration.

Installation

npm install @sentry/aws-serverless

Setup Methods

There are two ways to set up Sentry in AWS Lambda:

Basic Lambda Handler

// handler.js
export const handler = async (event, context) => {
  // Errors are automatically captured
  const data = await fetchData();
  
  return {
    statusCode: 200,
    body: JSON.stringify(data),
  };
};

Callback Handler

export const handler = (event, context, callback) => {
  try {
    const result = processEvent(event);
    callback(null, {
      statusCode: 200,
      body: JSON.stringify(result),
    });
  } catch (error) {
    // Error is automatically captured
    callback(error);
  }
};

Error Handling

Manual Error Capture

import * as Sentry from '@sentry/aws-serverless';

export const handler = async (event, context) => {
  try {
    const result = await riskyOperation();
    return {
      statusCode: 200,
      body: JSON.stringify(result),
    };
  } catch (error) {
    Sentry.captureException(error, {
      tags: {
        handler: 'processOrder',
        requestId: context.requestId,
      },
    });
    
    return {
      statusCode: 500,
      body: JSON.stringify({ error: 'Internal Server Error' }),
    };
  }
};

Validation Errors

import * as Sentry from '@sentry/aws-serverless';

export const handler = async (event) => {
  const body = JSON.parse(event.body);
  
  if (!body.email) {
    const error = new Error('Email is required');
    Sentry.captureException(error, {
      level: 'warning',
      tags: { validation: 'email' },
    });
    
    return {
      statusCode: 400,
      body: JSON.stringify({ error: 'Email is required' }),
    };
  }
  
  // Process valid request
};

Performance Monitoring

Custom Spans

import * as Sentry from '@sentry/aws-serverless';

export const handler = async (event, context) => {
  return await Sentry.startSpan(
    {
      name: 'process-order',
      op: 'function.aws.lambda',
      attributes: {
        orderId: event.orderId,
      },
    },
    async () => {
      const order = await fetchOrder(event.orderId);
      await processOrder(order);
      
      return {
        statusCode: 200,
        body: JSON.stringify({ success: true }),
      };
    },
  );
};

Database Operations

import * as Sentry from '@sentry/aws-serverless';
import { DynamoDBClient, GetItemCommand } from '@aws-sdk/client-dynamodb';

const client = new DynamoDBClient({});

export const handler = async (event) => {
  return await Sentry.startSpan(
    {
      name: 'dynamodb.getItem',
      op: 'db.query',
      attributes: {
        'db.system': 'dynamodb',
        'db.operation': 'GetItem',
      },
    },
    async () => {
      const result = await client.send(
        new GetItemCommand({
          TableName: 'Users',
          Key: { id: { S: event.userId } },
        })
      );
      
      return {
        statusCode: 200,
        body: JSON.stringify(result.Item),
      };
    },
  );
};

External API Calls

import * as Sentry from '@sentry/aws-serverless';

export const handler = async (event) => {
  return await Sentry.startSpan(
    {
      name: 'external-api-call',
      op: 'http.client',
    },
    async () => {
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();
      
      return {
        statusCode: 200,
        body: JSON.stringify(data),
      };
    },
  );
};

Context and Tags

Lambda Context

import * as Sentry from '@sentry/aws-serverless';

export const handler = async (event, context) => {
  // Set Lambda context
  Sentry.setContext('lambda', {
    functionName: context.functionName,
    functionVersion: context.functionVersion,
    requestId: context.requestId,
    memoryLimit: context.memoryLimitInMB,
  });
  
  // Set event context
  Sentry.setContext('event', {
    source: event.source,
    httpMethod: event.httpMethod,
    path: event.path,
  });
  
  // Your handler logic
};

User Identification

import * as Sentry from '@sentry/aws-serverless';

export const handler = async (event) => {
  // Extract user from event (e.g., API Gateway authorizer)
  const userId = event.requestContext?.authorizer?.userId;
  
  if (userId) {
    Sentry.setUser({ id: userId });
  }
  
  // Your handler logic
};

Sentry Lambda Layer

Use the official Sentry Lambda Layer for easier deployment:
1

Add Layer to Function

  1. Go to your Lambda function in AWS Console
  2. Choose LayersAdd Layer
  3. Specify ARN:
arn:aws:lambda:us-west-1:943013980633:layer:SentryNodeServerlessSDKv10:19
Get the latest ARN from the docs.
2

Configure Environment Variables

Add these environment variables:
NODE_OPTIONS="--import @sentry/aws-serverless/awslambda-auto"
SENTRY_DSN="your-dsn-here"
SENTRY_TRACES_SAMPLE_RATE="1.0"

Serverless Framework

Integrate with Serverless Framework:
# serverless.yml
service: my-service

provider:
  name: aws
  runtime: nodejs20.x
  environment:
    NODE_OPTIONS: --import ./instrument.js
    SENTRY_DSN: ${env:SENTRY_DSN}
    SENTRY_TRACES_SAMPLE_RATE: "1.0"
    SENTRY_ENVIRONMENT: ${self:provider.stage}

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: get

plugins:
  - serverless-plugin-scripts

custom:
  scripts:
    hooks:
      'after:deploy:deploy': npx sentry-cli releases new $SENTRY_RELEASE

AWS SAM

Configure with AWS SAM:
# template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Timeout: 30
    Environment:
      Variables:
        NODE_OPTIONS: --import ./instrument.js
        SENTRY_DSN: !Ref SentryDsn
        SENTRY_TRACES_SAMPLE_RATE: "1.0"

Parameters:
  SentryDsn:
    Type: String
    Description: Sentry DSN

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/
      Handler: handler.hello
      Runtime: nodejs20.x
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get

Environment Variables

Required

SENTRY_DSN=your-dsn-here

Optional

# Performance monitoring
SENTRY_TRACES_SAMPLE_RATE=1.0

# Environment tracking
SENTRY_ENVIRONMENT=production

# Release tracking
SENTRY_RELEASE=1.0.0

# Enable PII capture
SENTRY_SEND_DEFAULT_PII=true

Event Sources

API Gateway

import * as Sentry from '@sentry/aws-serverless';

export const handler = async (event) => {
  Sentry.setContext('apiGateway', {
    httpMethod: event.httpMethod,
    path: event.path,
    headers: event.headers,
  });
  
  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ message: 'Success' }),
  };
};

S3 Events

import * as Sentry from '@sentry/aws-serverless';

export const handler = async (event) => {
  for (const record of event.Records) {
    Sentry.setContext('s3', {
      bucket: record.s3.bucket.name,
      key: record.s3.object.key,
      size: record.s3.object.size,
    });
    
    try {
      await processS3Object(record);
    } catch (error) {
      Sentry.captureException(error);
    }
  }
};

SQS Events

import * as Sentry from '@sentry/aws-serverless';

export const handler = async (event) => {
  for (const record of event.Records) {
    try {
      const message = JSON.parse(record.body);
      await processMessage(message);
    } catch (error) {
      Sentry.captureException(error, {
        tags: {
          messageId: record.messageId,
          queue: record.eventSourceARN,
        },
      });
    }
  }
};

Best Practices

Use Layers

Use the official Sentry Lambda Layer for easier deployment and updates.

Instrument Early

Initialize Sentry before any other imports using NODE_OPTIONS.

Set Context

Add Lambda context and event data for better debugging.

Sample Wisely

Adjust tracesSampleRate based on traffic to control costs.

Troubleshooting

Ensure:
  1. NODE_OPTIONS is set correctly
  2. SENTRY_DSN is configured
  3. Lambda has internet access (or VPC endpoint)
  4. Function timeout is adequate for flushing events
Consider:
  1. Use asynchronous error reporting
  2. Reduce tracesSampleRate
  3. Enable Lambda SnapStart for faster cold starts

Next Steps

API Gateway

Integrate with API Gateway events

DynamoDB

Track database operations

Step Functions

Monitor workflow executions

Layers

Advanced Lambda Layer configuration