# Using Statsig in Serverless Environments

> 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's server SDKs run in serverless environments such as Google Cloud Functions, Cloudflare Workers, and Fastly Compute. Initialize the SDK, evaluate gates and configs locally inside the function, then call `statsig.flush()` before the function exits to send queued exposure and custom events. The examples use the `statsig-node` SDK in a Google Cloud Function, so adjust the implementation for your cloud provider.

## How Statsig runs in serverless environments

Statsig server SDKs work in serverless environments. If you can't call `initialize` outside of a serverless function, the SDK makes a server round trip to Statsig servers to initialize on every function invocation.

After initialization, the SDK evaluates all checks locally within the function.

Before the function exits, flush any enqueued events (exposure and custom events) to Statsig by calling `statsig.flush()`. Refer to the [Node.js SDK flushing documentation](https://docs.statsig.com/server/nodejsServerSDK#flushing-events-) for the Cloudflare example.

## Google Cloud Function example

The following example includes debugging information to show the cost of initializing the SDK in a cloud function. The `initialize` call typically takes less than a second, and subsequent function invocations don't incur this startup cost.

```javascript
const statsig = require('statsig-node');

let requestsHandled = 0;
const initStart = Date.now();
let initEnd = 0;
let initialized = false;

const initializationPromise = statsig.initialize(process.env.sdkKey).then(() => {
  initEnd = Date.now();
  initialized = true;
});

exports.statsig = async (req, res) => {
  const functionStart = Date.now();
  requestsHandled++;

  if (!initialized) {
    await initializationPromise;
  }

  const alwaysOnGateValue = await statsig.checkGate({userID: 'gcp'}, 'always_on_gate');
  const functionEnd = Date.now();

  res.status(200).send({
    initStart,
    initEnd,
    functionStart,
    functionEnd,
    requestsHandled,
    initializeTime: initEnd - initStart,
    functionTime: functionEnd - functionStart,
    alwaysOnGateValue: alwaysOnGateValue,
  });
};
```

## Alternative: Database-backed initialization

If the standard initialization approach doesn't work, you can set up a custom integration, though it requires additional setup. For example, you could create a background function that fetches your definitions from Statsig servers periodically and stores them in your database. When initializing a Statsig server SDK, fetch the values from your database instead of making a request to Statsig servers.

[Reach out in Slack](https://www.statsig.com/slack) to discuss how to adapt Statsig to your architecture.

## Fastly implementation

Some Fastly account settings enable an extra security layer that requires a custom `fetch` method for network requests to third-party domains. Implement a custom `fetch` method that uses Fastly's required [backend parameter](https://js-compute-reference-docs.edgecompute.app/docs/globals/fetch).

First, define a module in its own file that implements a global override of `fetch`:

```javascript
export { };

const ogFetch = fetch.bind(fetch.prototype);

globalThis.fetch = (input, init) => {
  const backend: string = input instanceof URL ? input.hostname :
    input instanceof Request ? new URL(input.url).hostname :
    new URL(input).hostname;

  const initWithBackend: typeof init = { ...init, backend };

  return ogFetch(input, initWithBackend);
}

(globalThis as any).EdgeRuntime = "fastly";
```

Next, in the main function entrypoint, import the fetch override module before importing the Statsig SDK:

```javascript
import "./providers/utils/fastly-fetch-setup";
import Statsig from "statsig-node";
```
