> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/getsentry/sentry-javascript/llms.txt
> Use this file to discover all available pages before exploring further.

# AWS Lambda SDK

> Error monitoring and performance tracking for AWS Lambda functions

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

<CodeGroup>
  ```bash npm theme={null}
  npm install @sentry/aws-serverless
  ```

  ```bash yarn theme={null}
  yarn add @sentry/aws-serverless
  ```

  ```bash pnpm theme={null}
  pnpm add @sentry/aws-serverless
  ```
</CodeGroup>

## Setup Methods

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

<Tabs>
  <Tab title="Automatic (Recommended)">
    Use environment variables for zero-code setup:

    ```bash theme={null}
    NODE_OPTIONS="--import @sentry/aws-serverless/awslambda-auto"
    SENTRY_DSN="your-dsn-here"
    SENTRY_TRACES_SAMPLE_RATE="1.0"
    ```

    Configure these in your Lambda function settings or deployment configuration.
  </Tab>

  <Tab title="Manual">
    Create an instrumentation file for custom configuration:

    ```javascript theme={null}
    // instrument.js
    import * as Sentry from '@sentry/aws-serverless';

    Sentry.init({
      dsn: 'YOUR_DSN_HERE',
      
      // Performance Monitoring
      tracesSampleRate: 1.0,
      
      // Capture request data
      sendDefaultPii: true,
      
      // Environment
      environment: process.env.ENVIRONMENT,
    });
    ```

    Load it using NODE\_OPTIONS:

    ```bash theme={null}
    NODE_OPTIONS="--import ./instrument.js"
    ```
  </Tab>
</Tabs>

## Basic Lambda Handler

### Async Handler (Recommended)

```javascript theme={null}
// 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

```javascript theme={null}
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

```javascript theme={null}
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

```javascript theme={null}
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

```javascript theme={null}
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

```javascript theme={null}
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

```javascript theme={null}
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

```javascript theme={null}
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

```javascript theme={null}
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:

<Steps>
  <Step title="Add Layer to Function">
    1. Go to your Lambda function in AWS Console
    2. Choose **Layers** → **Add Layer**
    3. Specify ARN:

    ```
    arn:aws:lambda:us-west-1:943013980633:layer:SentryNodeServerlessSDKv10:19
    ```

    Get the latest ARN from the [docs](https://docs.sentry.io/platforms/javascript/guides/aws-lambda/install/layer).
  </Step>

  <Step title="Configure Environment Variables">
    Add these environment variables:

    ```bash theme={null}
    NODE_OPTIONS="--import @sentry/aws-serverless/awslambda-auto"
    SENTRY_DSN="your-dsn-here"
    SENTRY_TRACES_SAMPLE_RATE="1.0"
    ```
  </Step>
</Steps>

## Serverless Framework

Integrate with Serverless Framework:

```yaml theme={null}
# 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:

```yaml theme={null}
# 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

```bash theme={null}
SENTRY_DSN=your-dsn-here
```

### Optional

```bash theme={null}
# 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

```javascript theme={null}
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

```javascript theme={null}
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

```javascript theme={null}
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

<CardGroup cols={2}>
  <Card title="Use Layers" icon="layer-group">
    Use the official Sentry Lambda Layer for easier deployment and updates.
  </Card>

  <Card title="Instrument Early" icon="bolt">
    Initialize Sentry before any other imports using NODE\_OPTIONS.
  </Card>

  <Card title="Set Context" icon="tag">
    Add Lambda context and event data for better debugging.
  </Card>

  <Card title="Sample Wisely" icon="filter">
    Adjust tracesSampleRate based on traffic to control costs.
  </Card>
</CardGroup>

## Troubleshooting

<Accordion title="Events Not Captured">
  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
</Accordion>

<Accordion title="High Latency">
  Consider:

  1. Use asynchronous error reporting
  2. Reduce tracesSampleRate
  3. Enable Lambda SnapStart for faster cold starts
</Accordion>

## Next Steps

<CardGroup cols={2}>
  <Card title="API Gateway" icon="route" href="/api-gateway">
    Integrate with API Gateway events
  </Card>

  <Card title="DynamoDB" icon="database" href="/dynamodb">
    Track database operations
  </Card>

  <Card title="Step Functions" icon="diagram-project" href="/step-functions">
    Monitor workflow executions
  </Card>

  <Card title="Layers" icon="layer-group" href="/lambda-layers">
    Advanced Lambda Layer configuration
  </Card>
</CardGroup>
