---
title: Vercel
description: "Integrate Statsig with Vercel to evaluate feature gates and experiments in edge middleware, server components, and serverless functions on Vercel."
product: general
token_estimate: 2542
---
# Vercel

> For AI agents: a documentation index is available at [/llms.txt](/llms.txt). Append `.md` to any page URL for markdown, or send `Accept: text/markdown`.

Statsig offers a suite of integration tools for use with Vercel:

- Statsig automatically pushes project changes to Vercel's Edge Config, providing low-latency SDK startup.
- Statsig provides a Vercel helper that handles client initialization and event flushing so you can focus on your business logic.

1. ****

   #### Configure integration

   1. Go to the [Vercel Marketplace](https://vercel.com/integrations/statsig) and install the Statsig integration.
   2. Statsig prompts you to create a new account or link an existing one.

   #### New Statsig Account

   - Click **Accept and Create**
   - Enable Edge Config Syncing to have Statsig automatically push configs into Vercel's Edge Config

   ![Vercel marketplace installation interface](https://docs.statsig.com/images/vercel_marketplace_install.png)

   After Statsig creates the account, select **Open in Statsig** in the top right to set up gates and experiments for your new Statsig project.

   ![Vercel marketplace project view interface](https://docs.statsig.com/images/vercel_marketplace_view.png)

   Your Statsig Integration for Vercel is complete!

   #### Existing Statsig Account

   - Select your project and edge config
   - Click **Save**

   Your Statsig Integration is now complete! You can go to the **storage** tab to confirm your Statsig config specs have propagated to your Edge Config.
2. ****

   #### Install the Statsig SDK

   ```bash
   npm install @statsig/vercel-edge
   ```
3. ****

   #### Import the Vercel helper

   ```bash
   import {handleWithStatsig} from '@statsig/vercel-edge
   ```
4. ****

   #### Use the SDK

   ```Javascript
   export default handleWithStatsig(handler, params)
   ```

   The helper method takes two arguments:

   - `handler` Your Vercel function code
   - `params`

     | Parameter | Optional | Type | Description |
     | --- | --- | --- | --- |
     | `configKey` | No | `string` | The Key associated with your Statsig specs in your Edge Config |
     | `envStatsigKey` | No | `string` | Your Statsig Client API Key |
     | `statsigOptions` | Yes | `StatsigOptions` | Refer to [StatsigOptions](https://docs.statsig.com/client/javascript-sdk#statsig-options) |

   Best practice: store `configKey` and `envStatsigKey` as environment variables in your Vercel project settings.

### Example usage

```javascript
import { handleWithStatsig } from "@statsig/vercel-edge";

export const config = {runtime: 'edge'};

async function myHandler(request, client){
    const user = { userID: Math.random().toString().substring(2, 5) }; //Generates a random user id
    const passed = client.checkGate('test_vercel_edgeconfig', user);
    client.logEvent('vercel_wrapper', user, passed.toString());
    return new Response(
      JSON.stringify({ passed, user })
    );

export default handleWithStatsig(myHandler,{
    configKey : process.env.EDGE_CONFIG_KEY,
    statsigSdkKey: process.env.STATSIG_KEY
})
```

#### How it Works

The `handler` parameter is your Vercel function code: the same code you would normally export directly in your API route (for example, `myHandler` in the snippet above). Instead of exporting it directly, pass it into `handleWithStatsig`, which handles Statsig setup and cleanup.

When your function runs:

1. The Statsig SDK initializes a client using the config specs stored in your Edge Config.
2. Your function code (the handler) runs as usual.
3. Statsig automatically flushes any events you log when execution finishes.

The helper automatically:

- Initializes the Statsig Client with config specs from your Edge Config
- Executes your Vercel function code (your business logic and Statsig usage)
- Flushes all events after your handler completes execution
- Cleans up resources

## Advanced implementation

#### Advanced/manual usage

Use the advanced/manual setup if:

- You need fine-grained control over initialization timing
- You need fine-grained control over event flushing timing
- You need to customize error handling behavior

### Prerequisites

- Completed the [Statsig Vercel integration setup](#configure-integration)

1. **Install the Statsig SDK**

   ```bash
   npm install @statsig/vercel-edge
   ```
2. **Import the Statsig SDK**

   ```bash
   import {StatsigVercelClient} from '@statsig/vercel-edge'
   ```
3. **Create a StatsigVercelClient instance**

   ```javascript
   const client = new StatsigVercelClient(process.env.STATSIG_KEY)
   ```

   The client instantiation takes two arguments:

   - `sdkKey : string` Your Statsig client API key. Available from the [Project Settings](https://console.statsig.com/api_keys) page in the Statsig Console. Statsig uses the key to authenticate requests.
   - `options : StatsigOptions` Refer to [StatsigOptions](https://docs.statsig.com/client/javascript-sdk#statsig-options) for more options.

   Best practice: store `sdkKey` as an environment variable in your Vercel project settings.
4. **Client Initialization**

   This line initializes the client by loading feature gate and experiment configurations directly from your Vercel Edge Config.

   ```javascript
   const init = await client.initializeFromEdgeConfig(<YOUR_EDGE_CONFIG_KEY>);
   ```

   The client initialization takes one argument:

   - `ConfigKey : string` The Key associated with your Statsig specs in your Edge Config
5. **Checking a Gate**

   ```javascript
   const GateResult = client.checkGate('pass_gate', user);
   ```

   The `checkGate` method takes two arguments:

   - `name : string` The name of the Statsig gate to check.
   - `user : StatsigUser` The Statsig user object for whom you check the gate. For more information on the user object, refer to [StatsigUser](https://docs.statsig.com/sdks/user#introduction-to-the-statsiguser-object).

   Refer to the [JavaScript on-device evaluation SDK documentation](https://docs.statsig.com/client/jsOnDeviceEvaluationSDK) for how to check other entities like experiments and dynamic configs.
6. ****

   ```javascript
   client.logEvent('gate_check', { userID: randomUserId });
   ```

   The `logEvent` method takes two parameters:

   - `eventOrName : string | StatsigEvent` The name and details of the event to log.
   - `user : StatsigUser` The Statsig user object for whom you log the event.

   For more information on event logging, refer to [Logging an Event](https://docs.statsig.com/client/jsOnDeviceEvaluationSDK#logging-an-event).
7. ****

   ```javascript
   waitUntil(statsig.flush());
   ```

   This flushes all events from the SDK to Statsig. Without the flush call, diagnostic information and logged event data won't appear in the Statsig Console.

### Putting it all together

```javascript
import { StatsigVercelClient } from '@statsig/vercel-edge';
import { waitUntil } from '@vercel/functions';

export const config = {
  runtime: 'edge', 
};

export default async function handler(request) {
    const client = new StatsigVercelClient(process.env.STATSIG_KEY);
    
    let init = await client.initializeFromEdgeConfig(process.env.EDGE_CONFIG_KEY);
    
    const user = { userID: Math.random().toString().substring(2, 5) };
    const passed = client.checkGate('pass_gate', user);
    
    client.logEvent('vercel_event', user, passed.toString());
    
    waitUntil(client.flush())

    return new Response(
      JSON.stringify({ passed, user }),
    );
}
```

## Other considerations

### Polling for updates v5.13.0+

The SDK can't poll for updates across requests because Vercel Edge Functions don't allow timers outside the request handler. Statsig doesn't provide an API to detect config spec updates. When you change your project definition in the Statsig console, the changes propagate to your Edge Config. The changes take effect the next time you initialize the Statsig client.

### Flushing events v4.16.0+

The SDK enqueues logged events and flushes them in batches. To ensure the SDK flushes events, call flush using `waitUntil()` from `@vercel/functions`. The `waitUntil()` call keeps the request handler alive until the SDK flushes events, without blocking the response.

```plaintext
waitUntil(client.flush());
```

### Size limits

Vercel Edge Config has maximum size limits that may prevent Statsig from pushing configs into your Edge Config. Refer to [Vercel Edge Config limits](https://vercel.com/docs/concepts/edge-network/edge-config/edge-config-limits) for the current limits.

### Unsupported features

Statsig doesn't sync ID Lists into Vercel Edge Config. If you rely on large (>1000) ID lists, you can't check them in your Vercel edge functions. Because Statsig doesn't sync ID lists, the SDK sets `initStrategyForIDLists: 'none'` during initialization.

To review evaluations, go to the gate you created and check the Diagnostics tab.

![Diagnostics Stream](https://docs.statsig.com/images/integrations/vercel/2b690181-0103-43be-b791-7cf0a7db66eb.png)

To check the events you logged, in the **Statsig Console**, go to **Data** -> **Events**.

![vercel_event example in Statsig showing lineage chart and log stream table](../images/client/vercel_event.png)

The Vercel Edge Config integration for Statsig is now working.

## Using Flags SDK in NextJS

If you use NextJS in your Vercel project, you can use Statsig through Flags SDK and take advantage of built-in precompute patterns for improved performance. Refer to the [Statsig Adapter for Flags SDK docs](https://flags-sdk.dev/docs/api-reference/adapters/statsig) for setup steps. The marketplace app sets all required environment variables for the Flags SDK by default.

## Sending logs to Statsig

You can connect your Vercel logs to Statsig with a Log Drain to start exploring them in Logs Explorer.

1. From the [Vercel dashboard](https://vercel.com/), go to **Settings -> Drains** and click **Add Drain -> Integration**.
2. Select **Statsig**, follow the configuration steps provided, and choose a project to connect with the service.
3. Navigate to [Statsig's Logs Explorer](https://console.statsig.com/logs) to see your logs flow through.

