
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.

{% steps %}
{% step %}
#### 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.

{% accordion-group %}
{% accordion title="New Statsig Account" %}
* Click **Accept and Create**
* Enable Edge Config Syncing to have Statsig automatically push configs into Vercel's Edge Config

{% figure %}
![Vercel marketplace installation interface](/images/vercel_marketplace_install.png)
{% /figure %}

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

{% figure %}
![Vercel marketplace project view interface](/images/vercel_marketplace_view.png)
{% /figure %}

Your Statsig Integration for Vercel is complete!
{% /accordion %}

{% accordion title="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.
{% /accordion %}
{% /accordion-group %}
{% /step %}

{% step %}
#### Install the Statsig SDK

```bash
npm install @statsig/vercel-edge
```
{% /step %}

{% step %}
#### import the Vercel helper

```bash
import {handleWithStatsig} from '@statsig/vercel-edge
```
{% /step %}

{% step %}
#### 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](/client/javascript-sdk#statsig-options) |

Best practice: store `configKey` and `envStatsigKey` as environment variables in your Vercel project settings.
{% /step %}
{% /steps %}

### Example Usage

```javascript api/index.js
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
})
```

{% accordion title="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.
{% /accordion %}

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

{% accordion title="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)

{% steps %}
{% step title="Install the Statsig SDK" %}
```bash
npm install @statsig/vercel-edge
```
{% /step %}

{% step title="Import the Statsig SDK" %}
```bash
import {StatsigVercelClient} from '@statsig/vercel-edge'
```
{% /step %}

{% step title="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 this to authenticate requests.
* `options : StatsigOptions` Refer to [StatsigOptions](/client/javascript-sdk#statsig-options) for more options.

Best practice: store `sdkKey` as an environment variable in your Vercel project settings.
{% /step %}

{% step title="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
{% /step %}

{% step title="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 the gate is checked. For more information on the user object, refer to [StatsigUser](/sdks/user#introduction-to-the-statsiguser-object).

Refer to the [JavaScript on-device evaluation SDK documentation](/client/jsOnDeviceEvaluationSDK) for how to check other entities like experiments and dynamic configs.
{% /step %}

{% step %}
```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 the event is logged.

For more information on event logging, refer to [Logging an Event](/client/jsOnDeviceEvaluationSDK#logging-an-event).
{% /step %}

{% step %}
```javascript
waitUntil(statsig.flush());
```

This flushes all events from the SDK to Statsig. **Without this, diagnostic information and logged event data won't appear in the Statsig Console**.
{% /step %}
{% /steps %}

### Putting it all together

```javascript api/index.js
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 and 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`. This keeps the request handler alive until events are flushed without blocking the response.

```
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. This is why the SDK sets `initStrategyForIDLists: 'none'` during initialization.
{% /accordion %}

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

{% figure %}
![Diagnostics Stream](/images/integrations/vercel/2b690181-0103-43be-b791-7cf0a7db66eb.png)
{% /figure %}

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

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

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.
