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

# Evaluate flags with OpenFeature

> Register a shipd provider and evaluate flags through the OpenFeature SDK for JavaScript or Go.

## Overview

Use OpenFeature to evaluate shipd boolean, string, number, and JSON flags. The TypeScript provider is a release candidate for Node.js 20+. The Go provider is available starting in shipd Go SDK v0.3.0 and requires Go 1.23 or later and OpenFeature Go SDK v1.15.1 or later in the v1 series.

See the [OpenFeature changelog](https://docs.useshipd.com/changelog/openfeature.md) for release candidate availability.

## Install and register

Create a [server SDK key](https://docs.useshipd.com/concepts/keys.md) and set `SHIPD_SDK_KEY` in your server environment.

### TypeScript

```bash theme={null}
npm install @shipdit/openfeature@rc @openfeature/server-sdk@^1.23.0
```

```ts index.ts theme={null}
import { OpenFeature } from "@openfeature/server-sdk";
import { ShipdProvider } from "@shipdit/openfeature";

await OpenFeature.setProviderAndWait(new ShipdProvider({
  sdkKey: process.env.SHIPD_SDK_KEY!,
}));

const client = OpenFeature.getClient("checkout");
const enabled = await client.getBooleanValue("new-checkout", false, {
  targetingKey: "usr_8f2k19",
  plan: "pro",
});

// Run during your application's shutdown sequence.
await OpenFeature.close();
```

### Go

```bash theme={null}
go get github.com/alasti-company/shipd-go/openfeature
```

```go main.go theme={null}
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	shipd "github.com/alasti-company/shipd-go"
	shipdof "github.com/alasti-company/shipd-go/openfeature"
	"github.com/open-feature/go-sdk/openfeature"
)

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}

func run() error {
	provider := shipdof.NewProvider(shipd.Options{SDKKey: os.Getenv("SHIPD_SDK_KEY")})
	defer openfeature.Shutdown()
	if err := openfeature.SetProviderAndWait(provider); err != nil {
		return fmt.Errorf("initialize shipd: %w", err)
	}

	client := openfeature.NewClient("checkout")
	ctx := context.Background()
	user := openfeature.NewEvaluationContext("usr_8f2k19", map[string]any{"plan": "pro"})

	checkout, err := client.BooleanValueDetails(ctx, "new-checkout", false, user)
	if err != nil {
		log.Printf("new-checkout: %v", err)
	}
	log.Printf("checkout=%t reason=%s", checkout.Value, checkout.Reason)
	return nil
}
```

Set `SHIPD_SDK_KEY` and run `go run .` from your Go module. Reuse one provider per environment and keep its SDK key on the server. The provider owns its client and closes it on replacement or shutdown. Configure polling, streaming, bootstrap, cache, or diagnostics through the [TypeScript SDK options](https://docs.useshipd.com/reference/sdk.md#options) or [Go SDK options](https://docs.useshipd.com/reference/go-sdk.md#new).

## Pass evaluation context

`targetingKey` becomes shipd's user identity. In Go, pass it as the first argument to `openfeature.NewEvaluationContext`. Other fields become targeting attributes. OpenFeature merges context before each evaluation, and the provider keeps each user's context request-scoped.

Use strings, finite numbers, booleans, or null (`nil` in Go). Nested objects, arrays, dates, and non-finite numbers return `INVALID_CONTEXT`. Use `targetingKey` for identity because `userId` is reserved. Pass attributes directly and let shipd evaluate audiences from the snapshot. Supply context and caller defaults through OpenFeature.

## Read values and details

```ts TypeScript theme={null}
// evaluations.ts
const variant = await client.getStringValue("search-variant", "control");
const retries = await client.getNumberValue("max-retries", 2);
const payload = await client.getObjectValue("checkout-payload", {});
const details = await client.getBooleanDetails("new-checkout", false);
```

```go Go theme={null}
// main.go
variant := client.String(ctx, "search-variant", "control", user)
retries := client.Int(ctx, "max-retries", 3, user)
payload := client.Object(ctx, "checkout-payload", map[string]any{}, user)
details, err := client.BooleanValueDetails(ctx, "new-checkout", false, user)
```

String calls resolve variant flags. Object calls resolve JSON flags, including primitives, arrays, and null. For Go number flags, use `Float` for `float64` values or `Int` for whole numbers representable as `int64` after snapshot decoding.

Unknown flags return `FLAG_NOT_FOUND`. An incompatible flag type or value returns `TYPE_MISMATCH`. Both errors return the default you passed to the call. Disabled flags return the configured default from the snapshot.

Successful evaluations report `TARGETING_MATCH`, `DEFAULT`, or `DISABLED`. Read `snapshotVersion` and the optional `ruleId` from `flagMetadata` in TypeScript or `FlagMetadata` in Go.

## Track custom events

Custom event tracking requires `@shipdit/openfeature@0.1.0-rc.1` and
`shipdit@0.9.0` or later. Use this example once both releases are available.

```bash theme={null}
npm install @shipdit/openfeature@0.1.0-rc.1 @openfeature/server-sdk@^1.23.0
```

Ask support to enable the [customer webhooks](https://docs.useshipd.com/reference/customer-events.md)
beta for your organization. Create a service account token with
`{ "customer_event": ["publish"] }` scoped to the SDK key's project and
environment. Set the environment ID and publish token in your server
environment.

```ts index.ts theme={null}
import { OpenFeature } from "@openfeature/server-sdk";
import { ShipdProvider } from "@shipdit/openfeature";

await OpenFeature.setProviderAndWait(new ShipdProvider({
  sdkKey: process.env.SHIPD_SDK_KEY!,
  tracking: {
    environmentId: process.env.SHIPD_ENVIRONMENT_ID!,
    publishToken: process.env.SHIPD_EVENT_PUBLISH_TOKEN!,
  },
}));

const checkout = OpenFeature.getClient("checkout");
checkout.track(
  "checkout.completed",
  { targetingKey: "usr_8f2k19", plan: "pro" },
  { value: 49.95, currency: "USD", order: { itemCount: 2 } },
);
```

Event names start with an ASCII letter and can contain letters, digits,
underscores, periods, and hyphens, up to 120 characters. shipd sends the name
as the webhook envelope's `type`. The envelope's `data` contains the fields below.

| Field | Contents |
| - | - |
| `occurredAt` | SDK timestamp captured at the call in ISO 8601 format. |
| `userId` | The merged OpenFeature `targetingKey`, omitted when empty or absent. |
| `attributes` | Other merged evaluation context fields when present. Values must be strings, finite numbers, booleans, or null. |
| `details` | Optional JSON object. Fields accept strings, finite numbers, booleans, null, objects, and arrays. The reserved `value` field accepts a finite number. |

Pass identity in `targetingKey` for the event's request. Each call captures its
own context. Use plain JSON in the details and format dates as strings. The SDK
drops invalid events and publish bodies larger than 64 KiB.
Include only the context and details you want delivered to subscribers.

Subscribe an endpoint to the event name to receive its payload. Use
`eventWebhook/eventTypes` to see retained event names and **Webhooks** →
**Delivery history** for delivery status and attempts. The customer-event
ingestion limits and retention policy apply. See [Receive customer events](https://docs.useshipd.com/operations/receive-customer-events.md).

`track()` returns without waiting for a network request. The SDK publishes
from an in-memory queue, awaiting one publish attempt at a time, with up to 200 waiting
events. A full queue drops its oldest waiting event. Network failures,
request timeouts, HTTP 429, and 5xx responses retry up to twice using the
same idempotency key. Retry delays start at one and two seconds and honor
the API's numeric `Retry-After` when it is longer. Other failures drop the
event after the first attempt. `onError` receives a sanitized error for
each failed publish attempt.
The SDK controls diagnostic events separately through the `events` option.

After draining your application's requests, await `OpenFeature.close()` to
give pending events up to five seconds to publish. The SDK discards any
remaining work at the deadline. Process exits can lose buffered events.
Tracking failures leave flag evaluation available.

## Handle startup and updates

Waiting for registration returns an error if initial loading finishes or times out without a usable snapshot. A bootstrap or cached snapshot allows offline startup. Polling or streaming can recover after failed initialization and emit `PROVIDER_READY`. Snapshot version changes emit `PROVIDER_CONFIGURATION_CHANGED`.

With OpenFeature Go SDK v1.15.1, use asynchronous `openfeature.SetProvider` to receive recovery events after a failed startup. `SetProviderAndWait` reports the initialization error before the SDK attaches its event listener.

Failed refreshes keep the last valid snapshot available. Use `onError` in TypeScript or `OnError` in Go to observe background failures. Shut down OpenFeature after draining your requests to stop updates and flush diagnostics. The Go provider gives diagnostics up to five seconds to flush. Create a new provider instance to register again after shutdown.

## Browser and React

The web provider requires `@shipdit/openfeature` 0.1.0-rc.1 or later and `shipdit` 0.9.0 or later. Check the [OpenFeature changelog](https://docs.useshipd.com/changelog/openfeature.md) for availability. Import `ShipdWebProvider` from `@shipdit/openfeature/web` and register it with `@openfeature/web-sdk` 1.10 or later in the v1 series.

Use a [client SDK key](https://docs.useshipd.com/concepts/keys.md) and enable client availability for each flag you want to read. Shipd evaluates targeting at the edge and returns resolved values. Keep server SDK keys in your server environment.

```ts theme={null}
import { OpenFeature } from "@openfeature/web-sdk";
import { ShipdWebProvider } from "@shipdit/openfeature/web";

const provider = new ShipdWebProvider({
  sdkKey: import.meta.env.VITE_SHIPD_CLIENT_SDK_KEY,
  flagKeys: ["new-checkout"],
  onError: (error) => console.error("Shipd refresh failed", error),
});

await OpenFeature.setProviderAndWait(provider);
const checkout = OpenFeature.getClient();

await OpenFeature.setContext({ targetingKey: "usr_8f2k19", plan: "pro" });
const enabled = checkout.getBooleanValue("new-checkout", false);
await OpenFeature.setContext({});
```

In React, wrap your tree with `OpenFeatureProvider` from `@openfeature/react-sdk` and use `useFlag("new-checkout", false)`. OpenFeature updates the hook when flag values or the evaluation context change. Register one provider outside the render path. The [working React example](https://github.com/alasti-company/useshipd.com/tree/main/examples/openfeature-react) includes sign-in, sign-out, and loading feedback.

* Pass `flagKeys` to load flags at startup. Other keys load on first evaluation and return the caller's fallback until their results arrive. A provider can request up to 100 distinct keys.
* Pass the complete evaluation context on sign-in, logout, or attribute changes. The provider discards the old user's values during reconciliation. Attributes accept strings, finite numbers, booleans, and null. Pass identity as `targetingKey`.
* Read details for fallback causes. A flag that is missing or unavailable to clients returns `FLAG_NOT_FOUND`. An incompatible value returns `TYPE_MISMATCH`.
* Use `setProviderAndWait` when startup must wait for remote values. It rejects if startup finishes without them. With asynchronous registration, evaluations use caller fallbacks during loading. OpenFeature emits a provider error for failed startup or context reconciliation. A later successful refresh recovers the provider, and background refresh failures for the same context preserve the last successful values. Use `onError` to observe the underlying request failures.
* Call `await OpenFeature.clearProviders()` at app teardown. Provider replacement and teardown close the owned Shipd client and stop its updates.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.