# Serverless Error Tracking and Performance Monitoring

> Trace long page-loads & poor performing API calls to optimize your app with Serverless error & performance monitoring. Get started with Sentry today.

**URL:** https://sentry.io/for/serverless/

---

Using Sentry for Serverless makes debugging as painless as possible, so you can keep everything up and running.

**Documentation:** [https://docs.sentry.io/](https://docs.sentry.io/)

## Install

### AWS Lambda Node

Add `@sentry/aws-serverless` as a dependency:

```bash
npm install --save @sentry/aws-serverless
```

Then set these environment variables in your Lambda function configuration to load and initialize the SDK automatically:

```bash
NODE_OPTIONS="--import @sentry/aws-serverless/awslambda-auto"
SENTRY_DSN="https://<key>@sentry.io/<project>"
SENTRY_TRACES_SAMPLE_RATE="1.0"
```

Redeploy your function and you're all set. Prefer not to deploy any Sentry dependencies with your function? Use the [Sentry AWS Lambda Layer](https://docs.sentry.io/platforms/javascript/guides/aws-lambda/install/layer/) instead.

See the [AWS Lambda Node docs](https://docs.sentry.io/platforms/javascript/guides/aws-lambda/) for full setup options.

### AWS Lambda Python

Install our Python SDK into your deployment package using `pip`:

```bash
pip install --target ./package --upgrade sentry-sdk
```

Then use the AWS Lambda integration for the Python SDK like this:

```python
import sentry_sdk
from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration

sentry_sdk.init(
    dsn="https://<key>@sentry.io/<project>",
    # Add data like request headers and IP for users, if applicable;
    # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info
    send_default_pii=True,
    # Set traces_sample_rate to 1.0 to capture 100%
    # of transactions for tracing.
    # We recommend adjusting this value in production.
    traces_sample_rate=1.0,
    integrations=[AwsLambdaIntegration()],
)

def lambda_handler(event, context):
    # ...
```

See the [AWS Lambda Python docs](https://docs.sentry.io/platforms/python/integrations/aws-lambda/) for full setup options.

### Google Cloud Functions Node

Add `@sentry/google-cloud-serverless` as a dependency:

```bash
npm install --save @sentry/google-cloud-serverless
```

Then initialize Sentry at the top of your function code and wrap your function:

```javascript
const Sentry = require("@sentry/google-cloud-serverless");

Sentry.init({
  dsn: "https://<key>@sentry.io/<project>",
  tracesSampleRate: 1.0,
});

exports.helloHttp = Sentry.wrapHttpFunction((req, res) => {
  throw new Error("oh, hello there!");
});
```

See the [Google Cloud Functions Node docs](https://docs.sentry.io/platforms/javascript/guides/gcp-functions/) for full setup options.

### Google Cloud Functions Python

Add the Sentry SDK to your `requirements.txt`:

```text
sentry-sdk
```

Then use the GCP Functions integration for the Python SDK like this:

```python
import sentry_sdk
from sentry_sdk.integrations.gcp import GcpIntegration

sentry_sdk.init(
    dsn="https://<key>@sentry.io/<project>",
    # Add data like request headers and IP for users, if applicable;
    # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info
    send_default_pii=True,
    # Set traces_sample_rate to 1.0 to capture 100%
    # of transactions for tracing.
    # We recommend adjusting this value in production.
    traces_sample_rate=1.0,
    integrations=[GcpIntegration()],
)

def http_function_entrypoint(request):
    # ...
```

The GCP integration supports the Python 3.7 runtime. On newer runtimes, use the [`serverless_function` decorator](https://docs.sentry.io/platforms/python/integrations/serverless/) instead.

See the [Google Cloud Functions Python docs](https://docs.sentry.io/platforms/python/integrations/gcp-functions/) for full setup options.

### Microsoft Azure Node

Add `@sentry/node` as a dependency:

```bash
npm install --save @sentry/node
```

Then set up Sentry error logging for an Azure Function:

```javascript
"use strict";

const Sentry = require("@sentry/node");

Sentry.init({
  dsn: "https://<key>@sentry.io/<project>",
  tracesSampleRate: 1.0,
});

module.exports = async function(context, req) {
  try {
    await notExistFunction();
  } catch (e) {
    Sentry.captureException(e);
    await Sentry.flush(2000);
  }

  context.res = {
    status: 200,
    body: "Hello from Azure Cloud Function!",
  };
};
```

See the [Microsoft Azure Node docs](https://docs.sentry.io/platforms/javascript/guides/azure-functions/) for full setup options.

### Cloudflare Pages

Add `@sentry/cloudflare` as a dependency:

```bash
npm install --save @sentry/cloudflare
```

Set the `nodejs_compat` compatibility flag and a `compatibility_date` of `2024-09-23` or later in your `wrangler.json`:

```json
{
  "compatibility_flags": [
    "nodejs_compat"
  ],
  "compatibility_date": "2024-09-23"
}
```

Then add the Sentry middleware to your Cloudflare Pages functions in `functions/_middleware.js`:

```javascript
import * as Sentry from "@sentry/cloudflare";

export const onRequest = [
  // Make sure Sentry is the first middleware
  Sentry.sentryPagesPlugin((context) => ({
    dsn: 'https://<key>@sentry.io/<project>',
    tracesSampleRate: 1.0,
  })),
  // Add more middlewares here
];
```

See the [Cloudflare Pages docs](https://docs.sentry.io/platforms/javascript/guides/cloudflare/features/pages/) for full setup options.

### Cloudflare Workers

Add `@sentry/cloudflare` as a dependency:

```bash
npm install --save @sentry/cloudflare
```

Set the `nodejs_compat` compatibility flag and a `compatibility_date` of `2024-09-23` or later in your `wrangler.json`:

```json
{
  "compatibility_flags": [
    "nodejs_compat"
  ],
  "compatibility_date": "2024-09-23"
}
```

Then wrap your handler with the `withSentry` function:

```javascript
import * as Sentry from "@sentry/cloudflare";

export default Sentry.withSentry(
  (env) => ({
    dsn: 'https://<key>@sentry.io/<project>',
    tracesSampleRate: 1.0,
  }),
  {
    async fetch(request, env, ctx) {
      return new Response('Hello World!');
    },
  }
);
```

See the [Cloudflare Workers docs](https://docs.sentry.io/platforms/javascript/guides/cloudflare/) for full setup options.

### Cloud Functions for Firebase

Add `@sentry/node` as a dependency:

```bash
npm install --save @sentry/node
```

Create an initialization file (e.g., `instrument.ts`) that runs before your functions:

```javascript
import * as Sentry from '@sentry/node';

Sentry.init({
  dsn: 'https://<key>@sentry.io/<project>',
  tracesSampleRate: 1.0,
});
```

Import the initialization file at the top of your functions entry point:

```javascript
import './instrument'; // Import Sentry initialization first

import { onRequest } from 'firebase-functions/https';
import { onDocumentCreated } from 'firebase-functions/firestore';
import * as admin from 'firebase-admin';

admin.initializeApp();
const db = admin.firestore();

// HTTP function - automatically instrumented
export const helloWorld = onRequest(async (request, response) => {
  response.send('Hello from Firebase!');
});

// Firestore trigger - automatically instrumented
export const onUserCreated = onDocumentCreated('users/{userId}', async (event) => {
  const userId = event.params.userId;
  // Your logic here
});
```

See the [Cloud Functions for Firebase docs](https://docs.sentry.io/platforms/javascript/guides/firebase/) for full setup options.

## Features

### Code-Level Visibility

View stack traces on issues, user-agent information, and all the metadata around an issue for all the context needed to resolve the issue.

### Quickly Identify Function Latencies

Trace those ten-second page loads to poor-performing API calls and slow database queries. The event detail waterfall visually highlights what calls are giving your customers a poor experience.

### Fill in the Gaps

See what happened leading up to the issue. Get function execution details including function metadata, execution time, Amazon Resource Name, and function identity.

## FAQ

**How does Sentry differentiate from CloudWatch or Stackdriver?**

Sentry uses run-time instrumentation to capture errors. This allows users to get to the root of the problems using stack traces, breadcrumbs, function context and environment context.

CloudWatch/Stackdriver logs and metrics are hard to use to debug issues. The information is limited to some log statements and usually don't have the context needed to debug issues.

**What's the difference between run-time instrumentation versus Log Forwarding?**

Sentry uses run-time instrumentation to get real time visibility into execution environment and report all relevant info to be able to quickly debug issues. For example source code visibility when issues occur.

CloudWatch or Stackdriver log forwarding requires parsing through logs and usually are limited to details that already exist in logs.

**Does Sentry capture anything other than errors?**

Sentry supports distributed tracing in addition to error monitoring for serverless functions.

**How much does Sentry cost?**

You can get started for free. Pricing depends on the number of monthly events, transactions, and attachments that you send Sentry. For more details, visit our [pricing page](/pricing/).

---

*Source: [sentry.io/for/serverless/](https://sentry.io/for/serverless/)*
