# shipd > This file is very large and may be truncated. For an index of this content, please refer to https://docs.useshipd.com/llms.txt instead. > Feature flags with config-as-code and local evaluation. # Use shipd with AI assistants Source: https://docs.useshipd.com/ai A compact shipd context file for Claude, Cursor, Codex, ChatGPT, and other coding assistants, with the rules and common mistakes they need. ## Overview Coding assistants know little about shipd. Give them this page and they'll write correct shipd code. It's also available as plain Markdown at `https://docs.useshipd.com/ai.md`. | Resource | URL | Use it for | | - | - | - | | This page | `https://docs.useshipd.com/ai.md` | A compact context file. Paste it into `CLAUDE.md`, `AGENTS.md`, `.cursor/rules`, or a chat. | | Index | `https://docs.useshipd.com/llms.txt` | A map of every page with one-line summaries. | | Full docs | `https://docs.useshipd.com/llms-full.txt` | Every page in one file. | | Any page as Markdown | Append `.md` to its URL | Fetching one page, such as `https://docs.useshipd.com/reference/sdk.md`. Local `mint dev` previews don't serve `.md` URLs; use `/llms.txt` or the page's copy menu there. | | Control-plane API | `https://api.useshipd.com/api/v1/openapi.json` | OpenAPI 3.1 for the management API. | The navbar separates Docs, Guides, SDKs, Integrations, API docs, Tutorials, and Changelog. Shared examples have synchronized TypeScript and Go tabs: choose an SDK once to switch the matching examples on that page. Framework-specific examples document the SDK supported by that framework. For direct application control, [connect an agent through MCP](/operations/connect-an-agent) under **Guides → Operations**. The endpoint is `https://mcp.useshipd.com/mcp`; mutations require idempotency keys and updates require observed versions. Pending changes must be reviewed in the dashboard. [MCP tools and request guarantees](/reference/mcp) live under **API docs → Operations APIs**. [Release records](/reference/releases) (unreleased pending merge and deployment) track intent, manual lifecycle transitions, action attribution, and bounded evidence. They never execute deployments or prove publication, approval, or exposure; observed operational states remain unknown or not checked. Release writes require an idempotency key and updates require the current release version. For reusable coding workflows, [install shipd agent skills](/operations/agent-skills) with `npx skills add alasti-company/shipd-skills`. The skills cover flag implementation, CI synchronization, and rollout; remote operations still require CLI authentication or an MCP connection. The [Terraform provider](/integrations/terraform) manages projects and environments and provides read-only data sources. Use the published `alasti-company/shipd` provider from the Terraform Registry with `version = "~> 0.1.0"`, then run `terraform init`, `terraform plan`, and `terraform apply`. Later provider builds can also [register SDK keys and service account tokens](/reference/terraform#manage-credentials-from-ci) using a stable UUID, a nonsecret `secret_version`, and an ephemeral variable passed to the write-only `secret_wo` argument. Every page also has a menu to copy it as Markdown or open it in Claude, ChatGPT, or Cursor. To give your assistant shipd context permanently, add this to your project's `CLAUDE.md`, `AGENTS.md`, or editor rules: ```md theme={null} This project uses shipd for feature flags. Before writing shipd code, read https://docs.useshipd.com/ai.md and follow its rules. ``` ## shipd context for coding assistants shipd is a feature flag service. Flags are defined in TypeScript, Go, or version-1 JSON, synced with a shared CLI, and evaluated locally in memory by an SDK. ### Packages | Package / import | Purpose | | - | - | | `github.com/alasti-company/shipd-go/config` | Go flag authoring, in the same module as the Go SDK. `ShipdConfig` is a named map of `FlagDefinition` structs; exported fields include `Type`, `Default`, and `Description`. Declare a literal directly; `Validate` and `Defaults` validate it. | | `github.com/alasti-company/shipd-go` | Go server SDK (Go 1.23+). Definitions use its `config` subpackage (`config.ShipdConfig`). The CLI loads `shipd.config.go` directly and `types gen --language go` generates accessors. `shipd.New` requires `SDKKey` and defaults to the production edge. Use `Stream: true` for WebSocket updates with polling fallback. Pass `shipd.EvaluationContext` per evaluation. Use bounded contexts for `Ready` and `Shutdown`. `Identify` queues telemetry. `Shutdown(ctx)` flushes then closes. Reserve `Overrides` for development and tests. | | `github.com/alasti-company/shipd-go/openfeature` | Go OpenFeature provider. Create it with `NewProvider(shipd.Options{SDKKey: ...})` and register it with OpenFeature. Use `openfeature.NewEvaluationContext` with a targeting key and scalar attributes. Pass defaults through OpenFeature calls. See the [OpenFeature Go setup](/integrations/openfeature#go). | | `shipdit` | Server SDK (Node.js 20+, workers). `createClient`. | | `shipdit/client` | Browser SDK. `createClient` (edge-evaluated values in memory, `anonymousId` in `localStorage`). | | `shipdit/client/react` | React bindings. `createShipdReact`. | | `shipdit/config` | `defineFlags`, used only in `shipd.config.ts`. | | `@shipdit/openfeature` | OpenFeature server provider RC. `ShipdProvider` requires a server SDK key and scalar OpenFeature context; use `targetingKey` for identity. | | `@shipdit/cli` | CLI. Binary name is `shipd`. | | `@shipdit/convex` | Convex component. Mount with `SHIPD_SDK_KEY` and `SHIPD_WEBHOOK_SECRET`; snapshots use the default shipd edge. `SHIPD_EDGE_URL` was removed. `SHIPD_UNSAFE_EDGE_URL` is for shipd development and tests only and must be forwarded in the mount configuration. | ### Go workflow The CLI reads `shipd.config.go` directly and generates Go accessors by default, unless `typesLanguage` overrides the output language. Define an exported `var Config = config.ShipdConfig{...}` in a self-contained Go file inside your module. The CLI evaluates that file with Go; imported packages and helper declarations in the same file are supported. It does not load sibling Go files, so keep application dependencies in imported packages. Do not define `main` in the definition file. `shipd pull` rewrites the Go definitions and regenerates accessors; review the resulting diff because comments and helper code are replaced. Use generated accessors like `flags.NewCheckout(client, ctx)` and `flags.Defaults()`. ### Files | Path | What it is | | - | - | | `shipd.config.ts` | TypeScript flag definitions. The source of truth for which flags exist. | | `src/generated/flags.ts` | Generated `FlagDefinitions` types. Written by `shipd push`, `shipd pull`, `shipd types gen`. Never edit. | | `shipd.config.go` | Go flag definitions: `var Config = config.ShipdConfig{...}` in `package main`, no `main` func. Replaces `shipd.config.ts` in Go projects. | | `internal/flags/flags_gen.go` | Generated Go accessors, variant constants, and `Defaults()` (path set by `typesOut`). Never edit. | | `.shipd/config.json` | Optional CLI defaults: `org`, `project`, `env`, `typesOut`. | ### Define flags ```ts TypeScript theme={null} // shipd.config.ts import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, description: "Redesigned checkout" }, "search-variant": { type: "variant", variants: ["control", "semantic", "hybrid"] as const, default: "control", }, "max-retries": { type: "number", default: 3 }, "checkout-payload": { type: "json", default: { mode: "strict", showPromo: true } }, }); ``` ```go Go theme={null} // shipd.config.go package main import "github.com/alasti-company/shipd-go/config" var Config = config.ShipdConfig{ "new-checkout": {Type: "boolean", Default: false, Description: "Redesigned checkout flow", Tags: []string{"checkout"}}, "search-variant": {Type: "variant", Default: "control", Variants: []string{"control", "semantic", "hybrid"}}, "max-retries": {Type: "number", Default: 3}, "checkout-payload": {Type: "json", Default: map[string]any{"mode": "strict", "showPromo": true}}, } ``` Then run `shipd push`. It creates missing flags, updates changed definitions, and regenerates TypeScript types or Go accessors. It never deletes flags; `--prune` archives flags missing from the file. ### Evaluate on a server Streaming requires a WebSocket implementation. Node.js 22+ provides one globally. On Node.js 20, supply a compatible constructor through the `WebSocket` option; otherwise, the client uses polling. ```ts TypeScript theme={null} // src/lib/shipd.ts import { createClient } from "shipdit"; import type { FlagDefinitions } from "../generated/flags"; export const shipd = createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, // shipd_sdk_server_… stream: true, // optional; requires Node.js 22+ or the WebSocket option defaults: { "new-checkout": false, "search-variant": "control", "max-retries": 3, "checkout-payload": { mode: "strict", showPromo: true }, }, }); await shipd.ready(); // once at startup; never rejects shipd.isEnabled("new-checkout", { userId: user.id, attributes: { plan: user.plan } }); shipd.getVariant("search-variant", { userId: user.id }); // "control" | "semantic" | "hybrid" shipd.getNumber("max-retries"); shipd.getJson("checkout-payload"); ``` ```go Go theme={null} // Initialize once at startup; imports: context, log, os, time, and shipd. client, err := shipd.New(shipd.Options{ SDKKey: os.Getenv("SHIPD_SDK_KEY"), Defaults: map[string]any{ "new-checkout": false, "search-variant": "control", "max-retries": 3, "checkout-payload": map[string]any{"mode": "strict", "showPromo": true}, }, }) if err != nil { log.Fatal(err) } defer func() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if err := client.Shutdown(ctx); err != nil { log.Printf("shipd events: %v", err) } }() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) if err := client.Ready(ctx); err != nil { log.Printf("using defaults: %v", err) } cancel() user := shipd.EvaluationContext{UserID: "usr_8f2k19", Attributes: map[string]any{"plan": "pro"}} client.IsEnabled("new-checkout", user) client.GetVariant("search-variant", user) client.GetNumber("max-retries", user) client.GetJSON("checkout-payload", user) ``` ### Evaluate in React ```ts src/lib/shipd-react.ts theme={null} "use client"; import { createShipdReact } from "shipdit/client/react"; import type { FlagDefinitions } from "../generated/flags"; export const { ShipdProvider, useFlag, useVariant, useNumber, useJson, useReady } = createShipdReact(); ``` ```tsx theme={null} import { createClient } from "shipdit/client"; const client = createClient({ sdkKey: import.meta.env.VITE_SHIPD_SDK_KEY, // shipd_sdk_client_… stream: true, defaults: { "new-checkout": false, "search-variant": "control" }, }); ; client.identify({ userId: user.id, traits: { plan: user.plan } }); // after login client.reset(); // on logout const on = useFlag("new-checkout"); ``` ### Evaluation model * The server SDK downloads a **snapshot** of one environment from `https://edge.useshipd.com`, keeps it in memory, and refreshes it every 30 seconds or on a WebSocket notification. * `isEnabled`, `getVariant`, `getNumber`, and `getJson` make no network requests and never throw. * Value order: no snapshot or unknown key → `defaults[key]`; flag disabled → fallthrough, skipping rules; first matching rule → its serve; otherwise → fallthrough. * Browser SDKs request only evaluated values from `POST /sdk/v1/evaluate` for `clientAvailable: true` flags; client keys cannot read full snapshots. Include browser flag keys in `defaults` for initial loading. New identities and per-call contexts use defaults until values arrive. Do not pass full snapshot `bootstrap` or `cache` options to browser clients. Public keys and caller-supplied traits cannot enforce authorization; evaluate flags that depend on verified identity, role, or plan on your server and return allowlisted values with `Cache-Control: no-store` (refreshing via polling or authenticated SSE invalidations). Flags never replace backend authorization. See [Client vs. server evaluation](/concepts/client-vs-server). * For OpenFeature in a browser, register `ShipdWebProvider` from `@shipdit/openfeature/web` with a client SDK key. Preload keys with `flagKeys` and replace the evaluation context with `OpenFeature.setContext`. React apps use `OpenFeatureProvider` and `useFlag` from `@openfeature/react-sdk`. * **Evaluation context** is `{ userId?, attributes?, segmentIds? }`. Per-call context overrides `createClient({ context })`. In browsers (`shipdit/client`), `identify()` traits sit between the two; server `identify()` only records an event and never changes context. * Percentage rollouts hash the flag key and `userId`, or a chosen attribute. A missing bucket attribute makes the condition fall through. * Targeting rules, rollouts, and enabled state can be edited in the dashboard or declared in an optional per-flag `targeting` block in TypeScript, Go, or JSON config. Omission preserves dashboard targeting; `rules: []` clears rules. ### Credentials | Credential | Prefix | Used for | Never use it for | | - | - | - | - | | Server SDK key | `shipd_sdk_server_` | `shipdit` and the Go SDK on servers | Browsers, the CLI | | Client SDK key | `shipd_sdk_client_` | `shipdit/client` in browsers | The CLI | | Management API key | `shipd_mgmt_` | The CLI on a laptop (`shipd login` creates it) | SDKs | | Service account token | `shipd_sa_` | The CLI in CI (`SHIPD_API_KEY`) | SDKs | ### Rules for assistants 1. Import `defineFlags` from `shipdit/config`, never from `shipdit`. 2. Import `createClient` from `shipdit` on servers and from `shipdit/client` in browsers. 3. Type the client with the generated `FlagDefinitions`: `createClient(…)`. Never write flag types by hand. 4. Pass a `defaults` entry for every flag. Use the safe value (usually "off"). 5. Create one client per process and reuse it. Never create a client per request. 6. `await shipd.ready()` once at startup, before serving traffic that reads flags. 7. On servers, pass `{ userId, attributes }` per call. Server `identify()` only records an event; it never sets evaluation context. 8. Call `createShipdReact` once, in a `"use client"` module, and use hooks from that same call. 9. Add or change flags by editing `shipd.config.ts` (Go: `shipd.config.go`) and running `shipd push`. Don't create flags in the dashboard for code-managed projects. 10. Don't pass `endpoint` or `streamEndpoint`; they were removed. Use `stream: true` for realtime updates. For a custom stream gateway, preserve its URL with `overrides.streamEndpoint` and `stream: true`. Reserve `overrides.unsafeEndpoint` for development and tests; never use it in production. ### Rules for Go 1. Import the SDK as `shipd "github.com/alasti-company/shipd-go"` and definitions from its `config` subpackage. One `go get github.com/alasti-company/shipd-go` installs both. 2. Define flags in `shipd.config.go`, never `shipd.config.ts`. Run `shipd types gen` (Node.js 22.12+ and `@shipdit/cli`) to write accessors. 3. Call generated accessors such as `flags.NewCheckout(client, ctx)` instead of `client.IsEnabled("new-checkout", ctx)`, and pass `Defaults: flags.Defaults()` to `shipd.New`. 4. Create one `*shipd.Client` per process with `shipd.New` and share it across goroutines. 5. Call `Ready` once at startup with a bounded context. It returns the fetch error as soon as the first fetch fails; log it and serve defaults. 6. Pass a `shipd.EvaluationContext` on every evaluation. `Identify` only queues telemetry. 7. On shutdown, call `Shutdown(ctx)` with a bounded context. It attempts to flush pending events and closes even on delivery failure; check or log its returned error. `Close` does not flush. Never set `Overrides.UnsafeEndpoint` in application code. 8. JSON flags return `any` and numbers are `float64`; convert at the call site. 9. In tests, use an `HTTPClient` that fails, `DisablePolling`, and `DisableEvents`. To test targeting rules, pass snapshot JSON as `Bootstrap`. ### Common mistakes ```ts Wrong theme={null} import { defineFlags } from "shipdit"; ``` ```ts Right theme={null} import { defineFlags } from "shipdit/config"; ``` ```ts Wrong theme={null} // Server key in a browser bundle createClient({ sdkKey: process.env.NEXT_PUBLIC_SHIPD_SERVER_KEY!, … }); ``` ```ts Right theme={null} // Client key in the browser, server key only in server code import { createClient } from "shipdit/client"; createClient({ sdkKey: process.env.NEXT_PUBLIC_SHIPD_SDK_KEY!, … }); // shipd_sdk_client_… ``` ```ts Wrong theme={null} // Network call per check const res = await fetch("https://edge.useshipd.com/sdk/v1/snapshot", …); ``` ```ts Right theme={null} // In-memory check against the SDK's snapshot shipd.isEnabled("new-checkout", { userId }); ``` ```ts Wrong theme={null} app.get("/checkout", async (req, res) => { const shipd = createClient({ … }); // new client per request await shipd.ready(); }); ``` ```ts Right theme={null} // src/lib/shipd.ts exports one client, created at startup app.get("/checkout", (req, res) => { shipd.isEnabled("new-checkout", { userId: req.user.id }); }); ``` ```ts Wrong theme={null} type Flags = { "new-checkout": boolean }; // hand-written createClient({ … }); ``` ```ts Right theme={null} import type { FlagDefinitions } from "./generated/flags"; createClient({ … }); ``` **Don't:** * Call the edge API directly to evaluate flags. * Put a server SDK key, management API key, or service account token in browser code. * Use a management API key or service account token as an SDK key, or an SDK key with the CLI. * Edit `src/generated/flags.ts` by hand. * Assume `shipd push` deletes flags missing from `shipd.config.ts`. It leaves them; `--prune` archives them. * Run `shipd push --prune` without reading the plan. It archives every flag not in the file. * Put targeting rules or rollout percentages at the flag's top level. Use the optional `targeting` block in TypeScript, Go, or JSON config; omit it to preserve dashboard targeting. * Forget that `default` in `shipd.config.ts` is the fallthrough of the environment you push to. `shipd push` resets a fallthrough changed in the dashboard back to it. Update `default` (or run `shipd pull`) first. * Assume disabling a flag turns it off. A disabled flag serves its fallthrough. To turn a feature off, set the fallthrough to `false`. * Use `--force` to get past a conflict. Run `shipd pull`, re-apply the edit, and push again. * Treat `shipd push` exit code `5` as success. The change is waiting for approval. * Rely on percentage rollouts without supplying their bucket attribute (`userId` by default). * Import `shipdit/client/react` in server code. **Do:** * Supply `defaults` for every flag. * Evaluate locally with the SDK. * Commit `src/generated/flags.ts` along with `shipd.config.ts` (Go: `flags_gen.go` along with `shipd.config.go`). * Run `shipd diff --exit-code` in pull request CI, and `shipd push --ci` on merge with a service account token in `SHIPD_API_KEY`. * Production targeting saves (including `shipd push` defaults) create drafts. Use **Publish changes** in the flag’s **Across environments** table to update SDK snapshots. Approval makes a draft ready; it does not publish it. Non-production targeting stays immediate unless review is required. * Set `SHIPD_API_URL=https://api.useshipd.com` in CI. Without a saved login, the CLI defaults to `http://localhost:8000`. * Await `shipd.close()` on shutdown. In Go, drain active handlers first, then call `Shutdown(ctx)` with a bounded context and check its error. ### CLI cheat sheet ```bash theme={null} npm install -g @shipdit/cli shipd login # device login; pick org, project, environment shipd diff # show what push would change shipd push # apply shipd.config.ts or .go, regenerate types shipd push --ci # non-interactive (CI) shipd pull # overwrite shipd.config.ts or .go from shipd shipd types gen # regenerate types or Go accessors only ``` | Exit code | Meaning | | - | - | | `0` | Success, or no drift | | `1` | Error | | `2` | Drift (`diff --exit-code`) | | `3` | Conflict: someone changed the flag since you pulled | | `4` | Unlinked flags (`diff --exit-code`) | | `5` | Accepted but waiting for approval; not live yet | ## Where to look next * [SDK reference](/reference/sdk) · [CLI reference](/reference/cli) · [`shipd.config.ts` reference](/reference/config) * [Core concepts](/core-concepts) · [Glossary](/reference/glossary) * [Examples](/examples/node): complete apps to adapt ## Rules in code `defineFlags` accepts optional per-flag `targeting: { enabled, rules, fallthrough }` and `traits` declarations. Go uses `config.Targeting`, `config.Rule`, `config.Condition`, `config.Serve`, and `config.TraitDefinition`. Omitted targeting preserves dashboard rules; `rules: []` clears them. Trait contracts persist as flag metadata. Pull exports published targeting, not drafts. Review [configuration](/reference/config#targeting-in-code) and [sync semantics](/reference/cli#targeting-sync) before changing rules. ## Browser availability in code In TypeScript `defineFlags` and version-1 JSON configs, use `clientAvailable: true` to permit public browser delivery and `clientAvailable: false` to disable it. Omission preserves the existing remote setting on push; new flags default to private. Diff, push, and pull support the field. It is project-global, uses definition permissions, and propagates through snapshots. See [Configuration files](/reference/config#client-availability). Per-environment targeting overrides use `targeting.environments[slug]` as complete replacements. Explicit targeting is code-owned after push; omit it and push to release ownership. Optional `rollout` declares Sentry guard metrics, increasing percentage steps and minimum dwell. The `code-release-control` flag gates the scheduler. `shipd rollout status|pause|resume|abort` controls release records; MCP exposes `release_proposeProgressiveRollout`, `release_rolloutStatus` and `release_explainRolloutDecision`. Agents never approve production. Guard failures automatically restore the configured default; missing data holds exposure. Server snapshots can carry detached Ed25519 proofs. Pin PEM SPKI public keys by key ID with TypeScript `snapshotVerificationKeys` or Go `Options.SnapshotVerificationKeys` to require verification during refresh. Invalid or missing proofs retain the last good snapshot/defaults. Evaluation does not perform signature work. # Changelog Source: https://docs.useshipd.com/changelog Release notes for shipd SDKs, the CLI, Convex, OpenFeature, and the Terraform provider. ## Overview Find release notes by package. For upgrade instructions, see the [migration guides](/migrations). > [card] [TypeScript SDK](/changelog/typescript-sdk) > > `shipdit` for servers, browsers, and React. > [card] [Go SDK](/changelog/go-sdk) > > The Go server SDK. > [card] [Convex](/changelog/convex) > > `@shipdit/convex` component. > [card] [CLI](/changelog/cli) > > `@shipdit/cli` (`shipd`). > [card] [OpenFeature](/changelog/openfeature) > > `@shipdit/openfeature` for Node.js and browsers. > [card] [Terraform](/changelog/terraform) > > The `alasti-company/shipd` provider. # CLI changelog Source: https://docs.useshipd.com/changelog/cli Release notes for @shipdit/cli, the shipd command-line tool. ## Overview Release notes for the [`shipd` CLI](/reference/cli), newest first. Version notes are prepared with the version bump. Check the linked npm version for package availability. **@shipdit/cli 0.10.0** Version notes ### Minor Changes * 5182bc1: Add `shipd release` commands to inspect releases, manage accepted release health validations (`accept`, `list`, `revoke`), and control hosted rollouts (`pause`, `resume`, `stop`). [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.10.0) **@shipdit/cli 0.9.0** Version notes ### Minor Changes * 141b028: Define environment targeting overrides and guarded progressive rollout plans in TypeScript, JSON, or Go config. Explicit targeting is code-owned after push; omit it and push to return control to the dashboard. Diff plans show targeting and rollout changes for the selected environment. Use `shipd rollout status`, `shipd rollout pause`, `shipd rollout resume`, and `shipd rollout abort` to manage a guarded rollout. The feature-gated controller uses Sentry guards, human approval policies for protected advances, and automatic rollback to the configured default. See [rollout commands](https://docs.useshipd.com/reference/cli#rollout-status%7Cpause%7Cresume%7Cabort). ### Patch Changes * Updated dependencies \[141b028] * shipdit\@0.10.0 [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.9.0) **@shipdit/cli 0.8.2** Version notes ### Patch Changes * Updated dependencies \[6883d44] * Updated dependencies \[72cd4e6] * shipdit\@0.9.0 [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.8.2) **@shipdit/cli 0.8.1** Version notes ### Patch Changes * Updated dependencies \[97dcbb8] * shipdit\@0.8.0 [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.8.1) **@shipdit/cli 0.8.0** Version notes ### Minor Changes * fdcb95c: Support optional `clientAvailable` in TypeScript `defineFlags` and version-1 JSON configs. Set it to `true` to permit public client-key evaluation, or `false` to disable it. Diff, push, and pull preserve explicit values; omitted settings preserve existing remote availability, and new flags remain private by default. Availability is project-wide and changes take effect after snapshot publication. Upgrade the control plane, SDK, and CLI together. See [https://docs.useshipd.com/sdks/browser](https://docs.useshipd.com/sdks/browser) for public-key expectations and migration behavior. ### Patch Changes * 1cb4ebb: Refresh dependency and build tooling versions for the CLI, TypeScript SDK, and Convex integration. * Updated dependencies \[fdcb95c] * Updated dependencies \[1cb4ebb] * shipdit\@0.7.0 [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.8.0) **@shipdit/cli 0.7.2** Version notes ### Patch Changes * Updated dependencies \[8b9ef3c] * shipdit\@0.6.0 [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.7.2) **@shipdit/cli 0.7.1** Version notes ### Patch Changes * 0dade08: Generate Go definitions and accessors using the public github.com/alasti-company/shipd-go module. [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.7.1) **@shipdit/cli 0.7.0** Version notes ### Minor Changes * c6ccd3c: Define complete environment targeting and per-flag trait contracts in config. Push and pull preserve rule order, weighted fallthroughs, and enabled state across TypeScript, Go, and JSON. Targeting changes use existing production drafts and approvals. Local sync baselines detect dashboard conflicts and protect unsynced targeting on pull. Generate typed trait inputs alongside flag accessors. ### Patch Changes * Updated dependencies \[c6ccd3c] * shipdit\@0.5.0 [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.7.0) **@shipdit/cli 0.6.0** Version notes ### Minor Changes * 2d9cfd6: `shipd push` saves production targeting as drafts instead of applying it immediately. JSON output includes `drafts` and may report `outcome: "draft"`; publish those drafts from the dashboard environment plan. [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.6.0) **@shipdit/cli 0.5.0** Version notes ### Minor Changes * 2009992: Load native `shipd.config.go` flag definitions directly without a JSON export. Pull preserves Go source format. Generate Go flag accessors, variant constants, and defaults with `shipd types gen --language go`; Go input automatically selects Go output after push and pull. `shipd pull` writes gofmt-clean Go and checks Go identifiers before writing anything. Non-ASCII flag keys produce distinct exported identifiers. A missing Go toolchain reports how to install Go, and compiler errors point at `shipd.config.go`. ### Patch Changes * Updated dependencies \[0de734a] * Updated dependencies \[974027a] * Updated dependencies \[52de793] * shipdit\@0.4.0 [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.5.0) **@shipdit/cli 0.4.1** Version notes ### Patch Changes * c8167c3: Default the CLI API origin to [https://api.useshipd.com](https://api.useshipd.com) when no URL is configured, so commands besides `shipd login` reach production without `SHIPD_API_URL`. [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.4.1) **@shipdit/cli 0.4.0** Version notes ### Minor Changes * 23dffd5: chore: require Node.js 22.12 or later for `@shipdit/cli`. `commander` 15 is ESM-only and no longer supports Node 20 ### Patch Changes * Updated dependencies \[23dffd5] * shipdit\@0.3.1 [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.4.0) **@shipdit/cli 0.3.2** Version notes ### Patch Changes * Updated dependencies \[62ba4a0] * shipdit\@0.3.0 [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.3.2) **@shipdit/cli 0.3.1** Version notes ### Patch Changes * d691b9a: Return exit code 5 and structured request IDs when a push queues changes for approval, so CI cannot mistake pending changes for active configuration. * Updated dependencies \[e5ac21f] * shipdit\@0.2.4 [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.3.1) **@shipdit/cli 0.3.0** Version notes ### Minor Changes * 04af841: feat: add `shipd snapshots outbox`, `requeue`, `rebuild`, and `publications` so operators can inspect, dead-letter retry, and rebuild data-plane snapshots [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.3.0) **@shipdit/cli 0.2.2** Version notes ### Patch Changes * 210e892: feat: accept `shipd_sa_` service-account tokens via `SHIPD_API_KEY`. `whoami` prints the service-account identity, and unbound tokens require `--project` / `--env` [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.2.2) **@shipdit/cli 0.2.1** Version notes ### Patch Changes * Updated dependencies \[bdbadbe] * shipdit\@0.2.3 [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.2.1) **@shipdit/cli 0.2.0** Version notes ### Minor Changes * 96bb204: feat: `shipd push` reports environment default changes that were queued for approval instead of applied. JSON output includes `approvalRequests`. Live targeting stays unchanged until reviewers approve. Requires Enterprise with an enabled approval policy; otherwise push is unchanged. [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.2.0) **@shipdit/cli 0.1.2** Version notes ### Patch Changes * Updated dependencies \[2f856b5] * shipdit\@0.2.2 [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.1.2) **@shipdit/cli 0.1.1** Version notes ### Patch Changes * c0900e5: Default `shipd login` to `https://api.useshipd.com` via `--api-url` / `SHIPD_API_URL` so device authorization works without a local API. * Updated dependencies \[c0900e5] * shipdit\@0.2.1 [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.1.1) **@shipdit/cli 0.1.0** Version notes ### Minor Changes * c68d524: Treat `managedBy` as last-touch attribution instead of a lock. `shipd push --adopt` is a deprecated no-op; dashboard and CLI can both edit any flag, and equal definitions no longer emit ownership-only updates. ### Patch Changes * Updated dependencies \[c68d524] * shipdit\@0.2.0 [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.1.0) **@shipdit/cli 0.0.2** Version notes ### Patch Changes * Updated dependencies \[59ca1ce] * shipdit\@0.1.0 [View on npm](https://www.npmjs.com/package/@shipdit/cli/v/0.0.2) # Convex changelog Source: https://docs.useshipd.com/changelog/convex Release notes for @shipdit/convex, the shipd component for Convex. ## Overview Release notes for [`@shipdit/convex`](/sdks/convex), newest first. Upgrade steps for breaking releases are in [Migration guides](/migrations). Version notes are prepared with the version bump. Check the linked npm version for package availability. **@shipdit/convex 0.2.1** Version notes ### Patch Changes * 1cb4ebb: Refresh dependency and build tooling versions for the CLI, TypeScript SDK, and Convex integration. [View on npm](https://www.npmjs.com/package/@shipdit/convex/v/0.2.1) **@shipdit/convex 0.2.0** Version notes ### Minor Changes * dc2880d: **Breaking changes** (0.x minor). See the migration guide: [https://docs.useshipd.com/migrations/convex-0-2](https://docs.useshipd.com/migrations/convex-0-2) * **Breaking:** the required `SHIPD_EDGE_URL` env var was removed; delete it from `defineApp` and `app.use(shipd, { env })`. The component fetches snapshots from `https://edge.useshipd.com`. shipd development and test environments can point elsewhere with the optional `SHIPD_UNSAFE_EDGE_URL`, which is validated: an invalid value reports a clear refresh error, and a plaintext URL to a non-local host logs a warning. Never set it in production, because it receives your SDK key. Other changes: * The `X-Shipd-SDK-Version` header reports the installed package version instead of a fixed `convex-0.1.0`. * 0de734a: **Breaking changes** (0.x minor). See the timestamp migration instructions: * [https://docs.useshipd.com/migrations/shipdit-0-4#check-timestamp-rules-before-upgrading](https://docs.useshipd.com/migrations/shipdit-0-4#check-timestamp-rules-before-upgrading) * [https://docs.useshipd.com/migrations/convex-0-2#check-timestamp-rules-before-upgrading](https://docs.useshipd.com/migrations/convex-0-2#check-timestamp-rules-before-upgrading) * **Breaking:** timestamp comparisons follow one deterministic grammar: `YYYY-MM-DD` (midnight UTC), or a date-time with a required `Z` or `±hh:mm` zone. Zone-less date-times, lenient formats, and impossible dates now compare as strings instead of through `Date.parse`, so results no longer depend on the server's timezone. Audit date-based rule values and evaluation attributes before upgrading. Dashboard preview adopts this grammar on deploy, so older SDKs can disagree with preview; the edge serves snapshots and does not evaluate rules. [View on npm](https://www.npmjs.com/package/@shipdit/convex/v/0.2.0) **@shipdit/convex 0.1.3** Version notes ### Patch Changes * 23dffd5: chore: refresh development dependencies [View on npm](https://www.npmjs.com/package/@shipdit/convex/v/0.1.3) **@shipdit/convex 0.1.2** Version notes ### Patch Changes * a3637f1: Emit Convex-compatible `.js` component modules so packaged HTTP routes mount, and wire the example app for `convex dev`. [View on npm](https://www.npmjs.com/package/@shipdit/convex/v/0.1.2) **@shipdit/convex 0.1.1** Version notes ### Patch Changes * 0e066ec: add a convex component that caches shipd snapshots locally and evaluates flags from convex functions, refreshed by signed webhooks [View on npm](https://www.npmjs.com/package/@shipdit/convex/v/0.1.1) **@shipdit/convex 0.1.0** 2026-09-12 * Initial Convex package release. Install the component in a Convex app to evaluate flags from a locally cached shipd snapshot. [View on npm](https://www.npmjs.com/package/@shipdit/convex/v/0.1.0) # Go SDK changelog Source: https://docs.useshipd.com/changelog/go-sdk Release notes for the shipd Go server SDK. ## Overview Release notes for the [Go SDK](/sdks/go), newest first. Go releases are tagged `vX.Y.Z` in the [shipd-go repository](https://github.com/alasti-company/shipd-go) and are independent of npm packages. **Go SDK 0.3.0** 2026-11-22 ### Features * **openfeature:** add Shipd provider for Go (SHIPD-308) ([#5](https://github.com/alasti-company/shipd-go/issues/5)) ([1916a9d](https://github.com/alasti-company/shipd-go/commit/1916a9d15d68ee432ca2e131bec06591a62d3743)) [GitHub release](https://github.com/alasti-company/shipd-go/releases/tag/v0.3.0) **Go SDK 0.2.0** 2026-11-06 ### Features * add TypeScript server SDK feature parity ([#2](https://github.com/alasti-company/shipd-go/issues/2)) ([ee900c9](https://github.com/alasti-company/shipd-go/commit/ee900c95dbba045e9a0b951e3a3e6c717bbcbcdc)) [GitHub release](https://github.com/alasti-company/shipd-go/releases/tag/v0.2.0) ## Initial release The initial release predates the repository changelog. These notes are maintained by hand. **Go SDK 0.1.0** 2026-11-06 ### Added First release of the Go server SDK (Go 1.23+, no dependencies). * One module, `github.com/alasti-company/shipd-go`, with a `config` subpackage (`config.ShipdConfig`) for defining flags in `shipd.config.go`. * `shipd.New` with local evaluation from a polled snapshot. `IsEnabled`, `GetVariant`, `GetNumber`, `GetJSON`, and `Evaluate` (value, reason, rule ID, snapshot version). * Same targeting and rollout buckets as the TypeScript SDK, checked against a shared fixture. * `Ready(ctx)` returns `nil` once a snapshot loads, or the initial fetch error as soon as that attempt fails. * `Bootstrap` serves a snapshot until a newer one is fetched, so tests can exercise targeting rules without a fake edge. * `Identify` queues identify events for audience insights without changing evaluation context. * Events flush every `FlushInterval` (5 seconds) and as soon as `FlushAt` (50) events are buffered. `DroppedEvents` counts events lost to buffer overflow. * `SnapshotVersion` reports the loaded version without recording an event. * `Shutdown(ctx)` attempts to deliver pending events, then closes the client even if delivery fails. `Close` stops immediately and implements `io.Closer`. * `Refresh`, `Flush`, and `LastError` for manual control. * Exported errors for `errors.Is`: `ErrClosed`, `ErrMalformedSnapshot`, and `ErrUnsupportedSchema`. * The client always connects to `https://edge.useshipd.com`. `Overrides.UnsafeEndpoint` replaces it for shipd development and tests only, matching the TypeScript SDK's `overrides.unsafeEndpoint`. See the [Go SDK reference](/reference/go-sdk). [GitHub release](https://github.com/alasti-company/shipd-go/releases/tag/v0.1.0) # OpenFeature changelog Source: https://docs.useshipd.com/changelog/openfeature Release notes for the @shipdit/openfeature provider for JavaScript. ## Overview Release notes for the [`@shipdit/openfeature` provider](/integrations/openfeature), newest first. The Go provider ships with the [Go SDK](/changelog/go-sdk). **@shipdit/openfeature 0.1.0-rc.1** Unreleased * Add `ShipdWebProvider` in `@shipdit/openfeature/web`. It uses a client SDK key to fetch evaluated flag values from the edge and supports OpenFeature context updates and React hooks. * Support server-side `client.track()` for sending custom application events to customer webhooks. Tracking requires a service account token with `customer_event:publish` for the SDK key's environment. * Require `shipdit` 0.9.0 or later for browser evaluation and custom event tracking. **@shipdit/openfeature 0.1.0-rc.0** 2026-11-13 * Add the OpenFeature server provider for Node.js 20+ and `@openfeature/server-sdk` 1.23 or later in the 1.x series. The provider evaluates boolean, variant, number, and JSON flags locally and maps OpenFeature's `targetingKey` to shipd's user identity. * Return OpenFeature evaluation reasons and errors along with the snapshot version and matching rule ID when available. Emit provider events when a snapshot becomes available after startup failure or its version changes. [View on npm](https://www.npmjs.com/package/@shipdit/openfeature/v/0.1.0-rc.0) # Terraform provider changelog Source: https://docs.useshipd.com/changelog/terraform Release notes for the alasti-company/shipd Terraform provider. ## Overview Release notes for the [shipd Terraform provider](/integrations/terraform), newest first. The provider releases independently. Check the [Terraform Registry](https://registry.terraform.io/providers/alasti-company/shipd/latest/docs) for the current installable version and the [provider's GitHub releases](https://github.com/alasti-company/terraform-provider-shipd/releases) for its release notes. **Terraform provider 0.6.0** 2026-11-22 * Manage audit log retention and export destinations with `shipd_audit_settings` and `shipd_audit_destination`. [GitHub release](https://github.com/alasti-company/terraform-provider-shipd/releases/tag/v0.6.0) **Terraform provider 0.5.0** 2026-11-22 * Manage approval policies with `shipd_approval_policy`. [GitHub release](https://github.com/alasti-company/terraform-provider-shipd/releases/tag/v0.5.0) **Terraform provider 0.4.0** 2026-11-22 * Manage project access grants with `shipd_project_access_grant`. [GitHub release](https://github.com/alasti-company/terraform-provider-shipd/releases/tag/v0.4.0) **Terraform provider 0.3.0** 2026-11-19 * Manage SDK keys and workload service account tokens from Terraform. * Manage snapshot webhook destinations and customer event webhook endpoints. [GitHub release](https://github.com/alasti-company/terraform-provider-shipd/releases/tag/v0.3.0) **Terraform provider 0.2.0** 2026-11-19 * Manage service accounts with `shipd_service_account`. [GitHub release](https://github.com/alasti-company/terraform-provider-shipd/releases/tag/v0.2.0) **Terraform provider 0.1.0** 2026-11-08 * Initial Terraform provider release. Manage and import shipd projects and environments, detect drift, and look up existing projects and environments through data sources. [GitHub release](https://github.com/alasti-company/terraform-provider-shipd/releases/tag/v0.1.0) # TypeScript SDK changelog Source: https://docs.useshipd.com/changelog/typescript-sdk Release notes for shipdit, the TypeScript SDK for servers, browsers, and React. ## Overview Release notes for [`shipdit`](/sdks/node), newest first. Upgrade steps for breaking releases are in [Migration guides](/migrations). Version notes are prepared with the version bump. Check the linked npm version for package availability. **shipdit 0.10.0** Version notes ### Minor Changes * 141b028: Define per-environment targeting overrides and guarded progressive rollout plans in `shipd.config.ts`. After `shipd push`, explicit targeting is managed by code. Omit it and push again to return control to the dashboard. See [Targeting in code](https://docs.useshipd.com/reference/config#targeting-in-code). * Pin Ed25519 public keys with the server SDK's `snapshotVerificationKeys` option to verify signed snapshots during refresh. A failed verification keeps the last valid snapshot or uses defaults if no snapshot has loaded. See [Signature verification](https://docs.useshipd.com/concepts/snapshots#signature-verification). [View on npm](https://www.npmjs.com/package/shipdit/v/0.10.0) **shipdit 0.9.0** Version notes ### Minor Changes * 6883d44: Expose detailed remote flag evaluations and replacement evaluation context on browser clients. * 72cd4e6: Add opt-in custom event tracking to the server SDK. Publish named events with evaluation context and JSON details to shipd customer webhooks, with background delivery and a bounded shutdown flush. [View on npm](https://www.npmjs.com/package/shipdit/v/0.9.0) **shipdit 0.8.0** Version notes ### Minor Changes * 97dcbb8: Add server-only detailed evaluations for dynamic flag keys, including per-call defaults, declared flag types, targeting reasons, rule IDs, snapshot versions, and explicit resolution errors. Existing typed getters retain their behavior. [View on npm](https://www.npmjs.com/package/shipdit/v/0.8.0) **shipdit 0.7.0** Version notes ### Minor Changes * fdcb95c: Support optional `clientAvailable` in TypeScript `defineFlags` and version-1 JSON configs. Set it to `true` to permit public client-key evaluation, or `false` to disable it. Diff, push, and pull preserve explicit values; omitted settings preserve existing remote availability, and new flags remain private by default. Availability is project-wide and changes take effect after snapshot publication. Upgrade the control plane, SDK, and CLI together. See [https://docs.useshipd.com/sdks/browser](https://docs.useshipd.com/sdks/browser) for public-key expectations and migration behavior. ### Patch Changes * 1cb4ebb: Refresh dependency and build tooling versions for the CLI, TypeScript SDK, and Convex integration. [View on npm](https://www.npmjs.com/package/shipdit/v/0.7.0) **shipdit 0.6.0** Version notes ### Minor Changes * 8b9ef3c: **Breaking change for browser clients.** Move browser targeting to the edge so client keys receive only requested evaluated values. Full snapshots, targeting rules, audiences, and alternative values remain server-side. Use a client SDK key and remove full-snapshot bootstrap and cache options from browser clients. Browser clients remove legacy persisted snapshots and clear cached values on identity changes. Include keys in defaults for initial loading. Getters serve defaults for new contexts until refreshed values arrive. Polling and streaming continue to refresh values. See the [browser SDK guide](https://docs.useshipd.com/sdks/browser). Evaluation events now include bounded context attributes so identified evaluations can register entities without a separate identify call. Deploy the updated edge endpoint with this SDK release: older browser SDKs cannot read full snapshots with client keys and must upgrade. [View on npm](https://www.npmjs.com/package/shipdit/v/0.6.0) **shipdit 0.5.0** Version notes ### Minor Changes * c6ccd3c: Define complete environment targeting and per-flag trait contracts in config. Push and pull preserve rule order, weighted fallthroughs, and enabled state across TypeScript, Go, and JSON. Targeting changes use existing production drafts and approvals. Local sync baselines detect dashboard conflicts and protect unsynced targeting on pull. Generate typed trait inputs alongside flag accessors. [View on npm](https://www.npmjs.com/package/shipdit/v/0.5.0) **shipdit 0.4.0** Version notes ### Minor Changes * 0de734a: **Breaking changes** (0.x minor). See the timestamp migration instructions: * [https://docs.useshipd.com/migrations/shipdit-0-4#check-timestamp-rules-before-upgrading](https://docs.useshipd.com/migrations/shipdit-0-4#check-timestamp-rules-before-upgrading) * [https://docs.useshipd.com/migrations/convex-0-2#check-timestamp-rules-before-upgrading](https://docs.useshipd.com/migrations/convex-0-2#check-timestamp-rules-before-upgrading) * **Breaking:** timestamp comparisons follow one deterministic grammar: `YYYY-MM-DD` (midnight UTC), or a date-time with a required `Z` or `±hh:mm` zone. Zone-less date-times, lenient formats, and impossible dates now compare as strings instead of through `Date.parse`, so results no longer depend on the server's timezone. Audit date-based rule values and evaluation attributes before upgrading. Dashboard preview adopts this grammar on deploy, so older SDKs can disagree with preview; the edge serves snapshots and does not evaluate rules. * 974027a: **Breaking changes** (0.x minor). See the migration guide: [https://docs.useshipd.com/migrations/shipdit-0-4](https://docs.useshipd.com/migrations/shipdit-0-4) * **Breaking:** server clients (`shipdit`) no longer change evaluation context in `identify()`. It only records an identify event, so one request's identity can't leak into another request on a shared client. Pass context to each evaluation. Server `reset()` is also a no-op and preserves the shared anonymous id without notifying subscribers. Browser clients (`shipdit/client`) are unchanged. Other changes: * `close({ timeoutMs })` returns a promise that resolves once pending events are delivered, including events recorded during an in-flight send, when delivery fails, or after `timeoutMs` (default 5 seconds). * Event batches are capped at the edge's 100-event limit. * Server evaluation events carry the per-call `userId`. * 52de793: **Breaking change** (0.x minor). See [https://docs.useshipd.com/migrations/shipdit-0-4#remove-endpoint-and-streamendpoint](https://docs.useshipd.com/migrations/shipdit-0-4#remove-endpoint-and-streamendpoint) * **Breaking:** the top-level `endpoint` and `streamEndpoint` options were removed and now throw with migration instructions. The client always uses `https://edge.useshipd.com`; pass `stream: true` for realtime updates from `https://ws.useshipd.com`. shipd development and test environments can point elsewhere with `overrides: { unsafeEndpoint, streamEndpoint }`, which are validated, with a warning for plaintext URLs to non-local hosts. [View on npm](https://www.npmjs.com/package/shipdit/v/0.4.0) **shipdit 0.3.1** Version notes ### Patch Changes * 23dffd5: chore: refresh development dependencies [View on npm](https://www.npmjs.com/package/shipdit/v/0.3.1) **shipdit 0.3.0** Version notes ### Minor Changes * 62ba4a0: feat: fill `country`, `region`, `city`, and `timezone` for targeting [View on npm](https://www.npmjs.com/package/shipdit/v/0.3.0) **shipdit 0.2.4** Version notes ### Patch Changes * e5ac21f: Preserve request correlation identifiers when SDK snapshot fetches fail so client diagnostics can be joined to server logs. [View on npm](https://www.npmjs.com/package/shipdit/v/0.2.4) **shipdit 0.2.3** Version notes ### Patch Changes * bdbadbe: fix: resolve `ready()` immediately when the first snapshot fetch fails, so Node processes that await it before opening a server do not exit 13. Evaluations keep using defaults until a later poll succeeds. [View on npm](https://www.npmjs.com/package/shipdit/v/0.2.3) **shipdit 0.2.2** Version notes ### Patch Changes * 2f856b5: Mint short-lived stream tickets before WebSocket connect, reject malformed snapshots on the read path, and keep polling as the correctness floor. Reconnect backoff resets only after an authenticated `connected` frame. Failed diagnostic flushes are requeued with a dropped-event count. [View on npm](https://www.npmjs.com/package/shipdit/v/0.2.2) **shipdit 0.2.1** Version notes ### Patch Changes * c0900e5: accept generated `FlagDefinitions` interfaces in client generics (`FlagMap`) and resolve variant values from the `variants` union so `shipd types gen` output type-checks with `createClient` and `createShipdReact` [View on npm](https://www.npmjs.com/package/shipdit/v/0.2.1) **shipdit 0.2.0** Version notes ### Minor Changes * c68d524: Add `shipdit/client/react` via `createShipdReact()` (opt-in, client-only; typegen stays types-only) and `subscribe` / `getRevision` on the runtime client for external stores. [View on npm](https://www.npmjs.com/package/shipdit/v/0.2.0) **shipdit 0.1.0** Version notes ### Minor Changes * 59ca1ce: Add optional `streamEndpoint` WebSocket invalidation with min-version HTTP retries and schema/version guards (bundles shared stream protocol helpers from `@shipd/core`). [View on npm](https://www.npmjs.com/package/shipdit/v/0.1.0) # Architecture Source: https://docs.useshipd.com/concepts/architecture How flag changes reach your application and how local evaluation behaves during outages. ## Overview You manage flags in the dashboard, CLI, or management API. Server SDKs download an environment's configuration as a snapshot and evaluate flags locally in memory, without a network request on each check. Browser SDKs evaluate `clientAvailable: true` flags at the edge via `POST /sdk/v1/evaluate` and keep only resolved values in memory. See [Client vs. server evaluation](/concepts/client-vs-server). ## Manage flags Use the dashboard or [config as code](/reference/config#targeting-in-code) to change targeting rules, enabled state, and fallthrough values. Use the CLI to sync code definitions, or the [management API](/reference/control-plane-api) to automate supported operations. Code-owned targeting publishes from `shipd push` when approval policy allows. Dashboard production targeting edits create drafts for publication. [Signal-driven rollouts](/reference/config#signal-driven-rollout) compile to the same local snapshot rules; signal checks never enter SDK evaluation. Organizations, projects, environments, and credentials determine who can change flags and which configuration your application receives. See [Environments](/concepts/environments), [Access control](/enterprise/access-control), and [Keys](/concepts/keys). ## Evaluate in your application Server SDKs (`shipdit` and Go) download a [snapshot](/concepts/snapshots) for the environment bound to their server SDK key from `https://edge.useshipd.com` and evaluate each flag check locally in memory. Browser SDKs (`shipdit/client`) instead send requested `clientAvailable: true` keys and context to `POST /sdk/v1/evaluate` at the edge and keep only the resolved values in memory—targeting rules, audiences, and server-only flags never reach the browser. * Flag checks do not wait for the dashboard or control-plane API. * Rules can use only the snapshot and evaluation context available to the evaluator. * Percentage rollouts assign the same bucket for the same flag key and bucket attribute. See [Local evaluation](/concepts/local-evaluation) and [Client vs. server evaluation](/concepts/client-vs-server) for startup defaults, caching, and fallback behavior. ## Receive changes Server SDKs poll for updated snapshots, while browser SDKs poll `POST /sdk/v1/evaluate` for refreshed values. TypeScript SDKs can also enable realtime updates with `stream: true`: an update notification triggers a refresh (a snapshot fetch on servers, or a re-evaluation request in browsers) rather than waiting for the next poll. Streaming needs a WebSocket implementation. Node.js 20 callers supply the `WebSocket` option; browsers and Node.js 22+ provide one. See [SDK reference](/reference/sdk#createclient). With a positive `refreshIntervalMs`, polling continues if streaming is unavailable. With `refreshIntervalMs: 0`, the client keeps its last good snapshot or values until a manual refresh or another update notification. Go uses polling. ## Handle service interruptions If a refresh fails, server SDKs keep evaluating with their last good snapshot and browser SDKs retain the last good values for the current context. Before initial data loads, SDKs use configured defaults (or supported server `bootstrap`/`cache` options). Changes made during an interruption reach your application after a successful refresh. See [What happens if shipd is down?](/concepts/local-evaluation#what-happens-if-shipd-is-down) and [Troubleshooting](/resources/troubleshooting). ## Understand data sharing Server evaluation runs locally; browser evaluation sends only the requested flag keys and evaluation context to `POST /sdk/v1/evaluate`. SDKs can also send evaluation and identify events; those are separate from flag checks. Review [Identify users](/flags/identify-users) and the [Edge API](/reference/edge-api) for event contents and behavior. Disable event delivery with `events: false` in TypeScript or `DisableEvents: true` in Go. # Client vs. server evaluation Source: https://docs.useshipd.com/concepts/client-vs-server When to evaluate flags with the browser SDK versus on your server, what each SDK exposes, how to deliver private values to a frontend, and why flags do not replace authorization. ## Overview Use the browser SDK (`shipdit/client`) for flags whose evaluated values are safe to expose to anyone with your public client SDK key. Evaluate flags on your server (`shipdit` or the Go SDK) when targeting depends on verified identity, role, or billing plan, or when flag values should stay private. You can combine both in one app, and neither replaces backend authorization. ## What each SDK exposes Server and browser SDKs use different credentials and receive different data from the edge. | | Server SDK (`shipdit`, Go) | Browser SDK (`shipdit/client`, `shipdit/client/react`) | | - | - | - | | SDK key | `shipd_sdk_server_…` (secret, server-only) | `shipd_sdk_client_…` (public in browser bundles) | | Where evaluation runs | Locally in process from a downloaded snapshot | At the edge (`POST /sdk/v1/evaluate`); values kept in memory | | Snapshot access | Full environment snapshot (`GET /sdk/v1/snapshot`), including all flags, targeting rules, audiences, rollouts, and variants | None (`GET /sdk/v1/snapshot` returns `403`). Rejects `bootstrap` and snapshot `cache` adapters | | Flag visibility | Every flag in the environment | Only explicitly requested flags with `clientAvailable: true` (default is `false`) | | Trust in evaluation context | Verified by your server (session, RBAC, billing database) | Caller-supplied (`userId`, `attributes`, `segmentIds` can be spoofed) | | Realtime updates | `stream: true` invalidates and refreshes the local snapshot | `stream: true` invalidates and refreshes requested values from `/sdk/v1/evaluate` | A server snapshot contains your full targeting configuration—rules, audience predicates, rollout percentages, and every variant value. Keep server SDK keys and snapshots on infrastructure you control. Never serialize a server snapshot into browser HTML or pass it to a client. A browser SDK never downloads a snapshot, so targeting rules, audiences, unused variants, and server-only flags (`clientAvailable: false`) stay off the user's device. However, a client SDK key is still a public credential: anyone who extracts the key from your bundle can call `POST /sdk/v1/evaluate` with any `userId`, `attributes`, or `segmentIds` they choose and read the resolved value (including any JSON payload) for every flag marked `clientAvailable: true`. ## Choose where to evaluate a flag | Use the browser SDK (`shipdit/client`, `clientAvailable: true`) | Evaluate on the server (`shipdit` / Go, `clientAvailable: false`) | | - | - | | Public UI presentation rollouts (layout, editor, navigation variants) | Decisions based on verified user identity, organization membership, role, or billing plan | | Anonymous visitor and marketing experiments | Internal tools, debug routes, or staff-only capabilities | | Browser-only context such as edge geolocation (`country`, `region`, `city`, `timezone`) | Private beta access where you do not want callers probing who is enabled | | Non-sensitive copy, styling, or UI config where spoofing traits has no security or business impact | Sensitive JSON payloads, operational kill switches, or backend API behavior | Many applications use both patterns together: the browser SDK with `stream: true` drives public UI presentation flags with realtime updates, while an authenticated backend endpoint delivers private evaluated values. ## Deliver privately evaluated values to your frontend When a frontend needs the result of a server-only flag, evaluate an explicit allowlist of flags on your backend and return only the resolved values—never the raw snapshot or targeting rules. ### 1. Evaluate allowlisted flags with verified server identity Derive `userId`, organization membership, role, and plan from your authenticated session and database. Ignore targeting attributes sent in the request body or query string, and disable HTTP caching with `Cache-Control: no-store`. ```ts src/routes/capabilities.ts theme={null} import { Hono } from "hono"; import { shipd } from "../lib/shipd.server"; export const capabilitiesRoute = new Hono(); capabilitiesRoute.get("/api/capabilities", async (c) => { const session = await requireAuthenticatedSession(c); // verifies user, org, role, plan const context = { userId: session.userId, attributes: { organizationId: session.organizationId, role: session.role, plan: session.plan, }, }; return c.json( { // Explicit allowlist of evaluated values only; never return a snapshot. auditLog: shipd.isEnabled("audit-log", context), localEvaluations: shipd.isEnabled("local-evaluations", context), }, 200, { "Cache-Control": "no-store" }, ); }); ``` In frameworks with server rendering (such as [Next.js](/sdks/nextjs#evaluate-on-the-server)), you can evaluate the same allowlist during the server render and pass the resolved values as props to avoid an initial loading flash. ### 2. Keep private values updated in the browser Pair initial loading with polling, and add an authenticated Server-Sent Events (SSE) invalidation stream when you want realtime updates: 1. **Initial fetch or SSR props.** Load the evaluated values after authentication completes. 2. **Polling fallback.** Refetch `/api/capabilities` periodically (for example, every 30 seconds) or on window focus. 3. **Realtime invalidations (optional).** Run your server SDK client with `stream: true`, subscribe with `shipd.subscribe(...)`, and push an empty invalidation event over an authenticated SSE route (`Cache-Control: no-store`). When the browser receives the event, it refetches `/api/capabilities`. ```ts src/routes/capabilities-stream.ts theme={null} import { Hono } from "hono"; import { streamSSE } from "hono/streaming"; import { shipd } from "../lib/shipd.server"; export const capabilitiesStreamRoute = new Hono(); capabilitiesStreamRoute.get("/api/capabilities/stream", async (c) => { await requireAuthenticatedSession(c); c.header("X-Accel-Buffering", "no"); const response = streamSSE(c, async (stream) => { let dirty = false; let wake: (() => void) | undefined; const stop = () => { wake?.(); stream.abort(); }; const unsubscribe = shipd.subscribe(() => { dirty = true; wake?.(); }); // Bound stream lifetime so reconnects re-check session and membership. const timeout = setTimeout(stop, 30_000); stream.onAbort(stop); try { while (!stream.aborted) { if (dirty) { dirty = false; await stream.writeSSE({ event: "capabilities.updated", data: "{}" }); continue; } await new Promise((resolve) => { wake = resolve; }); wake = undefined; } } catch { // Client disconnected; EventSource will reconnect and re-authenticate. } finally { clearTimeout(timeout); unsubscribe(); } }); // Hono's streamSSE sets Cache-Control: no-cache; override it on the response. c.header("Cache-Control", "no-store"); response.headers.set("Cache-Control", "no-store"); return response; }); ``` ```ts src/lib/use-capabilities.ts theme={null} const stream = new EventSource("/api/capabilities/stream", { withCredentials: true }); stream.addEventListener("capabilities.updated", () => { void refetchCapabilities(); }); ``` Sending only an empty invalidation event keeps flag data out of long-lived stream buffers and forces every refetch of `/api/capabilities` to re-verify authentication, organization membership, role, and plan. ## Flags do not replace backend authorization > [!WARNING] > > Never rely on a flag—client-evaluated or server-evaluated—as your only access control check. Flags control feature rollout and UI exposure, not permissions: * **Browser flags are untrusted.** Any user can inspect your bundle, spoof evaluation context, or call your API directly without going through hidden UI. * **Authenticated capability endpoints only inform the UI.** Returning `{ auditLog: true }` from `/api/capabilities` tells the browser what to render; it does not protect the underlying API route. * **Enforce authorization on every backend handler.** Check authentication, role/RBAC permissions, tenant membership, and billing entitlements on every read and mutation endpoint. If a backend feature is also behind a release flag, evaluate the server-only flag *in addition to*—never instead of—your authorization checks. ## Related * [Browser SDK](/sdks/browser) * [Node.js and server runtimes](/sdks/node) * [Next.js](/sdks/nextjs) * [SDK keys, management API keys, and service account tokens](/concepts/keys) * [Local evaluation](/concepts/local-evaluation) * [Snapshots](/concepts/snapshots) # Organizations, projects, environments Source: https://docs.useshipd.com/concepts/environments How tenancy, production gating, and per-env defaults work. ## Overview shipd scopes everything to an organization, a project, and an environment. The same three scopes appear on management API keys, SDK keys, and every `shipd` command (`--org`, `--project`, `--env`). ## Hierarchy ```text theme={null} organization fieldkit └── project web-app ├── environment production (isProduction: true) └── environment staging ``` A project has at most one live production environment. Its slug can be `production`, `canary`, or `production-eu`; protection comes from the `isProduction` setting, not the name. Admins and owners can click **Mark as production** on the dashboard's **Environments** page. The confirmation identifies the current production environment, which loses that status when you promote another environment. Click **Remove production status** to clear the setting. [MCP environment tools](/reference/mcp) also support `isProduction` for authorized write connections. ## What is project-global and what is per environment | | Project-global | Per environment | | - | - | - | | Flag key, type, variants, tags, lifecycle | yes | | | Default / fallthrough, targeting rules, enabled | | yes | | SDK key | | yes (bound to one env) | | Management API key | | yes (bound to organization, project, and one environment) | Changing a definition (type, variants, and so on) applies to **all** environments, so `shipd push` warns you. When the project has a production environment, applying a definition change requires `flag.production.toggle` even with `--env staging`. Default-only updates on a non-production environment need only `flag.state.update`. See [Organizations and access control](/enterprise/access-control#production-safeguards). ## Keys Every credential is bound to part of this hierarchy. An SDK key belongs to exactly one environment, so a server in staging and a server in production use different SDK keys. A management API key is bound to one organization, project, and environment. `shipd login` picks all three in the browser and stores a management API key, not a user session. For prefixes, where each key is created, and which one to use, see [SDK keys, management API keys, and service account tokens](/concepts/keys). ## Next * [Define flags in code](/config-as-code/define-flags) * [SDK keys, management API keys, and service account tokens](/concepts/keys) * [CLI reference](/reference/cli) # SDK keys, management API keys, and service account tokens Source: https://docs.useshipd.com/concepts/keys Which shipd credential to use where: server SDK key vs client SDK key, CLI keys, and CI tokens. ## Overview shipd has three kinds of credentials. **SDK keys** read flags from the edge (data plane). **Management API keys** and **service account tokens** change flags through the control plane. A credential for one plane never works on the other. ## At a glance | Credential | Prefix | Plane | Where you create it | Bound to | Safe in a browser? | Used by | | - | - | - | - | - | - | - | | Server SDK key | `shipd_sdk_server_` | Data plane (`edge.useshipd.com`) | Project → **SDK keys** → **Create SDK key**, **Key type** `server` | One environment | No | `shipdit` on Node.js, Workers, server-side Next.js, [Convex](/sdks/convex) | | Client SDK key | `shipd_sdk_client_` | Data plane (`edge.useshipd.com`) | Project → **SDK keys** → **Create SDK key**, **Key type** `client` | One environment | Yes | `shipdit/client`, `shipdit/client/react` | | Management API key | `shipd_mgmt_` | Control plane (`api.useshipd.com`) | `shipd login`, or **Settings → API keys** → **Create key** | One organization, project, and environment | No | The `shipd` CLI on your machine | | Service account token | `shipd_sa_` | Control plane (`api.useshipd.com`) | **Settings → Service accounts** → **Create service account** → **Create token** | Explicit scopes, optional project or environment binding, optional expiry | No | CI and other automation | SDK keys are created for the environment that is active in the dashboard when you click **Create SDK key**. Every key is shown once; copy it before you close the dialog. ## Server SDK key vs client SDK key Use a **server SDK key** when the code runs on infrastructure you control. Use a **client SDK key** when the code ships to a user's device. | | Server SDK key | Client SDK key | | - | - | - | | Runs in | Your servers, Workers, route handlers, server components, Convex | Browser bundles, React client components, mobile apps | | Can be public | No. Keep it in a server-only secret. | Yes. It is expected to be visible in the bundle. | | Snapshot contents | Full snapshot, including targeting rules | No full snapshot. Only requested evaluated values from `POST /sdk/v1/evaluate`. | | Identity trait overlay (`GET /sdk/v1/identity`) | Yes | No | | Automatic location traits | No. Pass traits yourself. | Yes. `country`, `region`, `city`, and `timezone` from the edge. | Client keys cannot download targeting rules or audiences. They are public credentials: anyone with the key can request known `clientAvailable: true` flag values and supply evaluation traits. Keep private values, verified identity/role/plan targeting, and authorization decisions server-side. See [Client vs. server evaluation](/concepts/client-vs-server) for how to choose between SDKs and deliver privately evaluated values to a frontend. ## Which credential should I use? | You want to | Use | | - | - | | Evaluate flags in a Node.js server, Worker, or Convex function | Server SDK key | | Evaluate flags in the browser or in React client components | Client SDK key | | Run `shipd push`, `pull`, or `diff` from your laptop | Management API key, created by `shipd login` | | Run `shipd push` or `diff` in GitHub Actions or another CI system | Service account token in `SHIPD_API_KEY` | | Call the [control-plane API](/reference/control-plane-api) from a script | Service account token | The CLI reads `SHIPD_API_KEY` for both management API keys and service account tokens. See [Sync flags in CI](/config-as-code/ci) and [Create a service account](/enterprise/service-accounts). ## Rotate or revoke a credential | Credential | How to rotate | | - | - | | SDK key | Create a new key for the same environment, deploy it, then click **Revoke** on the old key. Apps still using the old key keep their last good snapshot and report a `401` to `onError`. | | Management API key | Revoke it on **Settings → API keys** (admin or owner), then run `shipd login` again. | | Service account token | Create a new token, update your CI secret, then revoke the old token. Disable the service account to invalidate all of its tokens at once. See [Service account tokens](/reference/service-account-tokens). | Revocation fails closed on the edge as soon as it propagates; open WebSocket connections are revalidated at least every 60 seconds. See [Edge API](/reference/edge-api). A management API key is checked against its creator's current role and project access on every use. If the creator loses access, the key stops working. ## Common mistakes > [accordion] A server SDK key in the browser bundle > > Any key in client code is public. If you put a `shipd_sdk_server_` key in a browser bundle (for example, in a `NEXT_PUBLIC_` environment variable), revoke it and create a client key for the browser. Keep the server key in a server-only secret. > [accordion] A management API key as the SDK key > > `createClient({ sdkKey: "shipd_mgmt_…" })` fails: the edge returns `401` for any credential that is not an SDK key. Create an SDK key on the project's **SDK keys** page. > [accordion] An SDK key for the CLI > > `SHIPD_API_KEY=shipd_sdk_…` fails with `401 unauthenticated`: SDK keys only work on the edge. Run `shipd login` locally, or use a service account token in CI. > [accordion] An SDK key from a different environment > > Each SDK key reads exactly one environment. If flags show staging values in production, check that the key was created with the production environment active. ## Related * [Organizations, projects, environments](/concepts/environments) * [Organizations and access control](/enterprise/access-control) * [Edge API](/reference/edge-api) * [Troubleshooting](/resources/troubleshooting) # Local evaluation Source: https://docs.useshipd.com/concepts/local-evaluation Why flag checks never wait on the network, and what happens if shipd is down. ## Overview On server SDKs (`shipdit` and Go), a flag check is a function call: look at the in-memory snapshot, hash if needed, and return a value. The SDK talks to the edge only to **refresh** that snapshot. Browser SDKs (`shipdit/client`) instead evaluate targeting at the edge via `POST /sdk/v1/evaluate` and keep only resolved values in memory so snapshots and targeting rules stay server-side; see [Client vs. server evaluation](/concepts/client-vs-server). See [SDK benchmarks](/reference/benchmarks) for measured evaluation latency, throughput, and update propagation, including behavior during snapshot replacement. ## Hot path ```ts TypeScript theme={null} shipd.isEnabled("new-checkout", { userId: "usr_8f2k19" }); // snapshot.flags["new-checkout"] + context → boolean ``` ```go Go theme={null} client.IsEnabled("new-checkout", shipd.EvaluationContext{UserID: "usr_8f2k19"}) // Snapshot + context → boolean. ``` No HTTP, no WebSocket, no Postgres. Rules can only use what is in the snapshot and the evaluation context, so a rule such as "everyone we saw last week" is not possible at evaluation time. ## Refresh path ```text theme={null} ready() / poll / snapshot.updated │ ▼ GET /sdk/v1/snapshot (ETag / If-None-Match) │ ├── 200 → atomic replace ├── 304 → keep └── error → onError, keep last good ``` TypeScript's `stream: true` only **invalidates**. Go refreshes by polling or manual `Refresh(ctx)`. Refreshes fetch snapshots over HTTP; startup can instead use a supplied bootstrap snapshot or, in TypeScript, a cached snapshot. See [Snapshots](/concepts/snapshots) for version and rollback rules. ## What happens if shipd is down? Flag checks keep working. Each part of shipd fails independently: | What is down | What still works | What fails | | - | - | - | | Edge (`edge.useshipd.com`) | Evaluation from the last good snapshot in memory | Snapshot refreshes and event delivery. Errors go to TypeScript's `onError` or Go's `LastError`; snapshot refreshes retry on the next poll, while event delivery retries on the event flush interval (Go: `FlushInterval`). | | Control plane (`api.useshipd.com`) | Evaluation and snapshot fetches. The edge keeps serving the last published snapshot. | `shipd push`, `shipd pull`, the dashboard, and every other way to change flags. Nothing new is published until it recovers. | | WebSocket gateway (`ws.useshipd.com`) | Evaluation and snapshot fetches | Instant updates. TypeScript continues polling when `refreshIntervalMs` is positive (30 seconds by default). With polling disabled, use manual refreshes. | TypeScript clients starting while the edge is unreachable use the first available source below. Go serves its `Bootstrap` snapshot if you set one, otherwise configured defaults, until its first valid snapshot. Go has no persisted cache in this release. | Source | When it applies | | - | - | | `bootstrap` snapshot | Server client where you passed `bootstrap` to `createClient` | | Cached snapshot | Server client with a custom `cache` adapter | | Your `defaults` | Nothing else is available (and on browser clients before initial evaluated values arrive) | TypeScript's `ready()` resolves after `readyTimeoutMs` (5 seconds by default) and never rejects for network errors. Evaluation methods never throw. An unknown key returns your default and emits an `unregistered_flag` event. Go's `Ready(ctx)` returns when a snapshot loads, when the initial fetch fails, or when the context expires. An initial fetch failure returns immediately without waiting for the deadline; handle the error and decide whether to accept traffic with defaults. Go uses `RefreshInterval` for polling (30 seconds by default), and `DisablePolling` leaves updates to manual refreshes. Related: [Reliability and data handling](/reference/reliability-and-data) · [SDK](/reference/sdk). ## Bucketing Percentage conditions hash `flagKey + userId` (or a chosen attribute) into one of 10,000 buckets (0 to 9999). The same inputs always land in the same bucket, so nothing is stored to make assignments sticky. Without a `userId` (or the chosen attribute), a percentage condition never matches. See [Roll out a flag to a percentage of users](/flags/percentage-rollouts). ## Next * [Node.js and server runtimes](/sdks/node) * [Snapshots](/concepts/snapshots) * [SDK reference](/reference/sdk) # Snapshots Source: https://docs.useshipd.com/concepts/snapshots The evaluation payload SDKs download from the edge. ## Overview A snapshot contains the flag values, targeting rules, and audiences a **server SDK** needs to evaluate flags locally for one environment. Server SDKs (`shipdit` and Go) download published snapshots automatically. Browser SDKs (`shipdit/client`) never download full snapshots; they request evaluated values for `clientAvailable: true` flags from `POST /sdk/v1/evaluate`. Snapshots exclude audit logs, credentials, tags, and `managedBy` metadata, but include targeting rules and audiences—keep snapshots server-side and avoid putting secrets in rules or flag values. See [Client vs. server evaluation](/concepts/client-vs-server). ## Shape ```json theme={null} { "schemaVersion": 1, "projectId": "prj_fieldkit_web", "environmentId": "env_prod_01", "environmentKey": "production", "version": 42, "generatedAt": "2026-08-18T16:04:00.000Z", "flags": { "new-checkout": { "key": "new-checkout", "type": "boolean", "enabled": true, "default": false, "version": 7, "rules": [], "fallthrough": { "kind": "boolean", "value": false } } }, "segments": {} } ``` `version` increases per environment, independently of each flag's version. Use it to check whether an application has received a recent configuration change. ## Receive a new snapshot Dashboard production targeting saves create drafts, including default changes from `shipd push` when targeting is omitted. Explicit code-owned targeting publishes from push when approval policy allows. The flag’s **Across environments** table compares live targeting with saved drafts. Click **Publish changes** to apply ready drafts, producing one snapshot per environment. A matching approval policy requires review before you can publish. Non-production targeting saves publish immediately unless review is required; unprotected definition edits remain immediate, while policy-covered definition changes are blocked. SDKs fetch changes through polling or, for TypeScript clients with streaming enabled, after an update notification. Publication and refresh can take time. If your application still serves an older value, start with [Troubleshooting](/resources/troubleshooting). If a publication failed, see [Publish a snapshot](/operations/publish-a-snapshot). ## SDK rules * Fetch current snapshot only (no replay of versions 11–14 if you jumped 10 → 15) * Ignore HTTP bodies with `version < local` (no rollback) * After an update notification, retry until the notified version is available, then keep the last good snapshot if refresh fails * Unsupported `schemaVersion` → `onError`, keep last good `ETag: "snapshot-"`. Send `If-None-Match` to get `304`. ## Next * [Publish a snapshot](/operations/publish-a-snapshot) * [Edge API](/reference/edge-api) * [Architecture](/concepts/architecture) ## Signature verification Your shipd operator can enable Ed25519 signatures for server snapshots. When enabled, the detached signature covers the exact snapshot bytes, including code-owned targeting and rollout metadata. Configure trusted public keys to require verification on refresh: ```ts TypeScript theme={null} // server.ts const client = createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, snapshotVerificationKeys: { "release-2026": process.env.SHIPD_SNAPSHOT_PUBLIC_KEY! }, defaults: { "new-checkout": false }, }); ``` ```go Go theme={null} // main.go client, err := shipd.New(shipd.Options{ SDKKey: os.Getenv("SHIPD_SDK_KEY"), SnapshotVerificationKeys: map[string]string{ "release-2026": os.Getenv("SHIPD_SNAPSHOT_PUBLIC_KEY"), }, }) ``` Use PEM SPKI Ed25519 public keys. A missing signature, unknown key, or changed body fails refresh and retains the last good snapshot or defaults. Keys are optional for existing deployments. Verification runs at refresh time; flag evaluation remains in process. Application-provided bootstraps remain trusted. Go cache adapters must persist `CachedSnapshot.Signature`; pinned clients verify cached bytes with the current keys before using them. Legacy unsigned cache entries trigger a fresh fetch. Browser keys use remote evaluation rather than downloading server snapshots. # Sync flags in CI Source: https://docs.useshipd.com/config-as-code/ci Check shipd.config.ts for drift on pull requests and push it on merge with a service account token. ## Overview In this guide you set up two GitHub Actions workflows for the `web-app` project: one runs `shipd diff --exit-code` on pull requests that touch your flag definitions, and one runs `shipd push` when it merges to `main`. Both authenticate with a service account token (`shipd_sa_…`), not a personal key. **Prerequisites** * Your flag config and generated output committed (`shipd.config.ts` and TypeScript types, or Go source and generated Go accessors). See [Define flags in code](/config-as-code/define-flags). * For TypeScript, `@shipdit/cli` in your `devDependencies`. The Go workflow pins the shared CLI to 0.5.0 (the upcoming Go-support release); update that version to match your team once it is published. * Permission to create service accounts (organization admin or owner). To have your coding agent prepare these workflows, [install shipd agent skills](/operations/agent-skills) and ask it to use `shipd-ci`. ## Create a service account token Create a service account named `github-actions`, then create a token bound to the `web-app` **project**. Do not bind it to an environment: `shipd push` makes project-wide changes, and environment-bound credentials get `403 forbidden`. Steps are in [Create a service account](/enterprise/service-accounts). Use two tokens so pull request jobs cannot change flags: | Token | Secret name | Scopes | | - | - | - | | Pull request (read-only) | `SHIPD_DIFF_TOKEN` | `flag:read`, `environment:read` | | Main branch (write) | `SHIPD_PUSH_TOKEN` | `flag:update`, `flag:create`, `flag_state:update`, `flag_production:toggle`, `environment:read` | Add `flag:archive` only if the job runs `shipd push --prune`. Why each permission is needed is in [Push permissions](/reference/cli#permissions). Create a `shipd-diff` environment under **Settings → Environments**, require trusted reviewers, and store `SHIPD_DIFF_TOKEN` as an environment secret there. Review the pull request commit before approving this environment job: TypeScript and Go configs execute code, and Go tests execute pull-request code too. Restrict approval to trusted changes; do not approve untrusted fork jobs. The examples deliberately gate the whole diff job before it receives the token. Store `SHIPD_PUSH_TOKEN` as a repository secret under **Settings → Secrets and variables → Actions** for the protected `main` branch workflow. Both workflow examples use the file paths from [Define flags in code](/config-as-code/define-flags). Go source selects Go output by default unless `typesLanguage` overrides it. ## Check drift on pull requests ```yaml TypeScript theme={null} # .github/workflows/flags-diff.yml name: flags-diff on: pull_request: paths: ["shipd.config.ts"] jobs: diff: environment: shipd-diff permissions: contents: read runs-on: ubuntu-latest env: SHIPD_API_URL: https://api.useshipd.com SHIPD_API_KEY: ${{ secrets.SHIPD_DIFF_TOKEN }} steps: - uses: actions/checkout@v4 with: persist-credentials: false - uses: pnpm/action-setup@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: pnpm - run: pnpm install --frozen-lockfile - run: pnpm exec shipd diff --exit-code --env production ``` ```yaml Go theme={null} # .github/workflows/flags-diff.yml name: flags-diff on: pull_request: paths: ["**/*.go", "go.mod", "go.sum"] jobs: diff: environment: shipd-diff permissions: contents: read runs-on: ubuntu-latest env: SHIPD_API_URL: https://api.useshipd.com SHIPD_API_KEY: ${{ secrets.SHIPD_DIFF_TOKEN }} steps: - uses: actions/checkout@v4 with: persist-credentials: false - uses: actions/setup-node@v4 with: node-version: 22 - uses: actions/setup-go@v6 with: go-version: "1.23" - run: npm install -g @shipdit/cli@0.5.0 - name: Validate definitions and generated accessors run: | shipd types gen git ls-files --error-unmatch internal/flags/flags_gen.go git diff --exit-code -- internal/flags/flags_gen.go go test ./... - run: shipd diff --exit-code --env production ``` `SHIPD_API_URL` is required. Without it, a runner that never ran `shipd login` calls `http://localhost:8000`. | Exit | Result | What to do | | - | - | - | | `0` | No drift | Nothing. | | `2` | The pull request changes flags | Expected when you edit `shipd.config.ts`. Read the plan in the job log. Make the job non-blocking if you only want the plan as information. | | `4` | Unlinked flags in the plan | Run `shipd diff` locally and follow its note. See [exit codes](/reference/cli#exit-codes). | | `1` | Error | Read the `Error:` line. See [Errors](/reference/errors#cli-error-codes). | `shipd diff` also reports flags that exist on the server but not in the file, as `- archive flag`, and counts them as drift. Add them to `shipd.config.ts` (or `shipd pull`) so the diff shows only your changes. ## Push on main ```yaml TypeScript theme={null} # .github/workflows/flags-push.yml name: flags-push on: push: branches: [main] paths: ["shipd.config.ts"] concurrency: shipd-push jobs: push: runs-on: ubuntu-latest env: SHIPD_API_URL: https://api.useshipd.com SHIPD_API_KEY: ${{ secrets.SHIPD_PUSH_TOKEN }} steps: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: pnpm - run: pnpm install --frozen-lockfile - name: shipd push run: | set +e pnpm exec shipd push --ci --env production code=$? if [ "$code" -eq 5 ]; then echo "::warning::shipd push queued changes for approval. They are not live until approved." exit 0 fi exit "$code" ``` ```yaml Go theme={null} # .github/workflows/flags-push.yml name: flags-push on: push: branches: [main] paths: ["**/*.go", "go.mod", "go.sum"] concurrency: shipd-push jobs: push: runs-on: ubuntu-latest env: SHIPD_API_URL: https://api.useshipd.com SHIPD_API_KEY: ${{ secrets.SHIPD_PUSH_TOKEN }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 - uses: actions/setup-go@v6 with: go-version: "1.23" - run: npm install -g @shipdit/cli@0.5.0 - name: Validate definitions and generated accessors run: | shipd types gen git ls-files --error-unmatch internal/flags/flags_gen.go git diff --exit-code -- internal/flags/flags_gen.go go test ./... - name: shipd push run: | set +e shipd push --ci --env production code=$? if [ "$code" -eq 5 ]; then echo "::warning::shipd push queued changes for approval. They are not live until approved." exit 0 fi exit "$code" ``` * `--ci` skips the confirmation prompt. `CI=true`, which GitHub Actions sets, does the same. Without either, push is cancelled in a non-interactive job. * `concurrency` stops two merges from pushing at once and conflicting with each other. * Pushing to `production` needs `flag_production:toggle` even for a `default`-only change. ## Go projects Use the same tokens, permission scopes, and exit codes. Install Go 1.23+ and Node.js 22.12+ on the runner. The CLI reads `shipd.config.go` directly and selects Go output by default unless `typesLanguage` overrides it. The workflows watch all Go source so edits to imported local helper packages also trigger them. Include any non-Go files those helpers read in the path filters, and adjust the output checks if you override `typesLanguage` or `typesOut`. ```bash theme={null} shipd types gen git ls-files --error-unmatch internal/flags/flags_gen.go git diff --exit-code -- internal/flags/flags_gen.go shipd diff --exit-code ``` `git ls-files` fails if the generated output is not tracked. The first diff checks that committed accessors match the Go definitions; the CLI diff compares definitions with the server. ## Handle exit codes 3 and 5 | Exit | Meaning | What to do | | - | - | - | | `3` | Conflict. A flag changed on the server after the plan, a change for the flag is already waiting for approval, or an approval policy blocks a definition change. Nothing was applied. | Let the job fail. On your machine, `shipd pull`, re-apply your edits, and open a new pull request. See [Why did shipd push return a conflict?](/config-as-code/conflicts) | | `5` | Some changes are queued for approval and not live. Other changes in the push applied. | The workflow above passes with a warning. A reviewer approves the request in the dashboard. See [Approvals](/operations/approvals). | Do not add `--force` to CI. It overwrites changes made in the dashboard, and it cannot bypass approvals. The full exit code list is in the [CLI reference](/reference/cli#exit-codes). ## Next steps * [Push, pull, and diff](/config-as-code/sync) * [Service account tokens](/reference/service-account-tokens) * [GitHub Actions example](/examples/github-actions) # Why did shipd push return a conflict (409 / exit 3)? Source: https://docs.useshipd.com/config-as-code/conflicts Causes of a shipd push conflict and how to recover without overwriting someone else's change. ## Overview `shipd push` exits `3` for targeting drift against its local sync baseline or when the server returns `409 conflict`. `shipd pull` also exits `3` when it would overwrite tracked local targeting edits. Nothing from the conflicted sync was applied. This page explains each cause and how to fix it. ```text theme={null} Error: Flag "search-variant" changed remotely (expected version 4, remote 5). Pull and retry, or pass --force. ``` ## Causes | Message starts with | Cause | | - | - | | `Flag "" targeting changed in the dashboard` | Published targeting differs from your last sync baseline and local definitions. Reconcile both sides before pushing. | | `Pull would overwrite local targeting changes` | Local targeting differs from the baseline and server state. Save your edits separately before pulling, or use `pull --force` to explicitly replace them. | | `Flag "" changed remotely` | **Stale version.** Someone changed the flag's definition after your push computed its plan. | | `Flag "" environment state changed remotely` | **Stale version.** Someone changed the environment's fallthrough, rules, or enabled switch after your plan. | | `Flag "" was created concurrently` | **Concurrent create.** Someone else created the same flag key between your plan and apply. Fix it the same way as a stale version: pull and push again. | | `A pending approval request already exists` | **Pending approval.** An earlier change to this flag in this environment is waiting for review. | | `This operation affects an environment protected by approval policy` | **Unsupported protected operation.** You created, archived, or changed the definition of a flag in a project where an approval policy covers an environment. These changes cannot be queued for review. | Every message is listed in [Errors](/reference/errors#push-conflict-messages). ## Fix a stale version Start from what is live, then re-apply your edit. **1. Save your edits** ```bash theme={null} git stash # or commit shipd.config.ts to a branch ``` **2. Pull** ```bash theme={null} shipd pull --env production ``` `shipd.config.ts` and `src/generated/flags.ts` are rewritten from the server. Comments are lost. If you committed your edits but the targeting guard still rejects the pull, first verify the commit contains them, then use `shipd pull --force` to replace the local file before reconciling. A commit alone does not reset the sync baseline. **3. Re-apply your edit** For stashed edits, inspect `git stash show -p`. For committed edits, inspect `git show -- shipd.config.ts` (or your Go/JSON config path). Reapply the intended changes on top of the pulled file; avoid restoring the entire old file and overwriting dashboard updates. **4. Diff and push** ```bash theme={null} shipd diff --env production shipd push --env production ``` The plan should contain only your change. ## Reconcile Go definitions Pull rewrites `shipd.config.go` directly and regenerates accessors. After resolving a stale version, inspect the Go diff and then push. See [Go definitions](/config-as-code/define-flags#go-definitions). ## Fix a pending approval Wait for a reviewer to approve or reject the open request in the dashboard, then push again. See [Approvals](/operations/approvals). ## Fix an unsupported protected operation The push mixed a definition change with a project that has an approval policy. Make the definition change in a way your policy allows, or ask an admin to adjust the policy. See [Approval workflows](/reference/approvals). ## --force: last resort ```bash theme={null} shipd push --force --env production ``` `--force` skips the version check and writes your file over whatever changed on the server. Use it only after you have read the other change and decided to discard it. * It is recorded in the [audit log](/operations/audit-log) with the reason `Forced CAS override`. * It does not bypass approval policies or pending requests. Those still exit `3` or `5`. * It does not skip permission checks. Details: [Conflicts](/reference/cli#conflicts). ## Next steps * [Push, pull, and diff](/config-as-code/sync) * [Sync flags in CI](/config-as-code/ci) # Define flags in code Source: https://docs.useshipd.com/config-as-code/define-flags Define flags in TypeScript or Go and sync them with shipd push. ## Overview Flag definitions live in TypeScript or Go, reviewed in pull requests like any other code. The CLI reads `shipd.config.ts` or `shipd.config.go` directly. In this guide you add a boolean flag and a variant flag, then create both with `shipd push`. **Prerequisites** * The shared `@shipdit/cli` installed (`npm install -g @shipdit/cli`), with Node.js 22.12+ to run it. TypeScript projects also install `shipdit`; Go definitions use `github.com/alasti-company/shipd-go/config`; install the [Go SDK](/sdks/go) when evaluating flags. * `shipd login` completed, or a service account token in `SHIPD_API_KEY`. See [Push permissions](/reference/cli#permissions). ## Define the flags For TypeScript, create `shipd.config.ts` in the project root. For Go, create `shipd.config.go` in your module. The CLI finds its config by walking up from the current directory. ```ts TypeScript theme={null} // shipd.config.ts import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, description: "Redesigned checkout flow", tags: ["checkout"], }, "search-variant": { type: "variant", variants: ["control", "semantic", "hybrid"] as const, default: "control", description: "Search ranking experiment", }, }); ``` ```go Go theme={null} // shipd.config.go package main import "github.com/alasti-company/shipd-go/config" var Config = config.ShipdConfig{ "new-checkout": {Type: "boolean", Default: false, Description: "Redesigned checkout flow", Tags: []string{"checkout"}}, "search-variant": {Type: "variant", Default: "control", Variants: []string{"control", "semantic", "hybrid"}}, } ``` * The object key is the flag key your code reads. * `default` is what the environment you push to serves until you add rules. * In TypeScript, write `variants` with `as const`; invalid defaults fail type checking. Go validates defaults when you call `Config.Validate`, or `Config.Defaults`. Number and JSON flags use the same shape. See [Number and JSON flags](/flags/number-and-json). ## Go definitions Flag definitions use the `config` package, which ships with the Go SDK: ```bash theme={null} go get github.com/alasti-company/shipd-go ``` The CLI reads `shipd.config.go` directly and generates Go accessors by default, unless `typesLanguage` overrides the output language. Define an exported `var Config = config.ShipdConfig{...}` in a self-contained Go file inside your module. The CLI evaluates that file with Go; imported packages and helper declarations in the same file are supported. It does not load sibling Go files, so keep application dependencies in imported packages. Use the same package name as other Go files in its directory; `package main` above assumes that directory is an application package. Do not define `main` in the definition file. `shipd pull` rewrites the Go definitions and regenerates accessors; review the resulting diff because comments and helper code are replaced. ## Push ```bash theme={null} shipd push --env development ``` ```text Output theme={null} Plan: + create flag "new-checkout" + create flag "search-variant" Note: definition changes (type, variants, tags, lifecycle, description, clientAvailable) apply to all environments. Note: definition/ownership changes apply to all environments (requires production permission). Apply this plan? [y/N] y Applied 2 change(s). Wrote types for 2 flag(s) to /home/dev/web-app/src/generated/flags.ts ``` ## What push did * **Created both flags** in the project. Definitions (type, variants, description, tags) are shared by every environment. * **Enabled them in `development`**, the environment you pushed to, serving their `default`. Other environments get the flags disabled until you configure them in the dashboard or push to them. * **Wrote types** to `src/generated/flags.ts`, for TypeScript; Go projects configured above get `internal/flags/flags_gen.go` with per-flag accessors. See [Generate flag types](/config-as-code/types). Push never deletes flags that are on the server but missing from the file. The full rules, including `--prune`, conflicts, and approvals, are in [`shipd push`](/reference/cli#shipd-push). ## Next steps > [card] [Evaluate the flag](/flags/boolean) > > Read `new-checkout` in your app. > [card] [Push, pull, and diff](/config-as-code/sync) > > The everyday edit, diff, push loop. > [card] [Generate flag types](/config-as-code/types) > > Use TypeScript types or generated Go accessors. > [card] [Sync flags in CI](/config-as-code/ci) > > Diff on pull requests, push on merge. Reference: [`defineFlags` and config files](/reference/config) · [CLI](/reference/cli) ## Define targeting rules Add an optional `targeting` block and `traits` contract to a flag. Run `shipd diff`, review rule order and fallthrough, then `shipd push`. Pull dashboard changes with `shipd pull` and review the generated source before committing. See the complete [TypeScript and Go examples](/reference/config#targeting-in-code) and [sync conflict rules](/reference/cli#targeting-sync). # Push, pull, and diff Source: https://docs.useshipd.com/config-as-code/sync Keep shipd.config.ts and the server in sync with shipd diff, shipd push, and shipd pull. ## Overview Three commands keep the local flag config (`shipd.config.ts` or `shipd.config.go`) and the server in sync. `shipd diff` shows what differs, `shipd push` makes the server match the file, and `shipd pull` makes the file match the server. There is no lockfile: the server is the source you compare against, and version checks stop you from overwriting someone else's change. | Command | Direction | Changes | Reference | | - | - | - | - | | `shipd diff` | compare | nothing | [`shipd diff`](/reference/cli#shipd-diff) | | `shipd push` | file → server | flags on the server, then TypeScript types or Go accessors | [`shipd push`](/reference/cli#shipd-push) | | `shipd pull` | server → file | the selected TypeScript, Go, or JSON config and generated TypeScript types or Go accessors | [`shipd pull`](/reference/cli#shipd-pull) | Each command works on one project and one environment: the ones your credential is bound to, or the ones you pass with `--project` and `--env`. ## Go definitions The CLI reads [`shipd.config.go`](/config-as-code/define-flags#go-definitions) directly. Push and pull generate Go accessors by default for Go input, unless `typesLanguage` overrides the output language. Pull writes the current server definitions back to the Go file. ## The everyday loop **1. Edit the file** ```ts TypeScript theme={null} // shipd.config.ts "max-retries": { type: "number", default: 5, // was 3 description: "Max retries for outbound API calls", }, ``` ```go Go theme={null} // Entry inside config.ShipdConfig (import github.com/alasti-company/shipd-go/config). "max-retries": {Type: "number", Default: 5, // Was 3. Description: "Max retries for outbound API calls"}, ``` **2. Diff** ```bash theme={null} shipd diff --env staging ``` ```text Output theme={null} Plan: ~ update flag "max-retries" default: 3 -> 5 ``` Every line should be a change you made. A `default:` line you did not expect usually means someone changed that environment's fallthrough in the dashboard. Pull before you push, or your push reverts it. **3. Push** ```bash theme={null} shipd push --env staging ``` Confirm the plan. Push applies it and regenerates types. **4. Commit** Commit definitions and generated output together. For Go, include the Go definitions and generated accessors. `default` belongs to the environment you push to. Descriptions, tags, types, and variants are shared by every environment. See [Field scope](/reference/cli#field-scope). ## Pull Use `shipd pull` to start from what is live, for example after a teammate edited flags in the dashboard or to resolve a [conflict](/config-as-code/conflicts). ```bash theme={null} shipd pull --env staging ``` > [!WARNING] > > `shipd pull` rewrites the selected TypeScript, Go, or JSON config from scratch. Comments, formatting, and helper code are lost. Commit or stash the file first, then re-apply anything you need from `git diff`. Each flag's `default` comes from the fallthrough of the environment you pull from, so pulling from `staging` and `production` can give different files. ## Flags missing from the file A flag that is on the server but not in `shipd.config.ts` is left alone. `shipd push` warns about it, and `shipd diff` lists it as `- archive flag`. To archive those flags, pass `--prune` on purpose: ```bash theme={null} shipd diff --env staging # read every "- archive flag" line shipd push --prune --env staging ``` `--prune` archives every server flag missing from the file, including flags created in the dashboard and demo flags in a new project. Never add `--prune` to a script you have not diffed. ## Next steps * [Generate flag types](/config-as-code/types) * [Sync flags in CI](/config-as-code/ci) * [Why did shipd push return a conflict?](/config-as-code/conflicts) # Generate flag types Source: https://docs.useshipd.com/config-as-code/types Generate TypeScript flag types or Go accessors and variant constants. ## Overview The CLI generates TypeScript types or Go accessors from the local flag config. TypeScript output defaults to `src/generated/flags.ts`. Pass its `FlagDefinitions` type to the SDK and flag keys, variant names, and value types are checked at compile time. A misspelled key fails the build instead of silently serving a default. ## Generated output ```ts TypeScript theme={null} // src/generated/flags.ts /* eslint-disable */ /* This file is generated by shipd types gen. Do not edit. */ export interface FlagDefinitions { "new-checkout": { type: "boolean"; default: false; }; "search-variant": { type: "variant"; variants: "control" | "semantic" | "hybrid"; default: "control"; }; "max-retries": { type: "number"; default: 3; }; "checkout-payload": { type: "json"; default: {"mode":"strict","showPromo":true}; }; } export type FlagKey = keyof FlagDefinitions; export type BooleanFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "boolean" ? K : never; }[FlagKey]; export type VariantFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "variant" ? K : never; }[FlagKey]; export type NumberFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "number" ? K : never; }[FlagKey]; export type JsonFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "json" ? K : never; }[FlagKey]; ``` ```go Go theme={null} // internal/flags/flags_gen.go // Code generated by shipd types gen --language go; DO NOT EDIT. package flags import ( "encoding/json" shipd "github.com/alasti-company/shipd-go" ) // Defaults returns a fresh map of the config's defaults for shipd.Options. func Defaults() map[string]any { var defaults map[string]any _ = json.Unmarshal([]byte("{\"checkout-payload\":{\"mode\":\"strict\",\"showPromo\":true},\"max-retries\":3,\"new-checkout\":false,\"search-variant\":\"control\"}"), &defaults) return defaults } const CheckoutPayloadKey = "checkout-payload" func CheckoutPayload(client *shipd.Client, context shipd.EvaluationContext) any { return client.GetJSON(CheckoutPayloadKey, context) } const MaxRetriesKey = "max-retries" func MaxRetries(client *shipd.Client, context shipd.EvaluationContext) float64 { return client.GetNumber(MaxRetriesKey, context) } const NewCheckoutKey = "new-checkout" func NewCheckout(client *shipd.Client, context shipd.EvaluationContext) bool { return client.IsEnabled(NewCheckoutKey, context) } const SearchVariantKey = "search-variant" type SearchVariantVariant string const SearchVariantControl SearchVariantVariant = "control" const SearchVariantSemantic SearchVariantVariant = "semantic" const SearchVariantHybrid SearchVariantVariant = "hybrid" func SearchVariant(client *shipd.Client, context shipd.EvaluationContext) SearchVariantVariant { return SearchVariantVariant(client.GetVariant(SearchVariantKey, context)) } ``` The exact shape is in [Generated types](/reference/config#generated-types). ## When it is written | Command | Writes types | | - | - | | `shipd push` | After a successful apply. Not when there is nothing to push. | | `shipd pull` | Always, after rewriting the selected flag config. | | `shipd types gen` | Always. Reads only the local file; no network or credential needed. | Types always come from the local flag config, never from the server. To write somewhere else, set `typesOut` in [`.shipd/config.json`](/reference/config#project-settings-file): ```json TypeScript theme={null} { "typesOut": "src/lib/shipd-flags.ts" } ``` ```json Go theme={null} { "typesLanguage": "go", "typesOut": "internal/flags/flags_gen.go", "typesPackage": "flags" } ``` ## Commit it Commit `src/generated/flags.ts` alongside `shipd.config.ts`. Your app then type-checks on a fresh clone and in CI without running the CLI first, and pull requests show type changes next to flag changes. * Never edit it by hand. The next push, pull, or `shipd types gen` overwrites it. * If it drifts from `shipd.config.ts`, run `shipd types gen` and commit the result. * To catch drift in CI, run `shipd types gen` and fail on `git diff --exit-code src/generated/flags.ts`. ## Use generated output with the SDK Pass `FlagDefinitions` as the TypeScript client type argument, or import your module's generated Go `flags` package. ```ts TypeScript theme={null} // src/flags.ts import { createClient } from "shipdit"; import type { FlagDefinitions } from "./generated/flags"; export const shipd = createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, defaults: { "new-checkout": false, "search-variant": "control" }, }); ``` ```go Go theme={null} // Import your module's internal/flags package as flags. client, err := shipd.New(shipd.Options{ SDKKey: os.Getenv("SHIPD_SDK_KEY"), Defaults: flags.Defaults(), }) if err != nil { return err } defer func() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if err := client.Shutdown(ctx); err != nil { log.Printf("shipd events: %v", err) } }() user := shipd.EvaluationContext{UserID: "usr_8f2k19"} if flags.NewCheckout(client, user) { // Serve the new checkout. } if flags.SearchVariant(client, user) == flags.SearchVariantSemantic { // Use semantic search. } retries := flags.MaxRetries(client, user) // float64 payload := flags.CheckoutPayload(client, user) // any; validate its shape _ = retries _ = payload ``` For React, create the typed bindings once: ```ts src/flags.ts (React) theme={null} "use client"; import { createShipdReact } from "shipdit/client/react"; import type { FlagDefinitions } from "./generated/flags"; export const { ShipdProvider, useFlag, useVariant } = createShipdReact(); ``` Without the type argument, any string is accepted as a key. ## Go output ```bash theme={null} shipd types gen --language go --package flags --out internal/flags/flags_gen.go ``` Set `typesLanguage: "go"` and `typesPackage: "flags"` in [project settings](/reference/config#project-settings-file) to generate Go after push and pull too. Go output defaults to `internal/flags/flags_gen.go`. The Go output above uses the four flags from the [Go tutorial](/examples/go). The generator creates one accessor per flag, its key constant, a `Defaults()` function, and named string types and constants for variants. Misspelled accessor names and incompatible return types fail compilation. Go variant types are named strings, so Go still permits explicit conversions from arbitrary strings; they are not closed unions. JSON stays `any` because the served payload can change shape. Flag keys become exported Go names (`new-checkout` → `NewCheckout`). Identifier collisions such as `new-checkout` and `new_checkout`, including collisions with generated variant constants, fail generation with a validation error. Rename the conflicting flag or variant. Commit `internal/flags/flags_gen.go` alongside the config. Check drift with: ```bash theme={null} shipd types gen --language go git diff --exit-code internal/flags/flags_gen.go ``` ## What a mistake looks like ```ts TypeScript theme={null} // src/checkout.ts if (shipd.isEnabled("new-chekout")) { // ... } ``` ```go Go theme={null} // checkout.go if flags.NewChekout(client, shipd.EvaluationContext{}) { // ... } // Compile error: undefined: flags.NewChekout ``` ```text Output theme={null} src/checkout.ts:1:21 - error TS2345: Argument of type '"new-chekout"' is not assignable to parameter of type '"new-checkout"'. ``` The same check catches reading a flag with the wrong method (`shipd.isEnabled("search-variant")`) and comparing against a variant that does not exist (`shipd.getVariant("search-variant") === "v3"`). ## Next steps * [Sync flags in CI](/config-as-code/ci) * [Node SDK](/sdks/node) · [Go SDK](/sdks/go) · [React](/sdks/react) * [SDK reference](/reference/sdk) # Core concepts Source: https://docs.useshipd.com/core-concepts The shipd mental model in five minutes: organizations, projects, environments, flags, snapshots, and local evaluation. ## Overview This page connects the pieces you'll see across the docs. If you remember one thing: **you define flags in code, choose code-owned or dashboard-owned targeting per environment, and evaluate them in memory.** ## Where things live ```text theme={null} Organization fieldkit └── Project web-app ← flags are defined here, once ├── Environment development ← each environment has its own ├── Environment staging enabled state, rules, fallthrough, └── Environment production SDK keys, and snapshot └── Snapshot v42 ← everything the SDK needs to evaluate ``` | Thing | What it is | Scope | | - | - | - | | **Organization** | Your company account. Members, roles, billing, SSO. | Top level | | **Project** | One product or codebase. Owns one flag config (TypeScript, Go, or JSON). | Organization | | **Environment** | A deployment target such as `development`, `staging`, or `production`. At most one is marked production. | Project | | **Flag definition** | Key, type, variants, description, tags. Written in TypeScript or Go, or directly in JSON. | Project (same in every environment) | | **Flag state** | Enabled or not, targeting rules, fallthrough. Declared in an optional targeting block, or edited in the dashboard when targeting is omitted. | Environment | | **Snapshot** | A JSON document with every flag's state for one environment. | Environment | | **SDK key** | Lets an app download one environment's snapshot. | Environment | ## How a flag gets to your app Go uses the same flow with `shipd.config.go`, read directly by the CLI. Version-1 JSON configs are also supported. See [Go definitions](/config-as-code/define-flags#go-definitions). ```text theme={null} shipd.config.ts you write flag definitions │ ▼ shipd push the CLI syncs definitions │ ▼ Control plane stores definitions + state (dashboard edits land here too) │ publishes on every change ▼ Snapshot one JSON document per environment │ ▼ Edge (CDN) serves the snapshot to SDKs, notifies them of changes │ ▼ SDK in your app keeps the snapshot in memory │ ▼ shipd.isEnabled(…) evaluated locally — no network call ``` 1. **Define.** TypeScript or Go definitions declare which flags exist and their types; The CLI reads Go definitions directly. It's reviewed in pull requests like any other code. 2. **Sync.** `shipd push` compares the file with shipd and applies the difference. It also writes TypeScript types or Go accessors for your flags. 3. **Control.** An explicit `targeting` block owns enabled state, rules, and fallthrough for the selected environment. Omit it to manage that environment in the dashboard. 4. **Publish.** Every change produces a new snapshot version for the affected environment. 5. **Deliver.** The SDK downloads the snapshot at startup, then refreshes it every 30 seconds, or on a WebSocket notification in TypeScript streaming clients. 6. **Evaluate.** TypeScript's `isEnabled`, `getVariant`, `getNumber`, and `getJson`, and Go's `IsEnabled`, `GetVariant`, `GetNumber`, and `GetJSON`, read the in-memory snapshot and never throw. See [SDK benchmarks](/reference/benchmarks) for measured boolean evaluation latency and throughput. ## How a value is chosen For each check, the SDK walks this list and stops at the first match: ```text theme={null} No snapshot yet? → your code's defaults[key] Flag not in snapshot? → your code's defaults[key] Flag disabled here? → the snapshot's default, which shipd derives from the fallthrough; rules are skipped Rule matches the context? → that rule's serve (rules are checked top to bottom) Otherwise → the fallthrough ``` The **fallthrough** is what an environment serves when no rule matches. `shipd push` sets the fallthrough of the environment you push to from the flag's `default` in your flag definitions, and resets it if the two differ. Push each environment separately; `targeting.environments` supplies code overrides, and environments without code ownership remain editable in the dashboard. > [!WARNING] > > Disabling a flag does not turn it off. It skips targeting rules and serves the fallthrough. To turn a feature off, set **Fallthrough** to `false`. See [Turn a feature off immediately](/flags/kill-switch). The **evaluation context** is who is asking: a `userId` plus `attributes` such as `plan` or `country`. Rules match on it. Percentage rollouts hash the flag key and `userId`, so the same user always gets the same answer. ```ts TypeScript theme={null} shipd.isEnabled("new-checkout", { userId: "usr_8f2k19", attributes: { plan: "pro", country: "US" }, }); ``` ```go Go theme={null} client.IsEnabled("new-checkout", shipd.EvaluationContext{ UserID: "usr_8f2k19", Attributes: map[string]any{"plan": "pro", "country": "US"}, }) ``` ## Two kinds of credentials | You're doing… | Use | Prefix | | - | - | - | | Evaluating flags in an app | SDK key (server or client) | `shipd_sdk_server_…`, `shipd_sdk_client_…` | | Running `shipd push` locally | Management API key (created by `shipd login`) | `shipd_mgmt_…` | | Running `shipd push` in CI | Service account token | `shipd_sa_…` | SDK keys only read snapshots. The others only change configuration. Neither works in place of the other. See [Keys and tokens](/concepts/keys). ## What this means in practice * **Your app doesn't wait on shipd.** Flag checks are in memory. If shipd is down, the SDK keeps the last snapshot it had, or serves your `defaults`. * **Code owns definitions and any explicit targeting.** Add or change flag definitions and run `shipd push`. Include `targeting` to control the selected environment from code, or omit it to use the dashboard. To archive a flag, remove its definition and run `shipd push --prune` after reviewing the plan. * **Environments share definitions, not state.** Adding a flag adds it everywhere. Turning it on in `staging` doesn't touch `production`. * **Always pass `defaults`.** They are what your users get before the first snapshot arrives and whenever shipd can't be reached. ## Go deeper * [Architecture](/concepts/architecture): control plane, data plane, and realtime updates * [Local evaluation](/concepts/local-evaluation): the hot path and failure modes * [Environments](/concepts/environments): production protection and per-environment state * [Snapshots](/concepts/snapshots): the document the SDK evaluates * [Glossary](/reference/glossary): every term, defined once # Organizations and access control Source: https://docs.useshipd.com/enterprise/access-control Organization roles, teams, project access, production safeguards, and credential authority. ## Overview Every user has one organization role: owner, admin, editor, or viewer. Teams restrict which projects editors and viewers can see. Direct project memberships and team assignments can grant a project-specific viewer or editor role. An unassigned project is organization-wide. ## Role permissions | Capability | Viewer | Editor | Admin | Owner | | - | - | - | - | - | | Read accessible projects, environments, flags, members, billing, and approvals | Yes | Yes | Yes | Yes | | Create/update/archive flags; change non-production state | No | Yes | Yes | Yes | | Change production state; update flag definitions when the project has a production environment | No | No | Yes | Yes | | Create/archive projects and environments; assign teams | No | No | Yes | Yes | | Manage members, teams, approval policies, SSO providers, and service accounts | No | No | Yes | Yes | | Read audit log and snapshot operations | No | No | Yes | Yes | | Manage billing | No | No | Yes | Yes | | Enforce SSO or delete the organization | No | No | No | Yes | Owners are the SSO break-glass role and remain exempt from enforcement. A role grants capability, while project/team scope decides where that capability applies. ## Role precedence Project permissions use this precedence: 1. Organization owners and admins retain their full authority on every project. 2. A direct project role overrides inherited team roles and the organization viewer/editor role. A direct viewer role can restrict an organization editor on that project. 3. Without a direct role, the strongest role from your assigned teams applies: editor outranks viewer. Existing team assignments without an explicit project role inherit your organization role. 4. Without team restrictions or a direct role, your organization role applies. A restricted project with no matching team or direct membership denies access. Project roles grant permissions only within that project. They cannot grant organization administration, production changes, or the ability to assign teams or project memberships. ## Teams and project scope On Teams and Enterprise plans, admins and owners can manage team assignments and direct memberships through the control-plane API: * `project/setMember`: set a viewer/editor role using the organization membership ID; pass `role: null` to remove the direct grant. * `project/listMembers`: list direct project memberships. * `project/setTeamRole`: set a viewer/editor role on an existing project-team assignment. * `project/access`: read your effective project role, its winning source, and all contributing organization, direct, and team sources. Removing team membership immediately removes that team's contribution. Other direct or inherited grants still apply. Removing organization membership revokes all project access and deletes direct grants; rejoining does not restore those grants. Project transfers discard source-organization direct grants and team assignments. ## Credentials and precedence Authorization never combines credentials. A session, management key, service-account token, or SDK key is evaluated as its own principal. * Management keys are bound to one organization, project, and environment. They support compatible project workflows but cannot administer organization-wide keys, billing, members, teams, SSO, service accounts, audit, or snapshot-wide reads. * Service-account tokens use only their declared scopes and optional project/environment bindings. Token scopes must be a subset of the creator's role at creation time. * SDK keys access the data plane only. Server keys download full environment snapshots for local evaluation, while client keys evaluate only `clientAvailable: true` flags at the edge via `POST /sdk/v1/evaluate` and never receive snapshots, targeting rules, or audiences. Never ship a server key to a browser or mobile app, and never treat a flag as a substitute for backend authorization. See [SDK keys, management API keys, and service account tokens](/concepts/keys) and [Client vs. server evaluation](/concepts/client-vs-server). * Environment and project bindings narrow authority. They never add permission or team membership. ## Production safeguards Production state changes require `flag.production.toggle` (admin or owner). Definition changes also require that permission when the project has a production environment because they affect every environment. Flag creation requires `flag.create` and does not require the production permission. Matching approval policies queue environment changes for review; they do not grant missing RBAC permission. Conflict checks still apply after approval. Related: [Create a service account](/enterprise/service-accounts) · [Review production changes](/operations/approvals) · [Approval workflows](/reference/approvals). # Data isolation tiers Source: https://docs.useshipd.com/enterprise/isolation-tiers Standard, dedicated-schema, and dedicated-database placement boundaries and limitations. ## Overview Standard organizations share the control-plane database schema and data-plane namespace. Contracted Enterprise organizations can be operator-provisioned into a dedicated Postgres schema or database. Dedicated placement is not self-service. | Tier | Tenant data | Data plane | Region | | - | - | - | - | | Standard | Shared public schema | Shared KV namespace | Service default | | Dedicated schema | Organization schema on a shared cluster | Organization namespace | Shared cluster region | | Dedicated database | Organization database | Organization namespace | Contracted database region | Authentication, entitlement, usage, SSO, SCIM, heartbeat, and placement control records remain in the shared control plane for every tier. Cloudflare KV cannot currently be pinned to one jurisdiction, and regional compute routing is not offered. Do not interpret database placement as end-to-end data residency. During a placement migration, tenant operations fail closed with `503 tenant_migrating` or `503 tenant_unavailable`; clients continue using their last good snapshot. Point-in-time recovery and database row-level security are not part of the current isolation guarantee. Backup retention beyond the standard policy must be explicitly contracted and verified as deployed. Contact support ([hey@useshipd.com](mailto:hey@useshipd.com)) for provisioning, migration scheduling, current restore objectives, and evidence for your contracted placement. Related: [Reliability and data handling](/reference/reliability-and-data) · [Local evaluation](/concepts/local-evaluation). # Enterprise administration Source: https://docs.useshipd.com/enterprise/overview A map of shipd security, governance, provisioning, and isolation features. ## Overview Enterprise adds governance features around the same config-as-code and local-evaluation workflow. Availability is controlled by organization entitlements; a page appearing in documentation does not mean it is enabled for every plan or deployment. | Need | Start here | | - | - | | Roles, teams, and production permissions | [Organizations and access control](/enterprise/access-control) | | Change review | [Review production changes](/operations/approvals) | | Workforce authentication | [Connect organization single sign-on](/enterprise/sso) | | Directory provisioning | [Provision members with SCIM](/enterprise/scim) | | Automation identities and rotation | [Create a service account](/enterprise/service-accounts) | | Which credential to use where | [SDK keys, management API keys, and service account tokens](/concepts/keys) | | Compliance history and export | [View the audit log](/operations/audit-log) | | Limits and metering | [Usage and limits](/reference/usage-and-limits) | | Contracted placement | [Data isolation tiers](/enterprise/isolation-tiers) | | Recovery, access, and deletion expectations | [Reliability and data handling](/reference/reliability-and-data) | Dedicated placement, custom retention, and residency are contract- and deployment-specific. Confirm their active state with support before relying on them for compliance. # Provision members with SCIM Source: https://docs.useshipd.com/enterprise/scim Connect Okta or Entra ID so your directory adds and removes shipd organization members. ## Overview In this guide you connect Okta or Entra ID to shipd over SCIM 2.0 (System for Cross-domain Identity Management), so your directory adds people to the organization and removes them when they leave. **Prerequisites:** an Enterprise plan with SCIM enabled, the `sso.manage` permission (admin or owner), and at least one enabled, domain-verified [SSO provider](/enterprise/sso). ## Why SCIM and SSO SSO proves who someone is. SCIM decides whether they belong to your shipd organization. | | SSO only | SSO + SCIM | | - | - | - | | Membership created | When the person first signs in (JIT) | When the directory assigns the shipd app | | Person leaves | Membership stays until an admin removes it | Deactivating them in the directory removes the membership and ends their sessions | | Unassigned person with a work email | Can join by signing in | Cannot join; SSO does not JIT-join anyone the directory has not provisioned | ## Connect your directory **1. Copy the tenant URL** Open **Settings → Security → Directory (SCIM)** and copy **Tenant URL**. It ends in `/api/v1/auth/scim/v2`. **2. Generate a token** Click **Generate SCIM token**. Copy the token now; shipd shows it once. **3. Configure the identity provider** Create a SCIM 2.0 app in your identity provider, or turn on provisioning for your existing shipd SSO app. Authenticate with the bearer token and map `externalId` to the identity-provider subject, so a later SSO sign-in matches the same person. ```text Okta theme={null} SCIM connector base URL: {tenant URL} Authentication: HTTP Header Authorization: Bearer {token} Unique identifier: externalId ← Okta user id ``` ```text Entra theme={null} Tenant URL: {tenant URL} Secret token: {token} Unique user mapping: externalId ← oid ``` **4. Push users and groups** Assign people to the app and start provisioning. If you assign through groups, push groups too. Send ordinary User and Group requests; `/Bulk` is not supported, and each request body must be under 1 MiB. ## Map groups to teams After pushing groups, open **Settings → Security → Directory (SCIM) → Group to team mappings**. Select the existing organization teams each group should populate. Changes save immediately and synchronize current members. Create teams before mapping them; SCIM does not create teams. See [Group to team mappings](/reference/scim#group-to-team-mappings) for membership and removal rules. ## What the directory controls Assigning a user creates a SCIM-owned `viewer` membership. Deactivating or removing them removes that membership and ends their sessions. Memberships created manually, or whose role an admin changed, are never deleted by SCIM. Groups populate teams only when you explicitly map them; they do not grant organization roles. The full rules are in [SCIM provisioning](/reference/scim#membership). Owners stay for recovery and must be removed or transferred explicitly. See [Enterprise identity](/reference/enterprise-identity#offboarding). ## Rotate, revoke, or decommission Rotate, revoke, or decommission the connection from **Settings → Security → Directory (SCIM)**. These controls stay available after a plan downgrade or an SSO provider problem. See [SCIM provisioning](/reference/scim#lifecycle). Related: [SCIM provisioning](/reference/scim) · [Connect organization single sign-on](/enterprise/sso) · [Organizations and access control](/enterprise/access-control). # Create a service account Source: https://docs.useshipd.com/enterprise/service-accounts Mint a scoped shipd_sa_ token for CI instead of a personal management key. ## Overview A service account is a non-human identity for CI and integrations. Tokens start with `shipd_sa_` and support explicit scopes, project or environment bindings, expiry, and revocation. The dashboard shows each token once. Prefer this over a personal management key (`shipd_mgmt_`) for GitHub Actions and other integrations. ## Steps **1. Create the account** Dashboard → **Settings → Service accounts** → **Create service account**. Name it after the job, e.g. `github-actions`. **2. Mint a token** Open the account. **Create token**. Pick the smallest scopes the job needs. Every `shipd push` needs `flag:update`; add `flag:create` for additions, `flag:archive` with `--prune`, `flag_state:update` for non-production default-only changes, and `flag_production:toggle` for production, definition changes, or additions. Bind it to `web-app` at the project level when the job creates or changes flag definitions. Environment-bound tokens are for environment-only reads and state operations. Optionally set an expiry. **3. Use it in CI** ```bash theme={null} SHIPD_API_KEY=shipd_sa_… shipd push --yes --project web-app --env production ``` If the token is org-wide (no project/environment binding), `--project` and `--env` are required. For Terraform, create the bootstrap account and token in the dashboard before using CI to register workload tokens. [Manage credentials from CI](/reference/terraform#manage-credentials-from-ci). Disable the account to invalidate every token at once. Revoke a single token when one pipeline is compromised. An approval policy may accept a default change but queue it for review. The CLI returns exit code `5` and reports the queued request instead of claiming that change is live. See [Review production changes](/operations/approvals). Related: [Service account tokens](/reference/service-account-tokens) · [Sync flags in CI](/config-as-code/ci) · [SDK keys, management API keys, and service account tokens](/concepts/keys). # Connect organization single sign-on Source: https://docs.useshipd.com/enterprise/sso Set up OIDC, verify your domain, and test owner recovery before enforcement. ## Overview Single sign-on (SSO) lets your organization's members authenticate through their identity provider. shipd supports OpenID Connect (OIDC). SAML is not available. ## Connect and test **1. Keep an independent owner login** Set a password or register a passkey for your owner account. If you use two-factor authentication, save backup codes offline and test recovery in a private browser. **2. Configure OIDC** Open **Settings → Security** and add your issuer, client ID, client secret, and work domains. Register the exact callback URI shown by shipd in the provider. Use separate provider applications for staging and production. PKCE is required. **3. Verify your domain** Publish the supplied DNS TXT record and run verification. Unverified connections cannot route or authenticate users. Select a provider explicitly if your organization has several connections. **4. Test before enforcing** Sign in through the provider as the owner and a regular member. Then enable enforced SSO. Members must reauthenticate through your organization provider; owners retain the independent recovery login. ## Recover from a provider outage Sign in as an owner using your password or passkey, complete shipd two-factor authentication if required, and turn off enforced SSO in **Settings → Security**. Repair and test the connection before enabling enforcement again. Recovery and configuration changes appear in the audit log. Next: [Provision members with SCIM](/enterprise/scim) to let your directory add and remove members. Related: [Enterprise identity](/reference/enterprise-identity) for session, provisioning, and removal rules. # Convex example Source: https://docs.useshipd.com/examples/convex A complete Convex backend that mounts the shipd component and evaluates flags in queries. ## Overview A complete Convex backend that mounts the `@shipdit/convex` component and evaluates `new-checkout` and `search-variant` in an authenticated query. The component stores the snapshot in Convex, so evaluations are reactive and add no network call. ## What's in it * `convex/convex.config.ts` mounts one component instance named `shipd` for one shipd environment. * `convex/lib/shipd.ts` wraps the instance with typed defaults. * `convex/storefront.ts` authorizes the caller, then evaluates both flags for that user. * A signed webhook from shipd triggers a refresh when a snapshot is published. A one-minute poll is the fallback. ```text theme={null} convex-example/ ├── package.json ├── shipd.config.ts └── convex/ ├── convex.config.ts ├── http.ts ├── storefront.ts └── lib/ └── shipd.ts ``` `convex/_generated/` is created by `npx convex dev`. ## Files ```json package.json theme={null} { "name": "convex-example", "private": true, "type": "module", "scripts": { "dev": "convex dev", "deploy": "convex deploy", "flags:diff": "shipd diff", "flags:push": "shipd push" }, "dependencies": { "@shipdit/convex": "^0.2.0", "convex": "^1.44.0" }, "devDependencies": { "@shipdit/cli": "^0.3.2", "shipdit": "^0.3.0", "typescript": "^5.9.0" } } ``` `shipdit` is a dev dependency here because only `shipd.config.ts` imports it. Convex functions use `@shipdit/convex`. ```ts shipd.config.ts theme={null} import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, description: "Redesigned checkout flow", tags: ["checkout"], }, "search-variant": { type: "variant", variants: ["control", "semantic", "hybrid"] as const, default: "control", description: "Search ranking experiment", tags: ["search", "experiment"], }, }); ``` ```ts convex/convex.config.ts theme={null} import shipd from "@shipdit/convex/convex.config.js"; import { defineApp } from "convex/server"; import { v } from "convex/values"; const app = defineApp({ env: { SHIPD_SDK_KEY: v.string(), SHIPD_WEBHOOK_SECRET: v.string(), }, }); // The component serves its webhook at `${httpPrefix}/webhook`. app.use(shipd, { name: "shipd", httpPrefix: "/shipd", env: { SHIPD_SDK_KEY: app.env.SHIPD_SDK_KEY, SHIPD_WEBHOOK_SECRET: app.env.SHIPD_WEBHOOK_SECRET, }, }); export default app; ``` ```ts convex/http.ts theme={null} import { httpRouter } from "convex/server"; // Your own HTTP routes go here. The shipd component registers its webhook route itself. export default httpRouter(); ``` The wrapper takes a flag map with variants as a `readonly` tuple. Keep it in sync with `shipd.config.ts`. ```ts convex/lib/shipd.ts theme={null} import { Shipd } from "@shipdit/convex"; import { components } from "../_generated/api"; type Flags = { "new-checkout": { type: "boolean"; default: false }; "search-variant": { type: "variant"; default: "control"; variants: readonly ["control", "semantic", "hybrid"]; }; }; // Returned before the first snapshot syncs, and for missing or mistyped flags. export const shipd = new Shipd(components.shipd, { "new-checkout": false, "search-variant": "control", }); ``` ```ts convex/storefront.ts theme={null} import { v } from "convex/values"; import { query } from "./_generated/server"; import { shipd } from "./lib/shipd"; export const flags = query({ args: {}, returns: v.object({ newCheckout: v.boolean(), search: v.union(v.literal("control"), v.literal("semantic"), v.literal("hybrid")), }), handler: async (ctx) => { // Component functions cannot see ctx.auth. Authorize here, before evaluating. const identity = await ctx.auth.getUserIdentity(); if (identity === null) { throw new Error("Unauthenticated"); } const context = { userId: identity.subject }; return { newCheckout: await shipd.isEnabled(ctx, "new-checkout", context), search: await shipd.getVariant(ctx, "search-variant", context), }; }, }); ``` ## Run it **1. Push the flags** ```bash theme={null} pnpm install pnpm exec shipd login # approve org → project → environment in the browser pnpm exec shipd push ``` **2. Start Convex** ```bash theme={null} npx convex dev ``` This creates the deployment and generates `components.shipd`. Leave it running. **3. Set environment values** In a second terminal, use a **server** SDK key for the environment you pushed to. Set a placeholder secret for now. ```bash theme={null} npx convex env set SHIPD_SDK_KEY shipd_sdk_server_... npx convex env set SHIPD_WEBHOOK_SECRET replace-after-dashboard-setup ``` **4. Create the webhook destination** In the shipd dashboard, open the project's **Settings → Integrations**. Under **Convex**, choose the environment and enter `https://.convex.site/shipd/webhook`. Click **Create destination**, copy the signing secret, and replace the placeholder: ```bash theme={null} npx convex env set SHIPD_WEBHOOK_SECRET ``` Click **Test delivery**. **5. Call the query** ```bash theme={null} npx convex run storefront:flags --identity '{"subject":"usr_8f2k19"}' # { newCheckout: false, search: "control" } ``` Add a rule to `new-checkout` in the dashboard and click **Save environment**. The webhook refreshes the component and subscribed clients re-render with the new value. ## Adapt it * Mount one named instance per shipd environment (for example `shipdDevelopment` and `shipdProduction`), each with its own SDK key, `httpPrefix`, and webhook secret. * Add attributes to the context (`plan`, `organizationId`) from your own tables after authorization. * Use `shipd.evaluate(ctx, key, context)` to get the reason and snapshot version, and `shipd.getStatus(ctx)` to check sync health. * Call `shipd.syncNow(ctx)` from an authorized action to force a refresh. ## Next * [Convex SDK guide](/sdks/convex) * [SDK keys](/concepts/keys) * [SDK reference](/reference/sdk) # GitHub Actions example Source: https://docs.useshipd.com/examples/github-actions Two complete workflows: preview flag changes on pull requests and push shipd.config.ts on merge to main. ## Overview Two complete GitHub Actions workflows for a repo that owns `shipd.config.ts`. `flags-diff` previews flag changes on every pull request that touches the file. `flags-push` applies them when the change merges to `main`. Each authenticates with its own service account token (`shipd_sa_…`), so pull request jobs can read flags but never change them, and both handle the CLI's exit codes explicitly. ## What's in it * `@shipdit/cli` is a dev dependency, so CI runs the same CLI version as your machine. * `flags-diff.yml` runs `shipd diff --exit-code`, writes the plan to the job summary, and checks that `src/generated/flags.ts` is committed. * `flags-push.yml` runs `shipd push --ci` and turns exit codes into errors or warnings. * Both jobs target project `web-app`, environment `production`. ```text theme={null} web-app/ ├── .github/ │ └── workflows/ │ ├── flags-diff.yml │ └── flags-push.yml ├── package.json ├── pnpm-lock.yaml ├── shipd.config.ts └── src/ └── generated/ └── flags.ts ``` ## Set up the tokens 1. In the dashboard, go to **Settings → Service accounts** and click **Create service account**. Name it `github-actions`. 2. Open the account and click **Create token** twice, binding both to project `web-app` (not to an environment). Scopes match an exact action, so `flag:update` does not grant `flag:read`: | Secret | Used by | Scopes | | - | - | - | | `SHIPD_DIFF_TOKEN` | `flags-diff` (pull requests) | `flag:read`, `environment:read` | | `SHIPD_PUSH_TOKEN` | `flags-push` (main) | `flag:update`, `flag:create`, `flag_state:update`, `flag_production:toggle`, `environment:read` | Add `flag:archive` to the push token only if you push with `--prune`. See [Sync flags in CI](/config-as-code/ci) for the reasoning. 3. Copy each token. They are shown once. 4. In GitHub, go to **Settings → Secrets and variables → Actions** and add both as repository secrets. ## Files ```json package.json theme={null} { "name": "web-app", "private": true, "type": "module", "packageManager": "pnpm@10.15.0", "scripts": { "flags:diff": "shipd diff", "flags:push": "shipd push" }, "dependencies": { "shipdit": "^0.3.0" }, "devDependencies": { "@shipdit/cli": "^0.3.2", "typescript": "^5.9.0" } } ``` `pnpm/action-setup` reads the pnpm version from `packageManager`. ```ts shipd.config.ts theme={null} import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, description: "Redesigned checkout flow", tags: ["checkout"], }, "search-variant": { type: "variant", variants: ["control", "semantic", "hybrid"] as const, default: "control", description: "Search ranking experiment", tags: ["search", "experiment"], }, }); ``` ````yaml .github/workflows/flags-diff.yml theme={null} name: flags-diff on: pull_request: paths: - shipd.config.ts - src/generated/flags.ts permissions: contents: read jobs: diff: runs-on: ubuntu-latest env: SHIPD_API_KEY: ${{ secrets.SHIPD_DIFF_TOKEN }} SHIPD_API_URL: https://api.useshipd.com SHIPD_PROJECT: web-app SHIPD_ENV: production steps: - uses: actions/checkout@v5 - uses: pnpm/action-setup@v4 - uses: actions/setup-node@v5 with: node-version: 22 cache: pnpm - run: pnpm install --frozen-lockfile - name: Check generated types are committed run: | pnpm exec shipd types gen git diff --exit-code -- src/generated/flags.ts \ || { echo "::error title=shipd::src/generated/flags.ts is stale. Run 'shipd types gen' and commit."; exit 1; } - name: Diff against production run: | set +e pnpm exec shipd diff --exit-code > diff.txt 2>&1 code=$? set -e cat diff.txt { echo "### shipd diff (web-app / production)" echo '```text' cat diff.txt echo '```' } >> "$GITHUB_STEP_SUMMARY" case "$code" in 0) echo "No flag changes." ;; 2) echo "::notice title=shipd::This PR changes flags. They apply to production when it merges to main." ;; 4) echo "::error title=shipd::Unlinked flags. See the diff output."; exit 4 ;; *) echo "::error title=shipd::shipd diff failed (exit $code)."; exit "$code" ;; esac ```` ````yaml .github/workflows/flags-push.yml theme={null} name: flags-push on: push: branches: [main] paths: - shipd.config.ts workflow_dispatch: permissions: contents: read # Never run two pushes against the same environment at once. concurrency: group: flags-push-production cancel-in-progress: false jobs: push: runs-on: ubuntu-latest env: SHIPD_API_KEY: ${{ secrets.SHIPD_PUSH_TOKEN }} SHIPD_API_URL: https://api.useshipd.com SHIPD_PROJECT: web-app SHIPD_ENV: production steps: - uses: actions/checkout@v5 - uses: pnpm/action-setup@v4 - uses: actions/setup-node@v5 with: node-version: 22 cache: pnpm - run: pnpm install --frozen-lockfile - name: Push to production run: | set +e pnpm exec shipd push --ci 2>&1 | tee push.txt code=${PIPESTATUS[0]} set -e { echo "### shipd push (web-app / production)" echo '```text' cat push.txt echo '```' } >> "$GITHUB_STEP_SUMMARY" case "$code" in 0) echo "Flags are in sync." ;; 3) echo "::error title=shipd::Conflict. Someone changed these flags since the plan. Run 'shipd pull', reconcile, and merge again."; exit 3 ;; 5) echo "::warning title=shipd::A default change is queued for approval and is not live yet. Approve it in the dashboard." ;; *) echo "::error title=shipd::shipd push failed (exit $code)."; exit "$code" ;; esac ```` ## Exit codes | Code | Command | Meaning | Workflow result | | - | - | - | - | | `0` | both | No changes (`diff`) or applied (`push`) | Pass | | `2` | `diff` | Local definitions differ from the environment. On a PR that edits flags, this is expected | Pass with a notice | | `3` | `push` | Conflict: a flag changed after the plan (stale version), or an approval request is already pending | Fail | | `4` | `diff` | Unlinked flags | Fail | | `5` | `push` | A protected default change is queued for approval. It is not live | Pass with a warning | | `1` | both | Any other error (auth, network, invalid config) | Fail | The full list lives in the [CLI reference](/reference/cli#exit-codes). ## Run it ```bash theme={null} pnpm add -D @shipdit/cli pnpm add shipdit pnpm exec shipd types gen # writes src/generated/flags.ts git add .github package.json pnpm-lock.yaml shipd.config.ts src/generated/flags.ts git commit -m "ci: sync shipd flags" ``` Open a pull request that edits `shipd.config.ts`. The `flags-diff` job summary shows the plan. Merge it and `flags-push` applies the plan to production. ## Adapt it * To block pull requests on any drift, including changes someone made in the dashboard, make exit code `2` fail: replace its `case` line with `exit 2`. * To fail the push job while an approval is pending, make exit code `5` fail the same way. * For more environments, copy the push job and change `SHIPD_ENV`. `default` values apply per environment. Definition fields apply to the whole project. * `SHIPD_API_URL` is required in CI. Only `shipd login` falls back to `https://api.useshipd.com`. You can also set `apiUrl` in `.shipd/config.json`. * Secrets are not passed to workflows triggered from forks, so `flags-diff` fails there. Skip the job for forks with `if: github.event.pull_request.head.repo.full_name == github.repository`. * Use `--prune` only after you confirm that no one manages flags in this project outside `shipd.config.ts`. It archives remote-only flags. ## Next * [Sync flags in CI](/config-as-code/ci) * [CLI reference](/reference/cli) * [Generated types](/config-as-code/types) # Go app Source: https://docs.useshipd.com/examples/go A complete Go app with Go-authored definitions, generated accessors, and local flag evaluation. ## Overview This tutorial defines four flags in Go, loads those definitions directly with the CLI, generates typed accessors, and evaluates flags for one user. You need Go 1.23+, Node.js 22.12+ for the CLI, and a shipd account. For a step-by-step first flag, use the [quickstart](/quickstart). For the equivalent TypeScript application, see the [Node tutorial](/examples/node). ## Create the project ```bash theme={null} mkdir shipd-go-example && cd shipd-go-example go mod init example.com/shipd-quickstart go get github.com/alasti-company/shipd-go npm install -g @shipdit/cli ``` ## Define flags Create `shipd.config.go`: ```go shipd.config.go theme={null} package main import "github.com/alasti-company/shipd-go/config" var Config = config.ShipdConfig{ "new-checkout": {Type: "boolean", Default: false, Description: "Redesigned checkout flow", Tags: []string{"checkout"}}, "search-variant": {Type: "variant", Default: "control", Variants: []string{"control", "semantic", "hybrid"}}, "max-retries": {Type: "number", Default: 3}, "checkout-payload": {Type: "json", Default: map[string]any{"mode": "strict", "showPromo": true}}, } ``` The CLI discovers `shipd.config.go` and selects Go output automatically. ## Push and generate accessors ```bash theme={null} shipd login shipd push shipd types gen ``` The CLI creates the flags in the selected project and environment, then writes `internal/flags/flags_gen.go`. Commit that file with `shipd.config.go`. The generator creates `Defaults()`, `NewCheckout`, `SearchVariant`, `MaxRetries`, and `CheckoutPayload`. ## Read flags Create `main.go`. One client fetches a snapshot, then evaluates every check locally: ```go main.go theme={null} package main import ( "context" "log" "os" "time" "example.com/shipd-quickstart/internal/flags" shipd "github.com/alasti-company/shipd-go" ) func main() { client, err := shipd.New(shipd.Options{ SDKKey: os.Getenv("SHIPD_SDK_KEY"), Defaults: flags.Defaults(), }) if err != nil { log.Fatal(err) } defer func() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() // Shutdown delivers pending events, then closes the client. if err := client.Shutdown(ctx); err != nil { log.Printf("shipd events: %v", err) } }() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) if err := client.Ready(ctx); err != nil { log.Printf("shipd startup: %v; continuing with defaults", err) } cancel() user := shipd.EvaluationContext{UserID: "usr_8f2k19", Attributes: map[string]any{"plan": "pro"}} log.Printf("checkout=%v search=%s retries=%v", flags.NewCheckout(client, user), flags.SearchVariant(client, user), flags.MaxRetries(client, user)) } ``` ## Run Create a **server** SDK key for the same environment in the dashboard, then run: ```bash theme={null} export SHIPD_SDK_KEY=shipd_sdk_server_… go run . ``` The program logs the checkout, search variant, and retry count, then flushes diagnostic events before closing. If the first snapshot cannot load within five seconds, it logs the error and uses the generated defaults. For a long-running service, reuse the client and pass an `EvaluationContext` on each request. Polling refreshes the snapshot every 30 seconds by default. `Identify` queues telemetry; it does not set a global evaluation identity. ## Next * [Go SDK setup](/sdks/go) and [Go reference](/reference/go-sdk) * [Target users](/flags/targeting) * [Sync flags in CI](/config-as-code/ci) # Next.js example Source: https://docs.useshipd.com/examples/nextjs A complete Next.js App Router app that evaluates shipd flags in server components and client hooks. ## Overview A complete Next.js App Router app. A server component evaluates `new-checkout` with a server SDK key. A client component reads `search-variant` with typed React hooks and a client SDK key. ## What's in it * `src/lib/shipd-server.ts` holds one server client per process. `import "server-only"` keeps the server key out of the browser bundle. * `src/lib/shipd-react.ts` binds typed hooks once with `createShipdReact()`. * `src/app/providers.tsx` creates the browser client with `NEXT_PUBLIC_SHIPD_SDK_KEY` and calls `identify` for the signed-in user. * `src/app/page.tsx` evaluates `new-checkout` on the server. `src/components/search-box.tsx` evaluates `search-variant` in the browser. ```text theme={null} nextjs-example/ ├── .env.example ├── next.config.ts ├── package.json ├── shipd.config.ts ├── tsconfig.json └── src/ ├── app/ │ ├── layout.tsx │ ├── page.tsx │ └── providers.tsx ├── components/ │ └── search-box.tsx ├── generated/ │ └── flags.ts └── lib/ ├── session.ts ├── shipd-react.ts └── shipd-server.ts ``` `next.config.ts`, `tsconfig.json`, and `next-env.d.ts` are the `create-next-app` defaults, including the `@/*` → `./src/*` path alias. ## Files ```json package.json theme={null} { "name": "nextjs-example", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "flags:diff": "shipd diff", "flags:push": "shipd push" }, "dependencies": { "next": "^16.0.0", "react": "^19.2.0", "react-dom": "^19.2.0", "server-only": "^0.0.1", "shipdit": "^0.3.0" }, "devDependencies": { "@shipdit/cli": "^0.3.2", "@types/node": "^22.18.0", "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", "typescript": "^5.9.0" } } ``` ```ts shipd.config.ts theme={null} import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, description: "Redesigned checkout flow", tags: ["checkout"], }, "search-variant": { type: "variant", variants: ["control", "semantic", "hybrid"] as const, default: "control", description: "Search ranking experiment", tags: ["search", "experiment"], }, }); ``` ```bash .env.example theme={null} # Server SDK key (server components, route handlers). Never prefix with NEXT_PUBLIC_. SHIPD_SDK_KEY=shipd_sdk_server_... # Client SDK key (browser). Safe to embed. NEXT_PUBLIC_SHIPD_SDK_KEY=shipd_sdk_client_... ``` `shipd push` and `shipd types gen` write this file. Commit it and do not edit it by hand. ```ts src/generated/flags.ts theme={null} /* eslint-disable */ /* This file is generated by shipd types gen. Do not edit. */ export interface FlagDefinitions { "new-checkout": { type: "boolean"; default: false; }; "search-variant": { type: "variant"; variants: "control" | "semantic" | "hybrid"; default: "control"; }; } export type FlagKey = keyof FlagDefinitions; export type BooleanFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "boolean" ? K : never; }[FlagKey]; export type VariantFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "variant" ? K : never; }[FlagKey]; export type NumberFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "number" ? K : never; }[FlagKey]; export type JsonFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "json" ? K : never; }[FlagKey]; ``` ```ts src/lib/shipd-server.ts theme={null} import "server-only"; import { createClient, type ShipdClient } from "shipdit"; import type { FlagDefinitions } from "@/generated/flags"; function createShipd(): ShipdClient { return createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, stream: true, defaults: { "new-checkout": false, "search-variant": "control", }, }); } // Reuse one client across hot reloads in development. const globalForShipd = globalThis as unknown as { shipd?: ShipdClient }; export const shipd = globalForShipd.shipd ?? createShipd(); if (process.env.NODE_ENV !== "production") { globalForShipd.shipd = shipd; } ``` ```ts src/lib/shipd-react.ts theme={null} "use client"; import { createShipdReact } from "shipdit/client/react"; import type { FlagDefinitions } from "@/generated/flags"; export const { ShipdProvider, useFlag, useVariant, useNumber, useJson, useReady, useShipdClient } = createShipdReact(); ``` Replace `getUserId` with your auth library. This example reads a `uid` cookie. ```ts src/lib/session.ts theme={null} import { cookies } from "next/headers"; export async function getUserId(): Promise { const cookieStore = await cookies(); return cookieStore.get("uid")?.value; } ``` ```tsx src/app/providers.tsx theme={null} "use client"; import { useEffect, useRef, type ReactNode } from "react"; import { createClient } from "shipdit/client"; import type { FlagDefinitions } from "@/generated/flags"; import { ShipdProvider } from "@/lib/shipd-react"; const isBrowser = typeof window !== "undefined"; // Module scope: one client per browser tab. Next.js also evaluates this module // once during server rendering, so that copy fetches once and skips polling, // the stream, and events. const client = createClient({ sdkKey: process.env.NEXT_PUBLIC_SHIPD_SDK_KEY!, stream: isBrowser, refreshIntervalMs: isBrowser ? 30_000 : 0, events: isBrowser, defaults: { "new-checkout": false, "search-variant": "control", }, }); export function Providers({ userId, children }: { userId?: string; children: ReactNode }) { const previousUserId = useRef(undefined); useEffect(() => { if (userId) { client.identify({ userId }); } else if (previousUserId.current) { // Signed out: clear the identity and start a new anonymous id. client.reset(); } previousUserId.current = userId; }, [userId]); return {children}; } ``` ```tsx src/app/layout.tsx theme={null} import type { ReactNode } from "react"; import { getUserId } from "@/lib/session"; import { Providers } from "./providers"; export default async function RootLayout({ children }: { children: ReactNode }) { const userId = await getUserId(); return ( {children} ); } ``` ```tsx src/app/page.tsx theme={null} import { SearchBox } from "@/components/search-box"; import { getUserId } from "@/lib/session"; import { shipd } from "@/lib/shipd-server"; export default async function Page() { const userId = await getUserId(); // Resolves after the first snapshot, or after 5s with `defaults`. Never rejects. await shipd.ready(); const newCheckout = shipd.isEnabled("new-checkout", { userId }); return (

Store

{newCheckout ? "Try the new checkout" : "Checkout"}
); } ``` ```tsx src/components/search-box.tsx theme={null} "use client"; import { useReady, useVariant } from "@/lib/shipd-react"; const placeholders = { control: "Search products", semantic: "Describe what you're looking for", hybrid: "Search by name or description", } as const; export function SearchBox() { const ready = useReady(); // "control" | "semantic" | "hybrid" const variant = useVariant("search-variant"); // useReady() is false during server rendering and the first client render, // so the markup matches and hydration succeeds. if (!ready) { return ; } return (
); } ``` ## Run it ```bash theme={null} pnpm install cp .env.example .env.local # paste a server key and a client key pnpm exec shipd login # approve org → project → environment in the browser pnpm exec shipd push # creates the flags and rewrites src/generated/flags.ts pnpm dev ``` Open `http://localhost:3000`. To test targeting, set a `uid` cookie (for example `usr_8f2k19`) in your browser's dev tools. Pushed flags serve their `default`. Add a rule for `new-checkout` in the dashboard, click **Save environment**, and reload. ## Adapt it * Server components are rendered per request. Pass the evaluation context on every call (`{ userId, attributes }`). Don't call `identify` on the shared server client. * Put the browser user's traits in `identify({ userId, traits: { plan } })`. Hooks re-render when context or the snapshot changes. * The browser client adds `country`, `region`, `city`, and `timezone` attributes automatically. The server client does not. If a rule targets location, pass those attributes on the server yourself. * For route handlers and server actions, import `shipd` from `@/lib/shipd-server` in the same way. ## Next * [Next.js SDK guide](/sdks/nextjs) * [React SDK guide](/sdks/react) * [SDK keys](/concepts/keys) * [SDK reference](/reference/sdk) # Node server example Source: https://docs.useshipd.com/examples/node A complete Hono server on Node 22 that evaluates shipd flags per request. ## Overview A complete Node 22 API built with [Hono](https://hono.dev). It creates one shipd client per process, waits for `ready()` before it listens, evaluates `new-checkout` and `search-variant` per request, and closes the client on shutdown. ## What's in it * `shipd.config.ts` defines two flags. `shipd push` syncs them and writes `src/generated/flags.ts`. * `src/lib/shipd.ts` creates a singleton client with a server SDK key (`shipd_sdk_server_…`). * A middleware builds the evaluation context from the `x-user-id` header or the `userId` query parameter. * `SIGINT` / `SIGTERM` stop the HTTP server, then call `shipd.close()`. ```text theme={null} node-example/ ├── .env.example ├── package.json ├── shipd.config.ts ├── tsconfig.json └── src/ ├── generated/ │ └── flags.ts ├── lib/ │ └── shipd.ts └── server.ts ``` ## Files ```json package.json theme={null} { "name": "node-example", "private": true, "type": "module", "engines": { "node": ">=22" }, "scripts": { "dev": "tsx watch --env-file=.env src/server.ts", "start": "tsx --env-file=.env src/server.ts", "check-types": "tsc --noEmit", "flags:diff": "shipd diff", "flags:push": "shipd push" }, "dependencies": { "@hono/node-server": "^1.19.0", "hono": "^4.9.0", "shipdit": "^0.4.0" }, "devDependencies": { "@shipdit/cli": "^0.3.2", "@types/node": "^22.18.0", "tsx": "^4.20.0", "typescript": "^5.9.0" } } ``` ```json tsconfig.json theme={null} { "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler", "strict": true, "skipLibCheck": true, "noEmit": true, "types": ["node"] }, "include": ["shipd.config.ts", "src"] } ``` ```ts shipd.config.ts theme={null} import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, description: "Redesigned checkout flow", tags: ["checkout"], }, "search-variant": { type: "variant", variants: ["control", "semantic", "hybrid"] as const, default: "control", description: "Search ranking experiment", tags: ["search", "experiment"], }, }); ``` ```bash .env.example theme={null} # Server SDK key from the dashboard: project → SDK keys → Create SDK key (Key type: server) SHIPD_SDK_KEY=shipd_sdk_server_... PORT=3000 ``` `shipd push` and `shipd types gen` write this file. Commit it and do not edit it by hand. ```ts src/generated/flags.ts theme={null} /* eslint-disable */ /* This file is generated by shipd types gen. Do not edit. */ export interface FlagDefinitions { "new-checkout": { type: "boolean"; default: false; }; "search-variant": { type: "variant"; variants: "control" | "semantic" | "hybrid"; default: "control"; }; } export type FlagKey = keyof FlagDefinitions; export type BooleanFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "boolean" ? K : never; }[FlagKey]; export type VariantFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "variant" ? K : never; }[FlagKey]; export type NumberFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "number" ? K : never; }[FlagKey]; export type JsonFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "json" ? K : never; }[FlagKey]; ``` ```ts src/lib/shipd.ts theme={null} import { createClient } from "shipdit"; import type { FlagDefinitions } from "../generated/flags"; const sdkKey = process.env.SHIPD_SDK_KEY; if (!sdkKey) { throw new Error("SHIPD_SDK_KEY is not set"); } // One client per process. It downloads the snapshot, keeps it in memory, // and evaluates every flag check locally. export const shipd = createClient({ sdkKey, // Node 22 has a global WebSocket, so realtime invalidation works without extra packages. stream: true, defaults: { "new-checkout": false, "search-variant": "control", }, onError: (error) => { console.error("[shipd]", error); }, }); ``` ```ts src/server.ts theme={null} import { serve } from "@hono/node-server"; import { Hono } from "hono"; import type { EvaluationContext } from "shipdit"; import { shipd } from "./lib/shipd"; type Env = { Variables: { flagContext: EvaluationContext } }; const app = new Hono(); // Build the evaluation context once per request. app.use("*", async (c, next) => { const userId = c.req.header("x-user-id") ?? c.req.query("userId"); const plan = c.req.header("x-plan"); c.set("flagContext", { userId, attributes: plan ? { plan } : {}, }); await next(); }); app.get("/checkout", (c) => { const newCheckout = shipd.isEnabled("new-checkout", c.get("flagContext")); return c.json({ checkout: newCheckout ? "new" : "legacy" }); }); app.get("/search", (c) => { const q = c.req.query("q") ?? ""; // "control" | "semantic" | "hybrid" const engine = shipd.getVariant("search-variant", c.get("flagContext")); return c.json({ q, engine, results: [] }); }); app.get("/healthz", (c) => c.json({ ok: true, snapshotVersion: shipd.getVersion() })); // ready() resolves after the first snapshot or after readyTimeoutMs (5s). // It never rejects for network errors; until a snapshot arrives you get `defaults`. await shipd.ready(); const port = Number(process.env.PORT ?? 3000); const server = serve({ fetch: app.fetch, port }, (info) => { console.log(`Listening on http://localhost:${info.port}`); }); function shutdown(signal: NodeJS.Signals) { console.log(`${signal} received, shutting down`); server.close(() => { // Stops polling and the stream, and flushes queued evaluation events. shipd.close(); }); } process.once("SIGINT", shutdown); process.once("SIGTERM", shutdown); ``` ## Run it ```bash theme={null} pnpm install cp .env.example .env # paste your server SDK key pnpm exec shipd login # approve org → project → environment in the browser pnpm exec shipd push # creates the flags and rewrites src/generated/flags.ts pnpm dev ``` ```bash theme={null} curl -H "x-user-id: usr_8f2k19" http://localhost:3000/checkout # {"checkout":"legacy"} curl "http://localhost:3000/search?q=boots&userId=usr_8f2k19" # {"q":"boots","engine":"control","results":[]} ``` Pushed flags serve their `default`. To see `{"checkout":"new"}`, open `new-checkout` in the dashboard, add a rule or change **Fallthrough** to `true`, and click **Save environment**. The server picks up the new snapshot without a restart. ## Adapt it * Add attributes to the evaluation context from your auth layer (`plan`, `country`, `organizationId`). The server SDK does not infer location. * Percentage rollouts need a `userId`. Requests without one fall through. * On Node 20, pass `WebSocket` from the `ws` package or omit `stream`. Polling still runs every 30 seconds. * Omit `stream` to poll only. Set `refreshIntervalMs: 0` for one fetch per process, for example in short-lived jobs. ## Next * [Node SDK guide](/sdks/node) * [SDK reference](/reference/sdk) * [SDK keys](/concepts/keys) * [Generated types](/config-as-code/types) # React (Vite) example Source: https://docs.useshipd.com/examples/react A complete Vite + React single-page app that reads shipd flags with typed hooks and identifies users after sign-in. ## Overview A complete Vite + React single-page app. It creates one browser client with a client SDK key, reads `new-checkout` and `search-variant` with typed hooks, and calls `identify` after sign-in. ## What's in it * `src/lib/shipd.ts` creates the browser client from `import.meta.env.VITE_SHIPD_SDK_KEY` and binds typed hooks with `createShipdReact()`. * `src/main.tsx` wraps the app in `ShipdProvider`. * `src/App.tsx` signs a user in and out. It calls `identify` on sign-in and `reset` on sign-out, and the hooks re-render. * The browser client evaluates `clientAvailable: true` flags at the edge, keeps resolved values in memory, and persists a stable anonymous id in `localStorage`. ```text theme={null} react-example/ ├── .env.example ├── index.html ├── package.json ├── shipd.config.ts ├── tsconfig.json ├── vite.config.ts └── src/ ├── App.tsx ├── main.tsx ├── vite-env.d.ts ├── components/ │ ├── checkout-button.tsx │ └── search-box.tsx ├── generated/ │ └── flags.ts └── lib/ └── shipd.ts ``` ## Files ```json package.json theme={null} { "name": "react-example", "private": true, "type": "module", "scripts": { "dev": "vite", "build": "tsc --noEmit && vite build", "preview": "vite preview", "flags:diff": "shipd diff", "flags:push": "shipd push" }, "dependencies": { "react": "^19.2.0", "react-dom": "^19.2.0", "shipdit": "^0.4.0" }, "devDependencies": { "@shipdit/cli": "^0.3.2", "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", "@vitejs/plugin-react": "^5.0.0", "typescript": "^5.9.0", "vite": "^7.1.0" } } ``` ```json tsconfig.json theme={null} { "compilerOptions": { "target": "ES2022", "lib": ["ES2022", "DOM", "DOM.Iterable"], "module": "ESNext", "moduleResolution": "Bundler", "jsx": "react-jsx", "strict": true, "skipLibCheck": true, "noEmit": true }, "include": ["src", "shipd.config.ts", "vite.config.ts"] } ``` ```ts vite.config.ts theme={null} import react from "@vitejs/plugin-react"; import { defineConfig } from "vite"; export default defineConfig({ plugins: [react()], }); ``` ```html index.html theme={null} shipd React example
``` ```ts shipd.config.ts theme={null} import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, clientAvailable: true, description: "Redesigned checkout flow", tags: ["checkout"], }, "search-variant": { type: "variant", variants: ["control", "semantic", "hybrid"] as const, default: "control", clientAvailable: true, description: "Search ranking experiment", tags: ["search", "experiment"], }, }); ``` ```bash .env.example theme={null} # Client SDK key (shipd_sdk_client_…). Vite inlines VITE_* values into the bundle. # Never put a server key here. VITE_SHIPD_SDK_KEY=shipd_sdk_client_... ``` ```ts src/vite-env.d.ts theme={null} /// interface ImportMetaEnv { readonly VITE_SHIPD_SDK_KEY: string; } interface ImportMeta { readonly env: ImportMetaEnv; } ``` `shipd push` and `shipd types gen` write this file. Commit it and do not edit it by hand. ```ts src/generated/flags.ts theme={null} /* eslint-disable */ /* This file is generated by shipd types gen. Do not edit. */ export interface FlagDefinitions { "new-checkout": { type: "boolean"; default: false; }; "search-variant": { type: "variant"; variants: "control" | "semantic" | "hybrid"; default: "control"; }; } export type FlagKey = keyof FlagDefinitions; export type BooleanFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "boolean" ? K : never; }[FlagKey]; export type VariantFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "variant" ? K : never; }[FlagKey]; export type NumberFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "number" ? K : never; }[FlagKey]; export type JsonFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "json" ? K : never; }[FlagKey]; ``` ```ts src/lib/shipd.ts theme={null} import { createClient } from "shipdit/client"; import { createShipdReact } from "shipdit/client/react"; import type { FlagDefinitions } from "../generated/flags"; // One client for the whole app. Create it at module scope, not inside a component. export const shipd = createClient({ sdkKey: import.meta.env.VITE_SHIPD_SDK_KEY, stream: true, defaults: { "new-checkout": false, "search-variant": "control", }, }); export const { ShipdProvider, useFlag, useVariant, useNumber, useJson, useReady, useShipdClient } = createShipdReact(); ``` ```tsx src/main.tsx theme={null} import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { App } from "./App"; import { ShipdProvider, shipd } from "./lib/shipd"; createRoot(document.getElementById("root")!).render( , ); ``` Replace `signIn` with your auth library. The important part is calling `identify` with the user's id and traits once you know them. ```tsx src/App.tsx theme={null} import { useState } from "react"; import { CheckoutButton } from "./components/checkout-button"; import { SearchBox } from "./components/search-box"; import { useShipdClient } from "./lib/shipd"; type User = { id: string; name: string; plan: "free" | "pro" }; async function signIn(): Promise { return { id: "usr_8f2k19", name: "Sam Lee", plan: "pro" }; } export function App() { const shipd = useShipdClient(); const [user, setUser] = useState(null); async function handleSignIn() { const next = await signIn(); // Every later evaluation uses this userId and these traits. shipd.identify({ userId: next.id, name: next.name, traits: { plan: next.plan } }); setUser(next); } function handleSignOut() { // Clears the identity and starts a new anonymous id. shipd.reset(); setUser(null); } return (
{user ? ( <> {user.name} ({user.plan}) ) : ( )}
); } ``` ```tsx src/components/checkout-button.tsx theme={null} import { useFlag, useReady } from "../lib/shipd"; export function CheckoutButton() { const ready = useReady(); const newCheckout = useFlag("new-checkout"); // Avoid flashing the old checkout before the first snapshot arrives. if (!ready) return null; return newCheckout ? ( Try the new checkout ) : ( Checkout ); } ``` ```tsx src/components/search-box.tsx theme={null} import { useVariant } from "../lib/shipd"; const placeholders = { control: "Search products", semantic: "Describe what you're looking for", hybrid: "Search by name or description", } as const; export function SearchBox() { // "control" | "semantic" | "hybrid" const variant = useVariant("search-variant"); return (
); } ``` ## Run it ```bash theme={null} pnpm install cp .env.example .env # paste your client SDK key pnpm exec shipd login # approve org → project → environment in the browser pnpm exec shipd push # creates the flags and rewrites src/generated/flags.ts pnpm dev ``` Open `http://localhost:5173`. Pushed flags serve their `default`. In the dashboard, add a rule to `new-checkout` that serves `true` when `plan` equals `pro`, then click **Save environment**. Click **Sign in** and the checkout link switches without a reload. ## Adapt it * Call `identify` wherever your auth state settles (session restore, sign-in callback). Call `reset` on sign-out. * Pass per-component context only for values that aren't about the user, such as `useFlag("new-checkout", { attributes: { cartSize: 3 } })`. Per-call attributes override `identify` traits. * The browser client adds `country`, `region`, `city`, and `timezone` attributes automatically. Pass `automaticTraits: false` to turn that off. * Gate UI with `useReady()` where a flash of the default matters, and list initial keys in `defaults` so the first evaluation request fetches them together. ## Next * [React SDK guide](/sdks/react) * [SDK keys](/concepts/keys) * [SDK reference](/reference/sdk) * [Generated types](/config-as-code/types) # Create a boolean flag Source: https://docs.useshipd.com/flags/boolean Define an on/off flag in TypeScript or Go, push it, evaluate it locally, and turn it on in the dashboard. ## Overview In this guide you add a boolean flag, `new-checkout`, in TypeScript or Go, push it, branch on it in code, and turn it on from the dashboard. You need the `shipd` CLI signed in (`shipd login`) and an SDK client. See the [Quickstart](/quickstart) if you have neither. ## Steps **1. Define the flag** ```ts TypeScript theme={null} // shipd.config.ts import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, description: "Redesigned checkout flow", tags: ["checkout"], }, }); ``` ```go Go theme={null} // Entries inside config.ShipdConfig (import github.com/alasti-company/shipd-go/config). "new-checkout": {Type: "boolean", Default: false, Description: "Redesigned checkout flow", Tags: []string{"checkout"}}, ``` For Go, add definitions to `Config` in `shipd.config.go`, then run `shipd push`. See [Define flags in code](/config-as-code/define-flags#go-definitions) for the complete file. **2. Push it** ```bash theme={null} shipd push --project web-app --env production ``` The flag is created in every environment of the project. In the environment you push to, it is enabled and its **Fallthrough** serves the `default` (`false`). Push also regenerates TypeScript types or Go accessors according to your [project settings](/reference/config#project-settings-file). **3. Evaluate it** ```ts TypeScript theme={null} // src/checkout.ts import { shipd } from "./lib/shipd"; export function renderCheckout(userId: string) { if (shipd.isEnabled("new-checkout", { userId })) { return renderNewCheckout(); } return renderLegacyCheckout(); } ``` ```go Go theme={null} // checkout.go if client.IsEnabled("new-checkout", shipd.EvaluationContext{UserID: userID}) { return renderNewCheckout() } return renderLegacyCheckout() ``` In React: ```tsx src/components/checkout.tsx theme={null} const on = useFlag("new-checkout"); ``` Pass `"new-checkout": false` in the client's `defaults` so the flag stays off before the first snapshot arrives. See [`isEnabled`](/reference/sdk#isenabled). **4. Turn it on** In the [dashboard](https://app.useshipd.com), open the project, click `new-checkout`, and select the environment. Then either: * set **Fallthrough** to `true` to turn it on for everyone, or * click **Add rule** to turn it on for some users ([by attribute](/flags/targeting) or [by percentage](/flags/percentage-rollouts)). Click **Save environment**. Running SDK clients pick up the change on their next snapshot refresh. > [!NOTE] > > `shipd push` sets **Fallthrough** in the target environment back to the config `default` when they differ. After you change **Fallthrough** in the dashboard, update `default` in your flag definitions (or run `shipd pull`) so the next push doesn't revert it. See [Push, pull, and diff](/config-as-code/sync). ## Create it without a config file ```bash theme={null} shipd flags create --key new-checkout --type boolean --description "Redesigned checkout flow" ``` Prefer `defineFlags` and `shipd push` so the repository stays the source of truth. See [CLI reference](/reference/cli). ## Next * [Target users by attribute](/flags/targeting) * [Roll out a flag to a percentage of users](/flags/percentage-rollouts) * [Turn a feature off immediately](/flags/kill-switch) # Run an A/B test Source: https://docs.useshipd.com/flags/experiments Split users across variants of a variant flag with sticky assignment, read the variant, and record exposure in your analytics. ## Overview An experiment in shipd is a [variant flag](/flags/variants) whose rules split users across variants. Assignment is deterministic and sticky per user. shipd assigns variants; it does not compute experiment results, so you record each exposure in your own analytics. ## Define the variants ```ts TypeScript theme={null} // shipd.config.ts import { defineFlags } from "shipdit/config"; export default defineFlags({ "search-variant": { type: "variant", variants: ["control", "semantic", "hybrid"] as const, default: "control", description: "Search ranking experiment", tags: ["search", "experiment"], }, }); ``` ```go Go theme={null} // Entries inside config.ShipdConfig (import github.com/alasti-company/shipd-go/config). "search-variant": {Type: "variant", Default: "control", Variants: []string{"control", "semantic", "hybrid"}, Description: "Search ranking experiment", Tags: []string{"search", "experiment"}}, ``` For Go, add definitions to `Config` in `shipd.config.go`, then run `shipd push`. See [Define flags in code](/config-as-code/define-flags#go-definitions) for the complete file. ```bash theme={null} shipd push --project web-app --env production ``` ## Split traffic Percentage conditions on the same flag share one bucket per user, so stacked rules with increasing **Rollout** values split users into slices. For a three-way split: | Rule | Condition | Serve | | - | - | - | | 1 | **Percentage**, **Rollout** `33` | `semantic` | | 2 | **Percentage**, **Rollout** `66` | `hybrid` | | Fallthrough | | `control` | Buckets 0–3299 get `semantic`, 3300–6599 get `hybrid` (rule 1 already matched the lower buckets), and the rest fall through to `control`. **1. Open the flag** In the [dashboard](https://app.useshipd.com), open the project, click `search-variant`, and select the environment. **2. Add the rules** Click **Add rule**, then **Percentage**, and set **Rollout** and **Serve** as in the table. Repeat for the second rule. Keep them in this order. **3. Save** Set **Fallthrough** to `control` and click **Save environment**. Users without a `userId` never match a percentage condition, so they get `control`. Don't change the **Rollout** values or **Seed** mid-experiment; that moves users between variants. See [how bucketing works](/flags/percentage-rollouts#how-bucketing-works). > [!NOTE] > > Rules and **Fallthrough** can also use a weighted serve (`kind: "weighted"`) that splits by weights in a single serve. The dashboard editor keeps existing weighted serves but doesn't edit their weights; set them through the [control-plane API](/reference/control-plane-api). ## Read the variant and record exposure ```ts TypeScript theme={null} // src/search.ts import { shipd } from "./lib/shipd"; import { analytics } from "./lib/analytics"; export function search(userId: string, query: string) { const variant = shipd.getVariant("search-variant", { userId }); analytics.track("experiment_exposure", { userId, experiment: "search-variant", variant, }); switch (variant) { case "semantic": return semanticSearch(query); case "hybrid": return hybridSearch(query); default: return controlSearch(query); } } ``` ```go Go theme={null} // search.go variant := client.GetVariant("search-variant", shipd.EvaluationContext{UserID: userID}) analytics.Track("experiment_exposure", map[string]any{ "userId": userID, "experiment": "search-variant", "variant": variant, }) // Use variant to choose the search implementation. ``` Log the exposure where the user actually sees the variant, and send your outcome metric (searches, conversions) to the same analytics tool. Compare metrics by `variant` there. SDKs also send evaluation events from production environments. The flag page's **Traffic** section uses them to show recent evaluations. They are not experiment analysis. ## End the experiment Set **Fallthrough** to the winning variant, remove the percentage rules, and click **Save environment**. Then update `default` in your flag definitions to match, or remove the flag from code and [archive it](/flags/naming-and-lifecycle). ## Related * [Create a variant flag](/flags/variants) * [`getVariant`](/reference/sdk#getvariant) * [Roll out a flag to a percentage of users](/flags/percentage-rollouts) # Identify users Source: https://docs.useshipd.com/flags/identify-users Set the evaluation context once per session with identify, override it per call, and clear it with reset. ## Overview In the browser SDK (`shipdit/client`), `identify` sets the default evaluation context for a client: a `userId` plus traits. Targeting rules, audiences, and percentage rollouts read from it on every later check until you call `reset`. On servers (`shipdit` and Go), one client serves many users. There, `identify` only records the user's traits for audience insights; pass context on every evaluation. ## Identify on login ```ts TypeScript theme={null} // src/auth.ts (browser) shipd.identify({ userId: "usr_8f2k19", name: "Dana Reyes", traits: { email: "dana@fieldkit.dev", plan: "pro", beta: true }, }); shipd.isEnabled("new-checkout"); // evaluates as usr_8f2k19 with those traits ``` ```go Go theme={null} // auth.go traits := map[string]any{"email": "dana@fieldkit.dev", "plan": "pro", "beta": true} if err := client.Identify(shipd.Identity{UserID: "usr_8f2k19", Name: "Dana Reyes", Traits: traits}); err != nil { log.Printf("shipd identify: %v", err) } client.IsEnabled("new-checkout", shipd.EvaluationContext{UserID: "usr_8f2k19", Attributes: traits}) ``` Both SDKs require a nonempty user ID. TypeScript throws for invalid identity; Go returns an error. In browsers, TypeScript traits become default context `attributes`. Server clients require them on each evaluation. See [`identify`](/reference/sdk#identify). ## Server identity events On a server client (`shipdit` or Go), `identify` queues an event for audience insights. Pass traits separately on every evaluation; it does not change the client's evaluation context, and it does not fetch remote trait overlays. See [Go Identify](/reference/go-sdk#identify). ## Reset on logout (TypeScript) ```ts theme={null} shipd.reset(); ``` See [`reset`](/reference/sdk#reset). ## Override per call A context passed to an evaluation method wins over the identified one. Attributes merge key by key. ```ts theme={null} shipd.identify({ userId: "usr_8f2k19", traits: { plan: "free" } }); shipd.isEnabled("new-checkout", { attributes: { plan: "pro" } }); // userId: usr_8f2k19, plan: "pro" ``` On servers, where one client serves many users, pass the context on every call: ```ts TypeScript theme={null} shipd.isEnabled("new-checkout", { userId: req.user.id, attributes: { plan: req.user.plan } }); ``` ```go Go theme={null} client.IsEnabled("new-checkout", shipd.EvaluationContext{ UserID: user.ID, Attributes: map[string]any{"plan": user.Plan}, }) ``` ## Anonymous ID in the browser `shipdit/client` creates an `anonymousId` and stores it in localStorage (key `shipdit:anonymousId`), so a visitor's sessions before and after login can be correlated. ```ts theme={null} shipd.getAnonymousId(); ``` Pass the `anonymousId` option to use an ID you already have, or `onAnonymousId` to be called when the client assigns or rotates one. See [`createClient`](/reference/sdk#createclient). ## Location traits (browser) Browser clients do not fetch stored trait overlays from `GET /sdk/v1/identity` (that route is restricted to server SDK keys). Pass the user's traits directly to `identify()` or in per-call context. Browser clients add location traits (`country`, `region`, `city`, `timezone`) automatically unless `automaticTraits: false` is set. See [Location traits in the browser](/flags/targeting#location-traits-in-the-browser) and [Client vs. server evaluation](/concepts/client-vs-server). ## Related * [Target users by attribute](/flags/targeting) * [`EvaluationContext`](/reference/sdk#types) # Turn a feature off immediately Source: https://docs.useshipd.com/flags/kill-switch Use a boolean flag as a kill switch: set Fallthrough to false, remove rules that serve true, and know how fast clients see it. ## Overview To turn a feature off for everyone, make the flag serve `false` in that environment: set **Fallthrough** to `false` and remove any rules that serve `true`. SDK clients pick up the change within seconds when streaming is on, or on their next poll. ## Turn it off **1. Open the flag** In the [dashboard](https://app.useshipd.com), open the project, click the flag (for example `new-checkout`), and select the environment, for example `production`. **2. Serve false** Set **Fallthrough** to `false`. **Remove** every rule that serves `true`, or change its **Serve** to `false`. **3. Save** Click **Save environment**. > [!WARNING] > > Switching **Enabled in production** off does not turn a boolean flag off by itself. A disabled flag skips its rules and serves the **Fallthrough** value to everyone. If **Fallthrough** is `true`, a disabled flag keeps serving `true`. Always set **Fallthrough** to the off value. Switching **Enabled in \** off is still useful when **Fallthrough** is already `false`: it stops every rule from matching in one click, without deleting the rules. ## How fast it takes effect | Client setup | Time to see the change | | - | - | | TypeScript: `stream: true` | Normally within seconds when a WebSocket implementation is available. The notification triggers a snapshot fetch; polling continues as a backup unless disabled. | | TypeScript: polling only | Next successful poll: `refreshIntervalMs` (default 30 seconds) after the previous fetch finishes, plus fetch time. Failures can delay it further. | | TypeScript: `refreshIntervalMs: 0` without `stream: true` | Only on manual `refresh()` or restart. Don't use this for flags you may need to kill. | | Go: polling | Next successful poll on the `RefreshInterval` schedule (default 30 seconds), plus fetch time. Slow or failed requests can delay it further. | | Go: `DisablePolling: true` | Only on manual `Refresh(ctx)` or restart. | ```ts TypeScript theme={null} // src/lib/shipd.ts export const shipd = createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, stream: true, defaults: { "new-checkout": false }, }); ``` ```go Go theme={null} // flags.go client, err := shipd.New(shipd.Options{ SDKKey: os.Getenv("SHIPD_SDK_KEY"), RefreshInterval: 5 * time.Second, Defaults: map[string]any{"new-checkout": false}, }) if err != nil { return err } defer func() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if err := client.Shutdown(ctx); err != nil { log.Printf("shipd events: %v", err) } }() ``` See [Local evaluation](/concepts/local-evaluation) for how snapshots refresh. ## Make the code default the safe value When the SDK has no snapshot (before `ready()`, or when the edge is unreachable with no cache), it serves the client `defaults`. Write flags so the default is the safe state: ```ts TypeScript theme={null} // Good: false means the risky path is off if (shipd.isEnabled("new-checkout", { userId })) { return renderNewCheckout(); } return renderLegacyCheckout(); ``` ```go Go theme={null} if client.IsEnabled("new-checkout", shipd.EvaluationContext{UserID: userID}) { return renderNewCheckout() } return renderLegacyCheckout() ``` Keep `default: false` in your flag definitions too. `shipd push` sets **Fallthrough** in the target environment to the config `default`, so a config that says `true` would turn the feature back on at the next push. ## Approvals If an [approval policy](/operations/approvals) protects the environment, **Save environment** can create a pending request instead of changing the live flag. The feature stays on until the request is approved. Plan for this before an incident: make sure enough reviewers are available, or keep a policy that lets on-call staff approve quickly. ## Related * [Create a boolean flag](/flags/boolean) * [Why isn't my flag updating?](/resources/troubleshooting) # Name, deprecate, and archive flags Source: https://docs.useshipd.com/flags/naming-and-lifecycle Choose flag keys, describe and tag flags, mark them deprecated, and archive them safely with shipd push --prune. ## Overview A flag's key is its permanent identity in code, config, and the snapshot. Name flags for what they control, mark them deprecated when you plan to remove them, remove them from code, and then archive them. shipd archives flags; it never hard-deletes them. ## Name the key | Do | Example | Avoid | | - | - | - | | Use lowercase kebab-case | `new-checkout` | `NewCheckout`, `new_checkout` | | Describe the behavior, not who gets it | `search-variant` | `search-for-acme`, `dana-test` | | Name numbers and JSON by what they hold | `max-retries`, `checkout-payload` | `config-1` | | Keep keys stable | `rules-editor` | `rules-editor-v2-final` | shipd accepts any non-empty key except `__proto__`. The conventions above are recommendations. Treat keys as permanent: deployed code that still evaluates an old key gets client defaults. To rename, add a flag with the new key, move code to it, then archive the old one. ## Describe and tag ```ts TypeScript theme={null} // shipd.config.ts "new-checkout": { type: "boolean", default: false, description: "Redesigned checkout flow. Remove after full rollout.", tags: ["checkout", "release"], }, ``` ```go Go theme={null} // Entries inside config.ShipdConfig (import github.com/alasti-company/shipd-go/config). "new-checkout": {Type: "boolean", Default: false, Description: "Redesigned checkout flow. Remove after full rollout.", Tags: []string{"checkout", "release"}}, ``` For Go, add definitions to `Config` in `shipd.config.go`, then run `shipd push`. See [Define flags in code](/config-as-code/define-flags#go-definitions) for the complete file. `description` and `tags` show on the flag page in the dashboard. Use tags for ownership and flag kind (`release`, `experiment`, `ops`). ## Mark a flag deprecated ```ts TypeScript theme={null} // shipd.config.ts "new-checkout": { type: "boolean", default: true, deprecated: true, }, ``` ```go Go theme={null} "new-checkout": {Type: "boolean", Default: true, Deprecated: true}, ``` `deprecated: true` sets the flag's lifecycle to `deprecated` when you push. It is a marker for people and tools; evaluation doesn't change. ## Archive a flag **1. Remove it from code** Delete every `isEnabled("new-checkout")` call (or other evaluation method), keeping the branch you shipped. Remove the key from client `defaults`. Deploy. **2. Remove it from shipd.config.ts** Delete the entry and run `shipd diff` to preview. **3. Push with --prune** ```bash theme={null} shipd push --prune --project web-app --env production ``` `--prune` archives remote flags that are no longer in your flag definitions. Without it, push leaves them alone. You can also archive one flag with `shipd flags archive --key new-checkout`, or with **Archive flag** on the flag page. An admin can restore an archived flag for 7 days; the key stays reserved until then. > [!WARNING] > > `--prune` archives **every** remote flag missing from your flag definitions, including flags created in the dashboard or by another repository. New projects include demo flags `welcome` and `beta-features`; a first `--prune` archives them. Check the plan before you confirm. ## Why code goes first An archived flag is removed from the snapshot. Code that still evaluates it gets the client `defaults` value (or the type's zero value, such as `false`, if you didn't pass one), and the SDK reports an `unregistered_flag` event. If you archive a flag that is fully rolled out before removing the code, users lose the feature. Push also regenerates TypeScript types or Go accessors, so references through generated TypeScript types or Go accessors fail to compile after removal. Go calls with literal keys, such as `client.IsEnabled("new-checkout", ctx)`, still compile. ## Approvals Archival isn't part of the approval request model. If an [approval policy](/operations/approvals) protects an environment, archiving a flag there is blocked, and a push that includes it fails. ## Related * [Define flags in code](/config-as-code/define-flags) * [CLI reference](/reference/cli) * [Config reference](/reference/config) # Create number and JSON flags Source: https://docs.useshipd.com/flags/number-and-json Serve numeric settings and JSON payloads with getNumber and getJson. ## Overview Number and JSON flags serve values instead of on/off. In this guide you add `max-retries` (a number) and `checkout-payload` (a JSON object), push them, and read them in code. ## Define them ```ts TypeScript theme={null} // shipd.config.ts import { defineFlags } from "shipdit/config"; export default defineFlags({ "max-retries": { type: "number", default: 3, description: "Max retries for outbound API calls", }, "checkout-payload": { type: "json", default: { mode: "strict", showPromo: true }, description: "Checkout UI settings", }, }); ``` ```go Go theme={null} // Entries inside config.ShipdConfig (import github.com/alasti-company/shipd-go/config). "max-retries": {Type: "number", Default: 3}, "checkout-payload": {Type: "json", Default: map[string]any{"mode": "strict", "showPromo": true}}, ``` For Go, add definitions to `Config` in `shipd.config.go`, then run `shipd push`. See [Define flags in code](/config-as-code/define-flags#go-definitions) for the complete file. ```bash theme={null} shipd push --project web-app --env production ``` ## Read a number ```ts TypeScript theme={null} // src/invoices.ts const retries = shipd.getNumber("max-retries"); await fetchInvoice(id, { retries }); ``` ```go Go theme={null} // invoices.go retries := client.GetNumber("max-retries", shipd.EvaluationContext{}) // GetNumber returns float64. Validate and convert it for your application's API. ``` In React, use `useNumber("max-retries")`. See [React bindings](/sdks/react). See [`getNumber`](/reference/sdk#getnumber). ## Read JSON ```ts TypeScript theme={null} // src/checkout.ts const ui = shipd.getJson("checkout-payload"); // typed from the default's shape in FlagDefinitions ``` ```go Go theme={null} // checkout.go ui := client.GetJSON("checkout-payload", shipd.EvaluationContext{}) payload, ok := ui.(map[string]any) if ok { mode, _ := payload["mode"].(string) _ = mode } ``` In React, use `useJson("checkout-payload")`. Code against that shape and keep values served from the dashboard compatible with it. See [`getJson`](/reference/sdk#getjson). ## Change the value On the flag page in the dashboard, set **Fallthrough** to a new value, or add a rule that serves a different value to some users. Click **Save environment**. # Roll out a flag to a percentage of users Source: https://docs.useshipd.com/flags/percentage-rollouts Serve a flag to a sticky percentage of users with a Percentage condition, then raise it gradually. ## Overview A percentage rollout serves a flag to a fixed share of users, for example 10% get `new-checkout`. Each user always lands in the same bucket, so raising the percentage adds users without removing anyone already in. ## Add the rollout **1. Open the flag** In the [dashboard](https://app.useshipd.com), open the project, click `new-checkout`, and select the environment. **2. Add a percentage rule** Click **Add rule**, then **Percentage**. Set **Rollout** to `10` and the rule's **Serve** to `true`. Leave **Fallthrough** at `false`. **3. Save** Click **Save environment**. Your code doesn't change, but it must send a `userId`: ```ts TypeScript theme={null} // src/checkout.ts shipd.isEnabled("new-checkout", { userId: "usr_8f2k19" }); ``` ```go Go theme={null} // checkout.go client.IsEnabled("new-checkout", shipd.EvaluationContext{UserID: "usr_8f2k19"}) ``` ## How bucketing works The SDK hashes the flag key and the `userId` into a bucket from 0 to 9999. The rule matches when the bucket is below **Rollout** × 100, so `10` matches buckets 0–999. * **Sticky.** The same user and flag always get the same bucket. No assignment is stored. * **Monotonic.** Raising **Rollout** from 10 to 25 keeps buckets 0–999 in and adds 1000–2499. * **Independent per flag.** A user in the first 10% of `new-checkout` isn't necessarily in the first 10% of another flag. To align flags, give them the same **Seed**. * **Needs an ID.** Without a `userId` (or the chosen bucketing attribute) the condition never matches and the user gets the next rule or **Fallthrough**. ## Bucket by something other than the user Set **Of attribute** to bucket on another context attribute, for example `organizationId`, so everyone in an organization gets the same result: ```ts TypeScript theme={null} shipd.isEnabled("new-checkout", { userId: "usr_8f2k19", attributes: { organizationId: "org_fieldkit" }, }); ``` ```go Go theme={null} client.IsEnabled("new-checkout", shipd.EvaluationContext{ UserID: "usr_8f2k19", Attributes: map[string]any{"organizationId": "org_fieldkit"}, }) ``` Leave **Of attribute** empty to bucket on `userId`. ## Combine with targeting Conditions in one rule must all match. Add an **Attribute** condition to the same rule to roll out to 10% of Pro users only (`plan is pro` and **Percentage** `10`). Rules run top to bottom, so put an internal-staff rule above the rollout to keep staff always on. See [Target users by attribute](/flags/targeting). ## Finish the rollout At 100%, the rule matches every user with an ID. To finish, set **Fallthrough** to `true`, remove the rule, and set `default: true` in TypeScript definitions or `Default: true` in Go definitions so the next `shipd push` doesn't set **Fallthrough** back to `false`. Later, remove the flag from code and [archive it](/flags/naming-and-lifecycle). ## Per environment Rollouts are environment state. A 10% rollout in `staging` doesn't affect `production`. To copy the enabled state, rules, and **Fallthrough** to other environments, click **Sync to…** on the flag page. ## Approvals If an [approval policy](/operations/approvals) protects the environment, saving can create a pending request instead of changing the live flag. Policies can target rollout increases specifically. SDKs keep serving the current rollout until the request is approved. ## Related * [Run an A/B test](/flags/experiments) * [Turn a feature off immediately](/flags/kill-switch) # Target users by attribute Source: https://docs.useshipd.com/flags/targeting Serve a flag to one user, an email domain, or a plan with dashboard rules that match evaluation context attributes. ## Overview Targeting rules can live in the dashboard or in an optional per-flag [`targeting` block](/reference/config#targeting-in-code). Pushing that block makes the selected environment code-owned and blocks dashboard targeting edits. Your code sends an evaluation context (a `userId` and attributes); the SDK matches it against the rules in the snapshot, locally, with no network call. This page shows how to target one user, an email domain, or a plan. ## Send attributes from code ```ts TypeScript theme={null} // src/checkout.ts shipd.isEnabled("new-checkout", { userId: "usr_8f2k19", attributes: { email: "dana@fieldkit.dev", plan: "pro", seats: 12, }, }); ``` ```go Go theme={null} // checkout.go client.IsEnabled("new-checkout", shipd.EvaluationContext{ UserID: "usr_8f2k19", Attributes: map[string]any{ "email": "dana@fieldkit.dev", "plan": "pro", "seats": 12, }, }) ``` In TypeScript session clients, you can also set them once with [`identify`](/flags/identify-users): ```ts theme={null} shipd.identify({ userId: "usr_8f2k19", traits: { email: "dana@fieldkit.dev", plan: "pro", seats: 12 }, }); shipd.isEnabled("new-checkout"); ``` Rules can only match what you send. Attribute values are strings, numbers, booleans, or `null`. See [`EvaluationContext`](/reference/sdk#types). ## Add a rule **1. Open the flag** In the [dashboard](https://app.useshipd.com), open the project, click the flag, and select the environment. **2. Add a condition** Click **Add rule**, then **Attribute**. Fill in **Attribute**, **Operator**, and **Value**. **3. Choose what to serve** Set the rule's **Serve** value, for example `true`. **4. Save** Click **Save environment**. Use the simulator on the flag page to check a user before you save. ## Common rules | Goal | Attribute | Operator | Value | | - | - | - | - | | One user | `userId` | is | `usr_8f2k19` | | A few users | `userId` | is one of | `usr_8f2k19, usr_3m7q04` | | An email domain | `email` | ends with | `@fieldkit.dev` | | Paid plans | `plan` | is one of | `pro, enterprise` | | Large accounts | `seats` | is at least | `10` | | Internal staff | `internal` | is | `true` | The `userId` attribute reads `context.userId`, so you don't need to repeat it in `attributes`. String operators are case-sensitive: lowercase emails before you send them. ## Operators | Dashboard label | Operator | Matches when the attribute… | | - | - | - | | is / is not | `eq` / `neq` | equals / does not equal the value | | is one of / is not one of | `in` / `not_in` | is / is not in a comma-separated list | | contains | `contains` | contains the string | | starts with / ends with | `startsWith` / `endsWith` | starts / ends with the string | | is greater than / is at least | `gt` / `gte` | is greater than / greater than or equal to | | is less than / is at most | `lt` / `lte` | is less than / less than or equal to | | exists / does not exist | `exists` / `not_exists` | is present / absent in the context | An attribute missing from the context matches only `does not exist`. ### How values compare `is` and `is one of` (and their negations) coerce numeric and boolean values, and otherwise use exact string equality. Ordered comparisons (`gt`, `gte`, `lt`, `lte`) compare numbers as numbers, then timestamps as instants, and otherwise strings by character code. Equivalent timestamps with different offsets match only in ordered comparisons, not string equality. Current SDK versions (`shipdit` 0.4+, `@shipdit/convex` 0.2+, and Go 0.1+) apply the same rules. Earlier TypeScript SDK versions use different timestamp parsing; see [Upgrade to shipdit 0.4](/migrations/shipdit-0-4). **Numbers.** A string counts as a number when it's a decimal (`10`, `-2.5`, `.5`, `1e3`) or an unsigned `0x`, `0o`, or `0b` literal (`0x10`). Surrounding whitespace is ignored. Underscores (`1_000`), hex floats (`0x1p-2`), signed hex (`-0x10`), and `Infinity` are not numbers, so they compare as strings. **Timestamps.** For ordered comparisons, both values must be strings in this format to compare as times: | Format | Example | Meaning | | - | - | - | | `YYYY-MM-DD` | `2026-01-02` | Midnight UTC that day | | `YYYY-MM-DDThh:mm[:ss[.fraction]]` plus a zone | `2026-01-02T10:00:00Z`, `2026-01-02T12:00+02:00` | That instant. The zone is `Z` or `±hh:mm` and is required. Fractions keep milliseconds; extra digits are dropped. | Dates are range-checked: `2026-02-30` and `2026-02-29` aren't dates. Anything else, including times without a zone (`2026-01-02T10:00`), a space instead of `T`, or single-digit months (`2026-1-2`), compares as a string. Send timestamps in UTC with a `Z` to avoid surprises. Saving a flag or audience with a date-looking value outside this grammar in an ordered comparison returns the non-blocking `x-shipd-rule-warning` API header; the dashboard displays the warning. The rule still saves because string ordering is supported. Older TypeScript SDKs and Convex components can disagree with dashboard preview: check the [TypeScript](/migrations/shipdit-0-4#check-timestamp-rules-before-upgrading) or [Convex migration guide](/migrations/convex-0-2#check-timestamp-rules-before-upgrading) before upgrading. ## Rule order * Rules run top to bottom. **The first matching rule wins**; later rules are not checked. * All conditions in one rule must match. Use **Any of** to match one of several conditions. * If no rule matches, the flag serves **Fallthrough**. Put narrow rules (one user) above broad ones (a plan or a percentage). Reorder rules with the arrows on each rule. ## Reuse targeting with audiences An audience is a named set of conditions you can reference from any flag in the project. Create one under **Audiences** → **New audience**, then add an **Audience** condition to a rule with **Membership** set to **is in** or **is not in**. Audiences compile into the snapshot and evaluate locally from the same context attributes. You can also assert membership from code by passing audience keys: ```ts TypeScript theme={null} shipd.isEnabled("new-checkout", { userId: "usr_8f2k19", segmentIds: ["beta-testers"], }); ``` ```go Go theme={null} client.IsEnabled("new-checkout", shipd.EvaluationContext{ UserID: "usr_8f2k19", SegmentIDs: []string{"beta-testers"}, }) ``` ## Location traits in the browser `shipdit/client` fills `country`, `region`, `city`, and `timezone` automatically, so you can add rules like `country is US` or `timezone is America/Los_Angeles` without sending them yourself. `country` is an ISO 3166-1 alpha-2 code; `timezone` is the browser's IANA zone. When the same attribute comes from more than one place, the first source wins: 1. Per-call `attributes` 2. `identify()` traits 3. `createClient({ context })` 4. Browser timezone 5. Edge geolocation Turn it off with `automaticTraits: false`. Server clients (`shipdit` and Go) don't infer location; pass it as an attribute. See [Browser SDK](/sdks/browser). ## Related * [Identify users](/flags/identify-users) * [Roll out a flag to a percentage of users](/flags/percentage-rollouts) * [Local evaluation](/concepts/local-evaluation) * [Edge API](/reference/edge-api) for evaluation events and identity # Create a variant flag Source: https://docs.useshipd.com/flags/variants Define a flag with named variants and read it with getVariant. ## Overview A variant flag serves one of a fixed set of string values. In this guide you add `search-variant` with the variants `control`, `semantic`, and `hybrid`, push it, and switch on the served value in code. ## Steps **1. Define the flag** ```ts TypeScript theme={null} // shipd.config.ts import { defineFlags } from "shipdit/config"; export default defineFlags({ "search-variant": { type: "variant", variants: ["control", "semantic", "hybrid"] as const, default: "control", description: "Search ranking variant", tags: ["search"], }, }); ``` ```go Go theme={null} // Entries inside config.ShipdConfig (import github.com/alasti-company/shipd-go/config). "search-variant": {Type: "variant", Default: "control", Variants: []string{"control", "semantic", "hybrid"}}, ``` For Go, add definitions to `Config` in `shipd.config.go`, then run `shipd push`. See [Define flags in code](/config-as-code/define-flags#go-definitions) for the complete file. `default` must be one of `variants`. TypeScript checks this at compile time; Go's `ShipdConfig` validates it when exporting. In TypeScript, keep `as const` to preserve literal variants. **2. Push it** ```bash theme={null} shipd push --project web-app --env production ``` **3. Evaluate it** ```ts TypeScript theme={null} // src/search.ts const variant = shipd.getVariant("search-variant", { userId: "usr_8f2k19" }); // "control" | "semantic" | "hybrid" switch (variant) { case "semantic": return semanticSearch(query); case "hybrid": return hybridSearch(query); default: return controlSearch(query); } ``` ```go Go theme={null} // search.go variant := client.GetVariant("search-variant", shipd.EvaluationContext{UserID: "usr_8f2k19"}) switch variant { case "semantic": return semanticSearch(query) case "hybrid": return hybridSearch(query) default: return controlSearch(query) } ``` In React: ```tsx src/components/search.tsx theme={null} const variant = useVariant("search-variant"); ``` See [`getVariant`](/reference/sdk#getvariant). **4. Choose who gets which variant** On the flag page in the dashboard, set **Fallthrough** to a variant, or add rules whose **Serve** is a variant. Click **Save environment**. To split users randomly across variants, see [Run an A/B test](/flags/experiments). ## Create it without a config file ```bash theme={null} shipd flags create --key search-variant --type variant --variants control,semantic,hybrid ``` `--variants` is required with `--type variant`. See [CLI reference](/reference/cli). # Feature flag best practices Source: https://docs.useshipd.com/guides/best-practices Practical feature flag best practices: how to define, review, and evaluate flags — and when not to use one. ## Overview Feature flags (flags) let you change what an app does without redeploying. This guide covers how to define them, review changes before production, evaluate them safely in code, and when a flag is the wrong tool. ## What a flag is for Use a flag when you need at least one of these: | Job | Example | | - | - | | Progressive delivery | Roll `new-checkout` from 5% to 100% | | Kill switch | Turn a risky path off without a deploy | | Targeted access | Ship to `plan: "pro"` or one email domain first | | Experiment | Split users across `search-variant` variants | A flag is temporary release control, not a permanent settings database. Plan the day you remove it when you create it. ## Define Write the flag key and type in code so every environment shares one definition. Review that file in a pull request like any other change. ```ts TypeScript theme={null} // shipd.config.ts import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, description: "Redesigned checkout. Remove after full rollout.", tags: ["checkout", "release"], }, "search-variant": { type: "variant", variants: ["control", "semantic", "hybrid"] as const, default: "control", description: "Search ranking experiment", tags: ["search", "experiment"], }, }); ``` ```go Go theme={null} // shipd.config.go package main import "github.com/alasti-company/shipd-go/config" var Config = config.ShipdConfig{ "new-checkout": {Type: "boolean", Default: false, Description: "Redesigned checkout. Remove after full rollout.", Tags: []string{"checkout", "release"}}, "search-variant": {Type: "variant", Default: "control", Variants: []string{"control", "semantic", "hybrid"}, Description: "Search ranking experiment", Tags: []string{"search", "experiment"}}, } ``` | Practice | Do | Avoid | | - | - | - | | Name the behavior | `new-checkout`, `max-retries` | `dana-test`, `flag-1` | | Safe default | `default: false` for risky paths | Defaulting to the new path | | One concern | One flag per release or experiment | Bundling unrelated features behind one key | | Ownership | `description` + `tags` | Keys with no owner or removal note | Push with `shipd push`. Define [targeting and rollout guards in code](/reference/config#targeting-in-code), or omit targeting to manage it in the dashboard per environment. See [Define flags in code](/config-as-code/define-flags) and [Name, deprecate, and archive flags](/flags/naming-and-lifecycle). ## Review Treat production flag changes like production code changes. 1. **Definitions in git.** Flag keys, types, and defaults land in pull requests. Reviewers see what can exist before anyone turns it on. 2. **Diff in CI.** Run `shipd diff` on pull requests so drift between the repo and shipd is visible before merge. See [Sync flags in CI](/config-as-code/ci). 3. **Second pair of eyes on production.** Require [approvals](/operations/approvals) for production environment changes when more than one person can ship. 4. **Raise exposure gradually.** Start with a [percentage rollout](/flags/percentage-rollouts) or a narrow [targeting](/flags/targeting) rule, then widen. Do not jump from 0% to 100% on an unproven path. Approval policies cover flag environment state (enabled, rules, fallthrough). Archival and other definition changes are blocked on a protected environment instead of queuing for review — see [Approvals](/operations/approvals#operations-outside-the-request-model). Prefer reviewing the plan before you publish. ## Evaluate Evaluate in process from a local snapshot. Do not put a network hop on the request path for the decision itself. ```ts TypeScript theme={null} // src/checkout.ts import { createClient } from "shipdit"; import type { FlagDefinitions } from "./generated/flags"; const shipd = createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, defaults: { "new-checkout": false, "search-variant": "control" }, }); await shipd.ready(); export function renderCheckoutFor(userId: string) { if (shipd.isEnabled("new-checkout", { userId })) { return renderNewCheckout(); } return renderLegacyCheckout(); } ``` ```go Go theme={null} // Within your application's request handler; see the Go quickstart for setup. if client.IsEnabled("new-checkout", shipd.EvaluationContext{UserID: "usr_8f2k19"}) { // New checkout. } else { // Legacy checkout. } ``` | Practice | Why | | - | - | | Pass a stable `userId` for rollouts and experiments | Percentage and variant assignment stay sticky per user | | Set client `defaults` to the safe value | Before `ready()`, or if the edge is unreachable with no cache, the SDK serves defaults | | Keep both branches working until cleanup | You must be able to turn the flag off without a hotfix deploy | | Test with a bootstrap snapshot | Unit tests should not depend on the network. See [Testing](/sdks/testing) | For how evaluation stays local and what happens when shipd is down, see [Local evaluation](/concepts/local-evaluation). To decide whether a flag belongs in the browser SDK (`clientAvailable: true`) or behind an authenticated server endpoint, see [Client vs. server evaluation](/concepts/client-vs-server). ## Remove flags on purpose A finished rollout that stays in the codebase forever is technical debt with a runtime API. **1. Finish the rollout** Serve the winning value to everyone (for a boolean, **Fallthrough** `true`, or archive the off path in code after you are sure). **2. Delete the branch in code** Keep only the shipped path. Remove `isEnabled` / `getVariant` calls and the key from client `defaults`. Deploy. **3. Deprecate, then archive** Keep the definition, set `deprecated: true`, and push so the lifecycle marker lands. After code no longer references the key, remove the definition and run `shipd push --prune` (or archive from the dashboard). Details: [Name, deprecate, and archive flags](/flags/naming-and-lifecycle). ## When not to use a flag Skip a flag when another tool is clearer: | Situation | Prefer instead | | - | - | | The value never varies by user or environment after launch | Ship the code; no flag | | Infrastructure or process config (log level, pool size) that ops owns | Environment variables or your config service | | Authorization ("is this user allowed?") | Your authz system; a flag can gate a UI, not replace permissions | | Secrets, API keys, or credentials | A secret manager — never a flag payload | | Long-lived product settings edited daily by non-engineers | A settings product, not a release flag | | You need experiment stats, funnels, or session replay | An analytics or experimentation suite; shipd assigns variants, it does not analyze them | If you already created a flag and the feature is fully rolled out, remove the flag rather than leaving it at 100% forever. ## Related * [Quickstart](/quickstart) * [Create a boolean flag](/flags/boolean) * [Turn a feature off immediately](/flags/kill-switch) * [Run an A/B test](/flags/experiments) * [Feature flag tools](https://useshipd.com/feature-flag-tools) # shipd Source: https://docs.useshipd.com/index Feature flags with config-as-code and local evaluation. ## Overview shipd is a feature flag service. You define flags in TypeScript or Go, control them from a dashboard, and evaluate them in memory in your app. > [card] [Quickstart](/quickstart) > > A working flag in about 3 minutes. > [card] [SDKs](/sdks/node) > > TypeScript, Go, browser, React, Next.js, Convex. > [card] [CLI reference](/reference/cli) > > `login`, `push`, `pull`, `diff`, `types gen`. ## Get started | Your stack | Start here | Complete example | | - | - | - | | Node.js / TypeScript server | [Node.js](/sdks/node) | [examples/node](/examples/node) | | Go server | [Go](/sdks/go) | [examples/go](/examples/go) | | Browser (any framework) | [Browser](/sdks/browser) | — | | React | [React](/sdks/react) | [examples/react](/examples/react) | | Next.js | [Next.js](/sdks/nextjs) | [examples/nextjs](/examples/nextjs) | | Convex | [Convex](/sdks/convex) | [examples/convex](/examples/convex) | New to shipd? Read [Core concepts](/core-concepts) — it's five minutes. ## Common tasks * [Feature flag best practices](/guides/best-practices) * [Create a flag](/flags/boolean) * [Target a user, plan, or email domain](/flags/targeting) * [Roll out to a percentage of users](/flags/percentage-rollouts) * [Run an A/B test](/flags/experiments) * [Turn a feature off immediately](/flags/kill-switch) * [Push flags from CI](/config-as-code/ci) * [Connect a coding agent](/operations/connect-an-agent) * [Test flags locally](/sdks/testing) * [Why isn't my flag updating?](/resources/troubleshooting) ## Understand shipd * [Core concepts](/core-concepts): the whole model on one page * [Local evaluation](/concepts/local-evaluation): why checks never wait on the network * [Environments](/concepts/environments): projects, environments, and production protection * [Keys and tokens](/concepts/keys): which credential goes where * [Architecture](/concepts/architecture): control plane and data plane ## Reference * [TypeScript SDK](/reference/sdk) · [Go SDK](/reference/go-sdk) · [CLI](/reference/cli) · [Config](/reference/config) * [Edge API](/reference/edge-api) · [Control-plane API](/reference/control-plane-api) · [Errors](/reference/errors) * [MCP tools](/reference/mcp) * [Glossary](/reference/glossary) ## At a glance Define flags in TypeScript with `defineFlags` or in Go with a `config.ShipdConfig` literal, then evaluate them with your SDK: ```ts TypeScript theme={null} // shipd.config.ts import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false }, "search-variant": { type: "variant", variants: ["control", "semantic", "hybrid"] as const, default: "control", }, }); ``` ```go Go theme={null} // shipd.config.go package main import "github.com/alasti-company/shipd-go/config" var Config = config.ShipdConfig{ "new-checkout": {Type: "boolean", Default: false}, "search-variant": { Type: "variant", Default: "control", Variants: []string{"control", "semantic", "hybrid"}, }, } ``` The [quickstart](/quickstart) shows how to sync these definitions with the CLI and generate TypeScript types or Go accessors. ```ts TypeScript theme={null} // src/checkout.ts import { createClient } from "shipdit"; import type { FlagDefinitions } from "./generated/flags"; const shipd = createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, defaults: { "new-checkout": false, "search-variant": "control" }, }); await shipd.ready(); if (shipd.isEnabled("new-checkout", { userId: "usr_8f2k19" })) { // new checkout } ``` ```go Go theme={null} // Within your application's startup function; see the Go quickstart for imports. client, err := shipd.New(shipd.Options{ SDKKey: os.Getenv("SHIPD_SDK_KEY"), Defaults: map[string]any{"new-checkout": false, "search-variant": "control"}, }) if err != nil { return err } defer func() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if err := client.Shutdown(ctx); err != nil { log.Printf("shipd events: %v", err) } }() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) if err := client.Ready(ctx); err != nil { log.Printf("using defaults: %v", err) } cancel() if client.IsEnabled("new-checkout", shipd.EvaluationContext{UserID: "usr_8f2k19"}) { // New checkout. } ``` The shipd dashboard runs on shipd: `rules-editor` and `audit-log` are flags. > [!TIP] > > Using an AI coding assistant? Point it at [`/ai`](/ai) (or `https://docs.useshipd.com/ai.md`) for a compact shipd context file, or at [`/llms-full.txt`](https://docs.useshipd.com/llms-full.txt) for the full docs. # Evaluate flags with OpenFeature Source: https://docs.useshipd.com/integrations/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](/changelog/openfeature) for release candidate availability. ## Install and register Create a [server SDK key](/concepts/keys) 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](/reference/sdk#options) or [Go SDK options](/reference/go-sdk#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](/reference/customer-events) 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](/operations/receive-customer-events). `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](/changelog/openfeature) 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](/concepts/keys) 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. # Manage projects and environments with Terraform Source: https://docs.useshipd.com/integrations/terraform Install the shipd Terraform provider from the Terraform Registry, configure credentials, and provision projects and environments. ## Overview Use the shipd Terraform provider to create and manage projects and environments, detect drift, or look up existing objects. Continue to manage flag definitions with [config as code](/config-as-code/define-flags). See the [Terraform provider changelog](/changelog/terraform) for the resources each release supports. > [!NOTE] > > This guide pins the v0.1 provider for projects and environments. For the > credential resources available in later builds, see [Manage credentials from CI](/reference/terraform#manage-credentials-from-ci). ## Prerequisites * Terraform 1.11 or later. CI covers Terraform 1.11.4 and 1.17.1; OpenTofu compatibility is not yet established. * A shipd organization and a [service account token](/enterprise/service-accounts). To create projects, use an organization-wide token with no project or environment binding. Grant these scopes for the example below. Create the service account and token in the dashboard before running Terraform. ```json theme={null} { "project": ["read", "create", "update", "archive"], "environment": ["read", "create", "update", "archive", "set_production"] } ``` ## Configure credentials Load your service account token from your secret store into the shell where you will run Terraform: ```bash theme={null} export SHIPD_API_KEY="shipd_sa_REPLACE_WITH_YOUR_TOKEN" ``` ## Create a project and environment Create `main.tf` in your configuration directory. Terraform installs the published [alasti-company/shipd provider](https://registry.terraform.io/providers/alasti-company/shipd/latest/docs) from the Terraform Registry: ```hcl main.tf theme={null} terraform { required_version = ">= 1.11" required_providers { shipd = { source = "alasti-company/shipd" version = "~> 0.1.0" } } } provider "shipd" {} resource "shipd_project" "app" { name = "Web app" slug = "web-app" lifecycle { prevent_destroy = true } } resource "shipd_environment" "production" { project_id = shipd_project.app.id name = "Production" slug = "production" type = "production" is_production = true lifecycle { prevent_destroy = true } } output "environment_id" { value = shipd_environment.production.id } ``` Run these commands from the configuration directory, review the plan, and apply it: ```bash theme={null} terraform init terraform plan terraform apply ``` Commit `.terraform.lock.hcl` to keep provider versions consistent across your team and CI. If you previously used a local build, remove its `dev_overrides` entry from your Terraform CLI configuration before initializing so Terraform uses the published provider. For existing projects or environments, [import their IDs](/reference/terraform#import-existing-resources) before applying, or use [data sources](/reference/terraform#data-sources) to read them without managing their lifecycle. ## Report runs from CI In **Settings → Service accounts**, create a service account token with the `terraform: report` scope. Bind it to the project and environment your CI job targets and save it as `SHIPD_TERRAFORM_REPORT_TOKEN` in CI. Set `SHIPD_PROJECT_ID`, `SHIPD_ENVIRONMENT_ID`, and `CI_RUN_URL` for the job. The project and environment IDs appear in the example configuration under **Project settings → Integrations → Terraform**. Run this script directly after your CI job finishes a plan or apply. Pass the operation, its exit code, and the ISO 8601 completion timestamp. ```bash report-terraform-run.sh theme={null} #!/usr/bin/env bash set -euo pipefail kind=$1 exit_code=$2 completed_at=$3 status=failed if [[ "$exit_code" == 0 || ( "$kind" == plan && "$exit_code" == 2 ) ]]; then status=succeeded fi jq -n \ --arg projectId "$SHIPD_PROJECT_ID" \ --arg environmentId "$SHIPD_ENVIRONMENT_ID" \ --arg kind "$kind" \ --arg status "$status" \ --arg completedAt "$completed_at" \ --arg runUrl "$CI_RUN_URL" \ --arg exitCode "$exit_code" ' {$projectId, $environmentId, $kind, $status, $completedAt, $runUrl} + (if $kind == "plan" and $status == "succeeded" then {hasChanges: ($exitCode == "2")} else {} end) ' | curl --fail-with-body --silent --show-error \ --header "Authorization: Bearer $SHIPD_TERRAFORM_REPORT_TOKEN" \ --header "Content-Type: application/json" \ --data-binary @- https://api.useshipd.com/api/v1/rpc/terraform/report ``` Use `terraform plan -detailed-exitcode` when reporting plans. Exit code `0` means no changes, `2` means changes, and `1` means the plan failed. [Terraform plan command reference](https://developer.hashicorp.com/terraform/cli/commands/plan#other-options) ```bash theme={null} plan_exit=0 terraform plan -input=false -detailed-exitcode || plan_exit=$? completed_at=$(date -u +%Y-%m-%dT%H:%M:%SZ) bash report-terraform-run.sh plan "$plan_exit" "$completed_at" || exit $? if [ "$plan_exit" -ne 2 ]; then exit "$plan_exit" fi ``` After your CI runs apply, call the script with `apply`, the apply exit code, and its completion timestamp. Keep the original `completedAt` if you retry a report. The endpoint returns `data.recorded: false` when it already has a report for that operation with an equal or newer completion timestamp. The **Terraform runs** panel shows the latest completed plan and apply for the selected environment, each with its CI run link. Results are marked **Stale** after seven days. Apply status describes the reported run at completion. ## Next * [Terraform provider reference](/reference/terraform) for configuration, resources, data sources, and lifecycle behavior. * [Define flags in code](/config-as-code/define-flags) after provisioning your project and environment. * [Service account tokens](/reference/service-account-tokens) for scopes and binding rules. # Migration guides Source: https://docs.useshipd.com/migrations Breaking-change migrations for public SDK, CLI, and configuration contracts. ## Overview Each breaking release has its own guide with before/after examples and roll-out and roll-back steps. Before upgrading a `0.x` minor version, read the [Changelog](/changelog): compatibility is not guaranteed across `0.x` minor releases. | Guide | Package | From → to | Changes | | - | - | - | - | | [Upgrade to shipdit 0.4](/migrations/shipdit-0-4) | `shipdit` | 0.3.x → 0.4.0 | `endpoint` and `streamEndpoint` removed; server `identify()` is telemetry-only; `close()` returns a promise; stricter timestamp targeting | | [Upgrade the Convex component to 0.2](/migrations/convex-0-2) | `@shipdit/convex` | 0.1.x → 0.2.0 | `SHIPD_EDGE_URL` removed; stricter timestamp targeting | # Upgrade the Convex component to 0.2 Source: https://docs.useshipd.com/migrations/convex-0-2 Migrate @shipdit/convex from 0.1.x to 0.2.0: removed SHIPD_EDGE_URL and stricter timestamp targeting. ## Overview Affects the Convex component (`@shipdit/convex`) when upgrading from 0.1.x to 0.2.0. See the [Convex changelog](/changelog/convex) for the full release notes. ## 1. Remove `SHIPD_EDGE_URL` Delete `SHIPD_EDGE_URL` from `defineApp({ env })` and from the `env` passed to `app.use(shipd, …)` for every mounted instance. The component now fetches from `https://edge.useshipd.com`. ```ts convex/convex.config.ts theme={null} const app = defineApp({ env: { SHIPD_SDK_KEY: v.string(), SHIPD_WEBHOOK_SECRET: v.string(), }, }); app.use(shipd, { name: "shipd", httpPrefix: "/shipd", env: { SHIPD_SDK_KEY: app.env.SHIPD_SDK_KEY, SHIPD_WEBHOOK_SECRET: app.env.SHIPD_WEBHOOK_SECRET, }, }); ``` Then remove the deployment value: ```bash theme={null} npx convex env remove SHIPD_EDGE_URL ``` > [!WARNING] > > `SHIPD_UNSAFE_EDGE_URL` exists for shipd development and test environments. Don't set it in > production: the URL you pass receives your SDK key. ## Check timestamp rules before upgrading Ordered comparisons (`gt`, `gte`, `lt`, `lte`) now accept `YYYY-MM-DD` (midnight UTC), or a date-time with a required `Z` or `±hh:mm` zone. Zone-less date-times, lenient formats, and impossible dates compare as strings. Audit flag rules, audience conditions, and the attributes your application sends: ```ts theme={null} // Before: implicit local timezone const cutoff = "2026-01-02T10:00:00"; // After: choose the timezone the rule intended const cutoff = "2026-01-02T10:00:00Z"; // UTC // Or "2026-01-02T10:00:00-08:00" for a fixed UTC-08:00 offset ``` Don't append `Z` unless the original value meant UTC. Correct impossible dates such as `2026-02-30`, and send the same explicit timestamp format in evaluation attributes. See [How values compare](/flags/targeting#how-values-compare). > [!WARNING] > > Dashboard preview adopts this grammar on dashboard deploy. Production evaluation changes only when > you upgrade `shipdit` or `@shipdit/convex`; the edge does not evaluate rules. An older SDK can therefore > disagree with preview before you upgrade. Saving a flag or audience with an invalid date-looking > ordered value returns an API warning and shows a dashboard warning, while still allowing string rules. ## Roll out and roll back Upgrade the package and edit `convex.config.ts` in the same deploy. To roll back, pin `@shipdit/convex@0.1.3` and restore `SHIPD_EDGE_URL` in `convex.config.ts` and the deployment env. # Upgrade to shipdit 0.4 Source: https://docs.useshipd.com/migrations/shipdit-0-4 Migrate the TypeScript SDK from 0.3.x to 0.4.0: removed endpoint options, telemetry-only server identify(), an awaitable close(), and timestamp targeting. ## Overview Affects the TypeScript SDK (`shipdit`) when upgrading from 0.3.x to 0.4.0. Go and the CLI are unaffected. See the [TypeScript SDK changelog](/changelog/typescript-sdk) for the full release notes. ## 1. Remove `endpoint` and `streamEndpoint` `createClient` throws if either option is set. Delete `endpoint` when using the default shipd edge. Replace the default shipd `streamEndpoint` with `stream: true`. For a custom gateway, also move its URL to `overrides.streamEndpoint` as shown below. ```ts theme={null} // Before createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, endpoint: "https://edge.useshipd.com", streamEndpoint: "https://ws.useshipd.com", }); // After createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, stream: true, }); ``` For a custom gateway, preserve its URL: ```ts theme={null} createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, stream: true, overrides: { streamEndpoint: process.env.SHIPD_WS_URL! }, }); ``` If you didn't pass `streamEndpoint`, omit `stream`; the client keeps polling every 30 seconds. Remove `SHIPD_EDGE_URL` and `SHIPD_WS_URL` only if you used the default shipd endpoints and no other code reads them. Keep `SHIPD_WS_URL` when using it for a custom gateway. > [!WARNING] > > `overrides.unsafeEndpoint` exists for shipd development and test environments. Don't set it in > production: the URL you pass receives your SDK key. ## 2. Pass context instead of calling `identify()` on servers On the server client (`shipdit`), `identify()` now only records an event. Code that relied on it to set the user for later checks must pass context on each call: ```ts theme={null} // Before shipd.identify({ userId: user.id, traits: { plan: user.plan } }); shipd.isEnabled("new-checkout"); // After const context = { userId: user.id, attributes: { plan: user.plan } }; shipd.isEnabled("new-checkout", context); ``` For a fixed identity, such as a single-user script, pass it once with `createClient({ context })`. Server `reset()` is a no-op and preserves the shared anonymous id. Browser clients (`shipdit/client`) still set the identity with `identify()` until `reset()`. ## 3. Optionally await `close()` `close()` now returns a promise that resolves after pending events are delivered, delivery fails, or the timeout passes (5 seconds by default). Existing calls keep working. Await it before exiting to give pending events time to flush: ```ts theme={null} process.on("SIGTERM", async () => { // Keep recording while active requests drain; bound long-lived requests. await new Promise((resolve) => { const deadline = setTimeout(() => { server.closeAllConnections(); resolve(); }, 5_000); server.close(() => { clearTimeout(deadline); resolve(); }); }); await shipd.close(); }); ``` ## 4. Check timestamp rules before upgrading Ordered comparisons (`gt`, `gte`, `lt`, `lte`) now accept `YYYY-MM-DD` (midnight UTC), or a date-time with a required `Z` or `±hh:mm` zone. Zone-less date-times, lenient formats, and impossible dates compare as strings. Audit flag rules, audience conditions, and the attributes your application sends: ```ts theme={null} // Before: implicit local timezone const cutoff = "2026-01-02T10:00:00"; // After: choose the timezone the rule intended const cutoff = "2026-01-02T10:00:00Z"; // UTC // Or "2026-01-02T10:00:00-08:00" for a fixed UTC-08:00 offset ``` Don't append `Z` unless the original value meant UTC. Correct impossible dates such as `2026-02-30`, and send the same explicit timestamp format in evaluation attributes. See [How values compare](/flags/targeting#how-values-compare). > [!WARNING] > > Dashboard preview adopts this grammar on dashboard deploy. Production evaluation changes only when > you upgrade `shipdit` or `@shipdit/convex`; the edge does not evaluate rules. An older SDK can therefore > disagree with preview before you upgrade. Saving a flag or audience with an invalid date-looking > ordered value returns an API warning and shows a dashboard warning, while still allowing string rules. ## Roll out and roll back Upgrade and deploy as one change: the new options require 0.4.0, and keeping the removed `endpoint` or `streamEndpoint` options throws on 0.4.0. To roll back, pin `shipdit@0.3.1` and restore `endpoint` (and `streamEndpoint`, if you streamed). # Install shipd agent skills Source: https://docs.useshipd.com/operations/agent-skills Teach your coding agent to implement features behind shipd flags, sync definitions through CI, and manage rollout through MCP. ## Overview Install shipd's agent skills to give your coding agent reusable workflows for flag implementation, CI synchronization, and rollout. The skills are maintained in the public [shipd-skills repository](https://github.com/alasti-company/shipd-skills). ## Install the skills You need Node.js with `npx` and a coding agent that supports skills. Run this command from your application repository, then select the skills and agent you use: ```bash theme={null} npx skills add alasti-company/shipd-skills ``` The installer configures the selected skills for your agent. See the [Skills CLI documentation](https://skills.sh/docs/cli) for installation options. ## Choose a workflow | Skill | Use it to | | - | - | | `shipd-feature-flags` | Add flag definitions, generate types, and implement a feature with a safe control path. | | `shipd-ci` | Check flag drift in pull requests and synchronize definitions on merge using the CLI. | | `shipd-rollout` | Inspect targeting, publish drafts, check approvals, and revert exposure through MCP. | Ask your agent to implement a feature: ```text theme={null} Use shipd-feature-flags to implement the new checkout behind a boolean flag named new-checkout. Keep the existing checkout when the flag is false, generate flag types, and verify both paths. Keep the flag off in production. ``` Set up flag synchronization: ```text theme={null} Use shipd-ci to add flag validation to our pull requests and synchronize our web-app project's definitions to production on merge. Keep release flags on their control values and report drafts or pending approvals. ``` Manage a scoped rollout: ```text theme={null} Use shipd-rollout to inspect new-checkout in web-app's production environment. Enable it only for our existing internal-users audience. Preserve other rules and report whether the change is published or waiting for approval. ``` ## Connect your account Skills provide instructions. To read or change remote flags, [connect your agent to shipd through MCP](/operations/connect-an-agent). MCP requires a Pro, Teams, or Enterprise organization; your current role, project access, and approval policies still apply. For CLI synchronization, configure the CLI and [service account tokens for CI](/config-as-code/ci). Installing skills does not create credentials or authorize production changes. ## Check the result Ask your agent to report the flag key, project, environment, validation results, and current state. Local code changes, saved drafts, pending approvals, and published configuration are separate outcomes. Deploying code does not by itself enable a flag. [Release records](/reference/releases) add a durable plan, action history, and evidence ledger for manually tracking a release (unreleased pending merge and deployment). They do not turn a recorded action into a successful deployment, published flag change, approval, or exposure change. Rollout guidance runs during your agent session. For continuous Sentry guard checks and automatic rollback, use the feature-gated [progressive controller](/reference/config#signal-driven-rollout). The skills themselves do not run background monitoring; Axiom and PostHog signal providers are not included in this version. See [MCP tools and request guarantees](/reference/mcp) for available operations. # Review production changes Source: https://docs.useshipd.com/operations/approvals Require another person to review a production flag change before it goes live. ## Overview In this guide you require a second person to review production changes to flags such as `new-checkout`. An approval policy holds the requested state separately from active configuration; SDKs keep evaluating the active snapshot until enough eligible reviewers approve and you publish the draft. **Prerequisites:** an Enterprise plan to create a policy, and the admin or owner role to manage it. Existing policies keep protecting changes if your plan changes, and reviews, withdrawals, and policy management remain available for existing workflows. ## Require production review **1. Create the policy** Open **Settings → Organization → Approvals → Policies** and choose **New policy**. Match production environments, require one approval, and leave **Allow self-approval** off. Lower priority numbers run first; the first matching enabled policy governs a change. **2. Submit a change** An editor changes `new-checkout` in production and clicks **Save environment**. The dashboard returns a pending request; the active flag and SDK snapshot stay unchanged. You need enough eligible reviewers other than the requester before a request can be created. **3. Review the immutable change** Reviewers find their assignments in the **Approvals** inbox. These are durable in-app notifications; shipd does not send approval email notifications. Inspect the requested state, then approve or reject it. Only currently authorized, assigned users can review. Management keys and service account tokens cannot approve. **4. Publish or withdraw** The final required approval makes the draft ready to publish. Open the flag’s **Across environments** table and click **Publish changes**. Publication applies targeting and records audit evidence together. The requester can cancel a pending request to withdraw it; authorized admins and owners can also cancel. Submit a new request to change the requested state. Votes never transfer to replacement requests. A request made through a creator-bound management key still belongs to that human for self-approval and withdrawal. Service accounts retain independent automation authority, but their token issuer is excluded from approving that token’s requests when self-approval is forbidden. Credentials without a known human issuer cannot submit under a no-self-approval policy; rotate the key or token. ## Requests that need resubmission Requests expire seven days after creation. Expiry is enforced whenever workflows are read or decided and before new submissions; a queued request cannot be applied after its deadline. Any approval-policy creation, update, or deletion invalidates existing pending requests in the organization. Changes to the flag definition, target state, production classification, or audience revisions in the project also make old requests stale at application. This conservatively includes audience changes unrelated to the requested rule. Resubmit against the new configuration. Identical decision retries return the committed outcome without another vote or audit event. If applying the final approval fails, that final vote and application roll back together; retry the same decision. Previously committed votes remain available, and only currently eligible reviewers count toward the threshold. ## Push from CI ```bash Terminal theme={null} SHIPD_API_KEY=shipd_sa_… shipd push --ci --json --project web-app --env production ``` A push containing queued requests exits with code `5` and JSON with `outcome: "pending_approval"` and `approvalRequests`. This means the requested defaults are not yet active. Save the request IDs and arrange human review; do not deploy on the assumption that the new defaults are live. `--ci`, `--yes`, and `--force` do not bypass approval. A repeated push with an existing pending request returns a conflict (exit code `3`). After review, publish the draft from the dashboard, then pull or diff again to inspect active state. Unprotected production defaults are saved as drafts; protected defaults wait for approval. Unprotected non-production defaults apply immediately. ## Operations outside the request model Requests currently represent flag environment state: enabled state, rules, and fallthrough. Definition changes, creation/archival, audience changes, environment production transitions, and project/environment archival are blocked when they affect a policy-protected environment. A config push containing such an unsupported operation fails as a whole, including when pushed against staging but affecting global definitions. Client labels and last-writer attribution never exempt a mutation. Rollout-increase policies use conservative exposure bounds and can require review when targeting overlap cannot be established precisely. Related: [Approval workflows](/reference/approvals) · [CLI](/reference/cli) · [Sync flags in CI](/config-as-code/ci) · [View the audit log](/operations/audit-log). # View the audit log Source: https://docs.useshipd.com/operations/audit-log Filter, inspect, and export organization audit events from the dashboard. ## Overview Sensitive changes create append-only audit events. In this guide you filter, inspect, export, and stream those events. Search is available on Teams and Enterprise; Enterprise also supports CSV/JSON export and external destinations. ## Open the log **1. Go to Settings → Audit log** You need `audit.read`. Destinations and retention need `organization.update`. **2. Narrow the list** Search an exact resource such as `flag:new-checkout` and click **Search**. Combine the visible filters, or open **Filters** for actor type, environment, flag key, and dates. Use **Clear filters** to reset the search. Date bounds use UTC; displayed event times use your browser's timezone. | Filter | Matches | | - | - | | Actor | Organization member | | Actor type | User, API key, service account, or system | | Resource search | Exact resource, such as `flag:new-checkout` | | Action | Distinct action names such as `flag.updated` | | Project / environment | Denormalized ids on the event | | Flag key | Resource `flag:` | | Source | Dashboard, CLI, API, SDK, MCP, or system | **3. Open an event** Click a row, or tab to it and press Enter, to see before/after JSON, request id, IP, user agent, and reason when present. `shipd push --force` records reason **Forced CAS override**. ## Export a snapshot Use **Export** on the events tab for CSV or JSON of the current filters (up to 10,000 rows). Use **Export next batch** to download older matches when the export is truncated. ```csv CSV theme={null} id,createdAt,action,resource,actorType,source 1042,2026-08-27T07:12:00.000Z,flag.updated,flag:new-checkout,user,cli ``` ```json JSON theme={null} { "id": 1042, "action": "flag.updated", "resource": "flag:new-checkout", "source": "cli", "reason": "Forced CAS override" } ``` ## Retention and destinations On **Export & retention**: * Request 7 days through 7 years, or forever. The effective value is capped by your entitlement (normally 7 days on Teams and 60 days on Enterprise); forever applies only to an unlimited entitlement. Events are never edited; expiry is the only delete. * Add a **webhook** (HMAC-SHA256 over `timestamp.eventId.body` in `x-shipd-signature`; signing secret is at least 16 characters and generated for you), a logging provider (**Splunk HEC**, **Datadog logs**, **Axiom**, **Better Stack**, or **JSON endpoint**), or object storage (**Amazon S3**, **Cloudflare R2**, or **S3-compatible storage**). Events are delivered automatically after the change is saved. Test a destination before you rely on it. Copy the webhook signing secret when you create the destination — it is shown once. Rotate it later from Edit; the current value is never returned again. SIEM tokens and S3 keys stay hidden after create. Related: [Audit log](/reference/audit-log) for event fields and destination formats · [Resolve a push conflict](/config-as-code/conflicts). # Connect an agent to shipd Source: https://docs.useshipd.com/operations/connect-an-agent Authorize Codex, Claude Code, Cursor, or another remote MCP client to manage flags, audiences, projects, and environments. ## Overview Connect your coding agent to shipd using the Model Context Protocol (MCP). You need a Pro, Teams, or Enterprise organization and a client supporting Streamable HTTP with browser OAuth authorization. The server endpoint is `https://mcp.useshipd.com/mcp`. For reusable implementation, CI, and rollout workflows, [install shipd agent skills](/operations/agent-skills). Skills provide instructions; the MCP connection below provides account access. ## Add shipd to your client ```bash Codex theme={null} codex mcp add shipd --url https://mcp.useshipd.com/mcp codex mcp login shipd ``` ```bash Claude Code theme={null} claude mcp add --transport http --scope user shipd https://mcp.useshipd.com/mcp ``` ```json Cursor — .cursor/mcp.json theme={null} { "mcpServers": { "shipd": { "url": "https://mcp.useshipd.com/mcp" } } } ``` In Claude Code, run `/mcp` and authenticate shipd. In Cursor, open the server's authentication action. Follow the browser sign-in flow. Official client instructions: [Codex](https://developers.openai.com/codex/mcp), [Claude Code](https://code.claude.com/docs/en/mcp), [Cursor](https://cursor.com/docs/mcp). ## Authorize access Select one organization and choose **Read and write** or **Read only**. Read and write is selected by default. Choose all current and future accessible projects, or select individual projects. Click **Allow read and write access** or **Allow read-only access**. You may be asked to sign in again before authorizing a connection. The agent acts as you. Your current role, project access, production permissions, quotas, and [approval policies](/operations/approvals) apply to every operation. A write connection does not grant permissions your role lacks. Ask your agent: ```text theme={null} List my projects and environments. In web-app, create a boolean flag named new-checkout, then read its current development state and propose targeting paid users. Keep the idempotency key unchanged when retrying a mutation. ``` Pending changes return an approval request and a dashboard review link. Review the exact change in shipd; the agent cannot approve it or change approval policies. ## Manage connections Open **Settings → Connected apps** to inspect access and revoke a connection. Each connection expires after 30 days without use or 90 days total. Sign in and authorize again after expiry. **Related:** [MCP tools and request guarantees](/reference/mcp) · [Access control](/enterprise/access-control) # Publish a snapshot Source: https://docs.useshipd.com/operations/publish-a-snapshot Retry publication when a saved flag change has not reached your application. ## Overview Publish targeting drafts with **Publish changes** in the flag’s **Across environments** table. Production saves and approval decisions leave the live snapshot unchanged until that step. Non-production saves publish immediately unless review is required. If a snapshot publication failed, use the recovery command below to retry the environment’s live configuration. Retrying does not apply drafts, change flag definitions, or bypass approvals. ## Before you publish Follow [Troubleshooting](/resources/troubleshooting) first: confirm the project, environment, SDK key, and approval status. A draft that requires review must be approved and then published from the environment plan before its change can reach SDKs. You need the `snapshot.publish` permission, available to editors, admins, and owners. Authenticate with `shipd login` or a service account token with that scope and access to the target environment. ## Retry publication ```bash Terminal theme={null} shipd snapshots publish --project web-app --env production ``` After the command succeeds, allow the SDK to refresh and check the flag again. A client with polling disabled needs an update notification or a manual refresh. If publication fails again or the value is still stale, contact [support](mailto:hey@useshipd.com) with the project, environment, error, and request ID if available. Do not send credentials. For publication status and additional recovery commands, see the [CLI reference](/reference/cli#shipd-snapshots-outbox). # Receive customer events Source: https://docs.useshipd.com/operations/receive-customer-events Create an endpoint, publish with a scoped credential, and verify durable event receipt. ## Overview Connect a public HTTPS receiver, publish an application event, and inspect its delivery. You need a beta-enabled organization, an existing project and environment, project admin or owner access for setup, and Node.js 24 or later for the receiver example. ## Create the endpoint Open your project’s **Settings → Webhooks** (also available through **Integrations → Manage webhooks**). Select the environment, click **Add endpoint**, enter a name and your public HTTPS `/shipd` URL, then click **Create endpoint**. Private networks, redirects, credentials in URLs, and URL fragments are unsupported. Select **All event types** before your first publish, or choose previously published event types. The selector uses retained event history; click **Refresh events** to load new types. Existing subscriptions remain selectable after history expires. To subscribe to a specific type before publishing it, use `eventWebhook/create` with `eventTypes: ["order.completed"]` in the [API reference](/reference/customer-events#api). Save the signing secret immediately in your secret manager: it is shown once. This secret verifies incoming requests; it is separate from the credential used to publish events. ## Run a durable receiver Use the complete [Node.js receiver example](https://github.com/alasti-company/useshipd.com/tree/main/examples/webhook-receiver). From its directory: ```sh Run the receiver theme={null} export SHIPD_WEBHOOK_SECRET='your endpoint signing secret' INBOX_DB=./inbox.sqlite PORT=3000 node receiver.mjs ``` Expose `/shipd` through your HTTPS reverse proxy, preserving the exact request body. Keep the SQLite file on durable storage. The example verifies the raw bytes before JSON parsing, rejects timestamps outside five minutes, compares signature bytes in constant time, and accepts the previous-signature header during rotation. It commits a unique event-ID inbox row before returning `204`; duplicate deliveries return `204` without creating another job. Process inbox rows asynchronously. Apply business effects idempotently and mark completion transactionally; use event IDs as idempotency keys for external services. See the example README for storage and worker requirements. ## Send a test Send a test from the endpoint’s actions, then open **Delivery history**. A queued test or HTTP `202` receipt means acceptance, not a successful HTTP delivery. Wait for **delivered** and inspect the HTTP attempt result. History refreshes every five seconds while open. The receiver should contain one `shipd.webhook.test` event with `test: true`. ## Create a publish-only credential Under organization **Settings → Service accounts**, create an account and choose **Create token**. Grant only `customer_event:publish` (API scopes: `{ "customer_event": ["publish"] }`), bind it to this project and environment, and set an expiry. Store the `shipd_sa_…` token on your server. SDK keys cannot publish; never expose the publisher credential or signing secret in browser code. See [service account setup](/enterprise/service-accounts). ## Publish and inspect Set `SHIPD_API_URL=https://api.useshipd.com`, `SHIPD_PUBLISH_TOKEN` to the scoped token, and `SHIPD_ENVIRONMENT_ID` to your environment ID. ```sh Publish an order event theme={null} curl --fail-with-body "$SHIPD_API_URL/api/v1/rpc/event/publish" \ -H "Authorization: Bearer $SHIPD_PUBLISH_TOKEN" \ -H 'Content-Type: application/json' \ -H 'Idempotency-Key: order-123-completed' \ --data "{\"environmentId\":\"$SHIPD_ENVIRONMENT_ID\",\"type\":\"order.completed\",\"data\":{\"orderId\":\"ord_123\"}}" ``` The `202` response contains `data.eventId`, `data.matchedEndpoints`, and `data.acceptedAt`. Retry the same logical publish with the same key and body to get the original receipt. A changed body under that key returns `409`. Publish keys last 24 hours; keep your own durable producer record for longer reconciliation. Find the event in **Delivery history**, inspect attempts, and verify its ID in the receiver inbox. Repeating the publish must return the same event ID; repeating delivery must leave a single inbox row. `matchedEndpoints: 0` is accepted without delivery units: no receiver is called, and adding a subscription later does not deliver that old event. It still uses ingestion capacity. Delivery is at least once and unordered. A receiver `2xx` confirms storage, not completion of your business workflow. Use event versions or reconcile current application state when processing out of order. See [delivery guarantees, retries, retention, and limits](/reference/customer-events). ## Inspect through the API Use a separate read-authorized server credential (`SHIPD_INSPECTION_TOKEN`), rather than widening the publish-only token. Set `SHIPD_EVENT_ID` from the publish receipt and `SHIPD_DELIVERY_ID` from the delivery list. ```sh Inspect delivery and attempts theme={null} curl --fail-with-body "$SHIPD_API_URL/api/v1/rpc/eventWebhook/deliveries" \ -H "Authorization: Bearer $SHIPD_INSPECTION_TOKEN" \ -H 'Content-Type: application/json' \ --data "{\"environmentId\":\"$SHIPD_ENVIRONMENT_ID\",\"eventId\":\"$SHIPD_EVENT_ID\"}" curl --fail-with-body "$SHIPD_API_URL/api/v1/rpc/eventWebhook/attempts" \ -H "Authorization: Bearer $SHIPD_INSPECTION_TOKEN" \ -H 'Content-Type: application/json' \ --data "{\"environmentId\":\"$SHIPD_ENVIRONMENT_ID\",\"deliveryId\":\"$SHIPD_DELIVERY_ID\"}" ``` Results appear under `data`; delivery status is `pending`, `delivered`, `failed`, or `cancelled`. Attempts contain HTTP status, duration, and sanitized errors, without customer payloads. Use `eventWebhook/usage` to check effective organization-wide limits; it additionally requires billing-read access. ## Operate the endpoint Use **Pause endpoint** to stop queued delivery and **Resume endpoint** to resume retained work. Delete cancels queued work; in-flight requests may still finish. URLs are immutable: create and test a replacement endpoint, then retire the old one. If your endpoint allowance prevents overlap, coordinate the interruption before deleting the old endpoint. Use **Rotate signing secret**, save the new secret once, and update the receiver within the 24-hour overlap. During overlap the old receiver can verify `x-shipd-signature-previous`. A second rotation is unavailable until the overlap ends. Manual redelivery of completed or failed events creates a new delivery for the same event ID and reserves another delivery unit; automatic retries are included. Test deliveries and their redeliveries are free. Only retained events can be redelivered, so recover failures before retention expires. Project transfer removes endpoints and customer payloads before ownership changes. Configure new endpoints in the destination organization; source usage stays charged. For disabled-rollout and archived-environment behavior, see the [reference](/reference/customer-events). # Quickstart Source: https://docs.useshipd.com/quickstart Add a flag to a TypeScript or Go app and turn it on from the dashboard without redeploying. ## Overview You'll build this: ```ts TypeScript theme={null} if (shipd.isEnabled("new-checkout")) { // new checkout } ``` ```go Go theme={null} if client.IsEnabled("new-checkout", shipd.EvaluationContext{}) { // New checkout. } ``` Then you'll flip `new-checkout` on in the dashboard and watch your running app change — no redeploy. **You need:** a [shipd account](https://app.useshipd.com) and Node.js 22.12+ for the shared CLI. Go applications also need Go 1.23+. TypeScript uses Node's built-in WebSocket for streaming; Go uses polling. Signing up creates an organization with one project and a `production` environment. ## 1. Install ```bash TypeScript theme={null} mkdir shipd-quickstart && cd shipd-quickstart npm init -y && npm pkg set type=module npm install shipdit npm install -g @shipdit/cli mkdir -p src .shipd ``` ```bash Go theme={null} mkdir shipd-quickstart && cd shipd-quickstart go mod init example.com/shipd-quickstart go get github.com/alasti-company/shipd-go npm install -g @shipdit/cli ``` ## 2. Log in ```bash theme={null} shipd login ``` Your browser opens. Pick your organization, your project, and the `production` environment, then approve. The CLI remembers that choice, so later commands don't need `--project` or `--env`. ## 3. Define a flag Create `shipd.config.ts` for TypeScript or `shipd.config.go` for Go: ```ts TypeScript theme={null} // shipd.config.ts import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, description: "Redesigned checkout flow", }, }); ``` ```go Go theme={null} // shipd.config.go package main import "github.com/alasti-company/shipd-go/config" var Config = config.ShipdConfig{ "new-checkout": { Type: "boolean", Default: false, Description: "Redesigned checkout flow", }, } ``` The CLI reads these files directly and selects the matching SDK language automatically. No project settings are required. See [Go config reference](/reference/config#go-shipdconfig). ## 4. Push it ```bash TypeScript theme={null} shipd push ``` ```bash Go theme={null} shipd push ``` ```text theme={null} Warning: 2 remote flag(s) not in local config (pass --prune to archive): - welcome - beta-features Plan: + create flag "new-checkout" Apply this plan? [y/N] y Applied 1 change(s). Wrote types for 1 flag(s) to /…/shipd-quickstart/src/generated/flags.ts ``` Type `y` to apply. The flag now exists in shipd. TypeScript output goes to `src/generated/flags.ts`; Go output goes to `internal/flags/flags_gen.go`. The warning lists the demo flags that came with your new project. `shipd push` never removes flags you didn't list, so you can ignore it. ## 5. Copy an SDK key In the [dashboard](https://app.useshipd.com), open your project → **SDK keys** → **Create SDK key**. Choose the **server** key type and copy the key (it's shown once). ```bash theme={null} export SHIPD_SDK_KEY=shipd_sdk_server_… ``` ## 6. Read the flag ```ts TypeScript theme={null} // src/index.ts import { createClient } from "shipdit"; import type { FlagDefinitions } from "./generated/flags"; const shipd = createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, stream: true, defaults: { "new-checkout": false }, }); await shipd.ready(); setInterval(() => { console.log("new-checkout:", shipd.isEnabled("new-checkout")); }, 1000); ``` ```go Go theme={null} // main.go package main import ( "context" "log" "os" "os/signal" "syscall" "time" "example.com/shipd-quickstart/internal/flags" shipd "github.com/alasti-company/shipd-go" ) func main() { client, err := shipd.New(shipd.Options{ SDKKey: os.Getenv("SHIPD_SDK_KEY"), Defaults: flags.Defaults(), }) if err != nil { log.Fatal(err) } defer func() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if err := client.Shutdown(ctx); err != nil { log.Printf("shipd events: %v", err) } }() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) if err := client.Ready(ctx); err != nil { log.Printf("using defaults: %v", err) } cancel() shutdown, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case <-shutdown.Done(): return case <-ticker.C: log.Printf("new-checkout: %v", flags.NewCheckout(client, shipd.EvaluationContext{})) } } } ``` ```bash TypeScript theme={null} npx tsx src/index.ts ``` ```bash Go theme={null} go run . ``` ```text theme={null} new-checkout: false new-checkout: false ``` Leave it running. ## 7. Flip it in the dashboard Open **Flags** → **new-checkout**. In the **Environment** section, set **Fallthrough** to `true` and click **Save environment**. TypeScript with streaming updates within a second or two. Go updates on the next poll (up to 30 seconds by default): ```text theme={null} new-checkout: false new-checkout: true ``` That's it. Your code checked a flag, and you changed its value remotely without redeploying. > [!NOTE] > > In the environment you push to, the definition's default sets the fallthrough. If you run `shipd push` now, it will offer to set the fallthrough back to `false`. Change TypeScript `default` or Go `Default` to `true` first. `shipd pull` copies the dashboard value into your TypeScript or Go definition file. See [Push, pull, and diff](/config-as-code/sync). ## What just happened * Your TypeScript or Go definitions are the source of truth for **which flags exist**. The CLI reads Go source directly; `shipd push` synced the definitions. * The dashboard controls **what each flag serves** in each environment. * The SDK downloaded a **snapshot** of your flags and evaluated `isEnabled` in memory. TypeScript streaming clients refresh after a WebSocket notification; Go refreshes on its next poll. * If shipd is unreachable, the SDK keeps the last valid snapshot, or serves configured defaults if no snapshot has loaded. Flag checks never throw and never make network requests. The five-minute version of this model is [Core concepts](/core-concepts). ## Next > [card] [Core concepts](/core-concepts) > > Projects, environments, snapshots, and local evaluation on one page. > [card] [Target users](/flags/targeting) > > Turn a flag on for one user, a plan, or an email domain. > [card] [Roll out to 10%](/flags/percentage-rollouts) > > Sticky percentage rollouts. > [card] [Add shipd to your stack](/sdks/node) > > TypeScript, Go, browser, React, Next.js, and Convex. # Approval workflows Source: https://docs.useshipd.com/reference/approvals Policy scope, request states, reviewer eligibility, audit events, and config push outcomes. ## Overview Approval enforcement runs on the server for dashboard, API, CLI, and service-account mutations. SDK evaluation uses only active configuration. A notification or supplied request ID never authorizes a write. ## Policy matching | Field | Meaning | | - | - | | Organization | Policies and requests belong to one organization. | | `projectIds` | Optional project scope; omitted or empty means all projects in the organization. | | `environmentIds` | Optional environment scope within the selected projects. | | `environmentProduction` | Match production (`true`) or non-production (`false`); omitted matches either. | | `minRolloutIncrease` | Minimum increase in percentage points, using conservative targeting bounds. | | `priority` | Lower numbers run first; the first enabled matching policy wins. | | `requiredApprovals` | Number of distinct eligible users required, from 1 to 20. | | `reviewerRoles`, `reviewerTeamIds` | Union of selected roles and teams, restricted to users currently authorized to review the project. | | `allowSelfApproval` | Whether the responsible human requester or credential issuer can approve. Defaults to false. | All project, environment, and team references must belong to the organization. Policies apply across dashboard, CLI, API, and service-account changes; they cannot be restricted to a particular client or last writer. Policies are frozen into requests. Editing, deleting, disabling, or adding any policy invalidates pending requests in the organization rather than changing the meaning of recorded votes. ## Request lifecycle | Status | Meaning | | - | - | | `pending` | Active state is unchanged. Votes are collected against immutable requested state. | | `approved` | Review is complete; publish the saved draft when present. Legacy approved requests without a saved draft were applied on approval. Pending requests carried over from the previous workflow now also require explicit publication. | | `rejected` | A reviewer rejected the request; it cannot be applied. | | `cancelled` | The requester withdrew it or an authorized user cancelled it. | | `stale` | Policy or resource revisions changed; submit a replacement request. | | `expired` | The seven-day deadline elapsed; submit a replacement request. | There is at most one pending request per flag/environment pair. To revise intent, cancel and resubmit. Identical decision retries are idempotent; changing the comment or decision of an existing vote is a conflict. Terminal requests cannot be reopened. Review authorization is checked at decision time. Removed, banned, demoted, or otherwise ineligible users cannot review, and their earlier votes do not count toward application. Reviewer assignments form the durable inbox notification; repeated reads do not duplicate it. Approval emails are not sent. ## Config and CLI outcomes | Outcome | CLI exit | Meaning | | - | - | - | | Applied/no changes | `0` | Definitions and unprotected non-production targeting are active, or there was no drift. | | Draft saved | `0` | Production targeting is saved; JSON includes `drafts` and `outcome: "draft"`. Publish from the dashboard. | | Pending approval | `5` | At least one default change queued; JSON includes `approvalRequests` and `outcome: "pending_approval"`. | | Conflict | `3` | Examples: existing pending request, stale versions, or an unsupported operation affecting a protected environment. | `--force` bypasses ordinary sync version conflicts only. It cannot bypass policy, immutable approval revisions, or review authorization. Non-interactive confirmation flags do not constitute approval. Mixed default-only pushes may apply some unprotected defaults and queue others; pushes with unsupported protected definition operations roll back entirely. ## Audit evidence Request creation, approvals, rejection, cancellation, expiration, policy invalidation, and application produce per-request audit events. Publishing an approved draft also produces the linked `flag.environment.updated` event. Decision comments are included subject to audit redaction. Events and export deliveries commit with their mutation; duplicate decisions do not append duplicate events. Audit evidence remains subject to its retention policy after organization deletion. See [Audit log](/reference/audit-log#retention) for retention and deletion rules. Related: [Review production changes](/operations/approvals). # Audit log Source: https://docs.useshipd.com/reference/audit-log Event fields, export limits, webhook signatures, and destination delivery. ## Overview Use **Settings → Audit log** to inspect, export, and stream the history of changes to your organization. Events are append-only. Membership, invitation, and team events can appear shortly after the change. ## Event fields | Field | Meaning | | - | - | | `id` | Identity cursor, newest first | | `organizationId` | Organization that owns this event, included in both export formats | | `actorId` / `impersonatorId` | Acting identity and, when applicable, the impersonating operator | | `action` | `flag.updated`, `member.invited`, `team.created`, `project.teams.updated`, … | | `resource` | `flag:new-checkout` | | `actorType` | `user`, `api_key`, `service_account`, or `system` | | `tokenId` | Service-account token that performed the mutation; `null` otherwise | | `source` | `dashboard`, `cli`, `api`, `sdk`, `system` | | `projectId` / `environmentId` | Project and environment identifiers remain available for filtering after archive | | `before` / `after` | JSON snapshots of the mutation | | `requestId` / `correlationId` | HTTP request ids when the write came from the API | | `ipAddress` / `userAgent` | Client provenance | | `reason` | Optional human note (`Forced CAS override` on `shipd push --force`) | Sensitive fields are redacted from event snapshots. Credentials, key hashes, tokens, and identity assertions must not be used as audit evidence. The dashboard renders snapshots as text. Date-only filters use UTC day boundaries; event timestamps display in your browser's timezone. Organization journal events use actions such as `member.added`, `member.role.updated`, `member.invitation.accepted`, and `team.member.removed`. Invitation events reference `invitation:`. Other identity journal events use `identity..` actions; impersonation sessions produce `impersonation.started` and `impersonation.ended` events. ## Export Audit-log search is available on Teams and Enterprise. Export is Enterprise-only. Export uses the same filters as the list, is capped at **10,000** rows per batch, and supports CSV and JSON. Each export reflects a consistent view of the matching events. Each request records started and completed or failed events. A successful response reports its row count and a `nextCursor` when the cap was reached. Use **Export next batch**, or pass that cursor with the same filters to the export API, to retrieve older events. Requests are limited to 60 seconds. Downloads require audit-read access and the export entitlement; responses are not cacheable. Downloads do not create a hosted artifact URL. CSV cells that start with `=`, `+`, `-`, or `@` are prefixed so spreadsheet apps will not treat them as formulas. ## Retention | Setting | Meaning | | - | - | | Missing row | 365-day request, capped by the plan and protected minimum | | `7`–`2555` | Requested days, subject to the plan and protected minimum | | `null` | Keep forever; accepted only when the entitlement is unlimited | Events expire according to your effective retention policy. The configured window is capped by the plan entitlement, but a protected contractual minimum takes precedence over that cap. A retention hold prevents expiry and customer retention changes. Retention settings remain attached to audit history after organization deletion. IP addresses and user agents follow the same event retention window, including holds; they are not retained under a separate indefinite policy. Exported copies are governed by the recipient's retention policy. Deletion requests do not override a hold or protected contractual minimum: contact support for policy review. Removing a hold requires an operator action with a recorded identity and reason. Previously expired data cannot be restored by extending retention. The standard caps are 7 days on Teams and 60 days on Enterprise; contracted entitlements and protected minimums can differ. Free and Pro do not expose the customer audit log. If your organization downgrades, existing audit history remains readable. Creating destinations, exporting, and changing retention continue to follow the current plan's entitlements. ## Webhook delivery POST JSON `{ "type": "audit.event", "event": { … } }`. | Header | Value | | - | - | | `content-type` | `application/json` | | `x-shipd-timestamp` | Unix seconds | | `x-shipd-signature` | `sha256=` of `timestamp.eventId.body` | | `x-shipd-event-id` | Audit event id | ```js Node theme={null} import { createHmac } from "node:crypto"; const expected = createHmac("sha256", secret) .update(`${timestamp}.${eventId}.${rawBody}`) .digest("hex"); ``` ```py Python theme={null} import hmac, hashlib expected = hmac.new( secret.encode(), f"{timestamp}.{event_id}.{rawBody}".encode(), hashlib.sha256, ).hexdigest() ``` Signing secret is at least 16 characters. Create returns it once; list and update redact it. Rotate by sending a new `config.secret` on update (omit or leave blank to keep the current value). SIEM tokens and S3 keys stay redacted after create. ## SIEM and S3 | Type | Auth | | - | - | | JSON | `Authorization: Bearer ` | | Splunk HEC | `Authorization: Splunk ` | | Datadog | `DD-API-KEY` | | Axiom (`axiom`) | `Authorization: Bearer ` | | Better Stack (`better_stack`) | `Authorization: Bearer ` | | S3-compatible | SigV4 path-style PutObject | Axiom uses a JSON array of public audit events with `_time` set to the original event time. Enter your deployment's full dataset ingest URL (`https://AXIOM_DOMAIN/v1/ingest/DATASET_NAME`) and an API token with ingest permission. See [Axiom ingestion](https://axiom.co/docs/restapi/ingest). Better Stack receives a JSON object with the public audit fields, `dt` set to the original event time, and `message` set to the action. Enter the ingesting host URL and source token from your Better Stack source. See [Better Stack HTTP ingestion](https://betterstack.com/docs/logs/ingesting-data/http/logs/). Amazon S3 and Cloudflare R2 use the existing S3-compatible delivery format. For Amazon S3, use the regional endpoint matching your bucket and region. For R2, use `https://ACCOUNT_ID.r2.cloudflarestorage.com` and region `auto`. Both write one JSON object per event under `/dt=YYYY-MM-DD/.json`. HTTP and private RFC1918 URLs are allowed (localhost Splunk, in-VPC MinIO). Cloud metadata and link-local addresses are rejected. Related: [View the audit log](/operations/audit-log) · [Access control](/enterprise/access-control). # SDK benchmarks Source: https://docs.useshipd.com/reference/benchmarks Measured flag evaluation latency, throughput, and configuration freshness in the TypeScript and Go SDKs. ## Overview These benchmarks show how quickly the TypeScript and Go SDKs evaluate flags locally, and how quickly configuration changes reach the TypeScript SDK. Measurements were recorded on **October 15, 2026 (UTC)** using a small production snapshot and synthetic evaluation contexts. They describe the tested workload and hardware, not a performance guarantee or latency SLO. ## Evaluation latency and throughput Flag checks read an in-memory snapshot without a network request. The table measures public SDK calls with **evaluation events disabled**. Startup, snapshot download, parsing, and refresh are excluded. | Boolean flag workload | SDK | p50 (µs) | p95 (µs) | p99 (µs) | Evaluations/sec | | - | - | - | - | - | - | | No targeting rules | TypeScript | 0.042 | 0.084 | 0.084 | 19.46M | | No targeting rules | Go | 0.166 | 0.209 | 0.333 | 4.98M | | Disabled flag | TypeScript | 0.042 | 0.084 | 0.084 | 20.56M | | Disabled flag | Go | 0.166 | 0.209 | 0.333 | 5.55M | | Attribute targeting: one rule | TypeScript | 0.083 | 0.125 | 0.125 | 12.33M | | Attribute targeting: one rule | Go | 0.375 | 0.500 | 0.875 | 2.96M | | Audience targeting: one rule | TypeScript | 0.083 | 0.125 | 0.125 | 12.49M | | Audience targeting: one rule | Go | 0.167 | 0.250 | 0.375 | 4.45M | | Audience and percentage targeting: two rules | TypeScript | 0.125 | 0.125 | 0.167 | 10.10M | | Audience and percentage targeting: two rules | Go | 0.208 | 0.250 | 0.375 | 4.03M | Workload labels describe the configured rules. Which rules execute depends on the evaluation context and the first matching rule; these results do not cover every targeting path or rule count. Latency percentiles come from individually timed calls and include timer overhead. TypeScript reports the median of five trial percentiles; Go latency comes from one pass. Throughput is measured separately and reports the median of five trials. It is not calculated from p99 latency. ## Evaluation while configuration updates A separate stress test repeatedly replaced snapshots while evaluations continued. It used the same six boolean flags as the evaluation run, including a second flag without targeting rules. Refreshes used an in-process transport to isolate replacement behavior from network latency. | SDK | Evaluation p99 across tested flags | First call after application p99 | | - | - | - | | TypeScript | 0.208–0.917 µs | 2.292–7.375 µs | | Go | 0.375–0.583 µs | Not measured separately | Each range contains the per-flag p99 values; it is not a percentile pooled across flags. The first TypeScript call after applying a snapshot was slower than steady-state calls in this run. JavaScript evaluation and snapshot application share one thread, so the test yielded between batches to allow updates. Go refreshed in a background goroutine. Both tests used one evaluation caller; they do not establish scaling across many concurrent callers. ## Configuration freshness The production test changed an isolated boolean flag ten times and measured when the SDK applied the new snapshot and returned the new value. | Synchronization path | p50 change request to application | Observed maximum | Samples | | - | - | - | - | | WebSocket notification followed by snapshot fetch | 906 ms | 1,722 ms | 10 | | Polling with a configured 1-second interval | 1,429 ms | 2,014 ms | 10 | **The default polling interval is 30 seconds.** The polling result above uses an explicitly configured **1-second interval**; it does not describe default polling freshness. The default interval was not measured in this run. Timing includes the configuration API request, publication, notification or polling, snapshot fetch, and application. The WebSocket test disabled polling fallback. Both paths were measured through the TypeScript SDK; Go currently refreshes through polling or manual refresh. Ten samples give an initial observation, not reliable p95 or p99 propagation estimates. See [Snapshots](/concepts/snapshots) for how updates reach your application. ## Measurement conditions and limits * **Hardware:** Apple M5 Pro with 18 logical CPUs; Node.js 26.11.1 and Go 1.26.2. * **Workload:** Six boolean flags with up to two rules, five compiled audiences, and 64 rotating, preallocated synthetic contexts with two attributes each. The tables show five representative flag workloads. Variant, number, and JSON flags were not measured. * **Sampling:** TypeScript latency used 50,000 calls per flag in each of five trials. Go latency used one 50,000-call pass per flag. Throughput used five trials per SDK, with warmup before measurement. Go throughput used `GOMAXPROCS=1`; the separate latency and replacement pass used the runtime default. Neither SDK was pinned to a physical CPU. * **Replacement test:** TypeScript measured 102,400 calls and 100 replacements per flag, with about 100 first-call-after-application samples. Go measured 50,000 calls and observed 8–16 background replacements per flag. * **Environment:** Measurements ran on a developer machine, and propagation testing overlapped part of the evaluation run. Submicrosecond timings are sensitive to timer resolution, runtime optimization, garbage collection, and scheduling. Use these results as a starting point when assessing shipd for your application. Larger rule sets, different evaluation contexts, event delivery, browser runtimes, and concurrent callers can change performance. Measure your own workload before setting latency budgets or capacity targets. Related: [Local evaluation](/concepts/local-evaluation) · [Snapshots](/concepts/snapshots) · [SDK reference](/reference/sdk) · [Go SDK reference](/reference/go-sdk). # CLI Source: https://docs.useshipd.com/reference/cli Every shipd command, option, exit code, and environment variable. The canonical home for push semantics. ## Overview `shipd` is the command-line interface for config as code. It syncs TypeScript, Go, or JSON flag configs with the server, generates flag types, and runs snapshot recovery operations. Every command supports `--json`. Use `--yes` or `--ci` to skip confirmation prompts for unattended runs. ```bash theme={null} npm install -g @shipdit/cli # Node.js 22.12 or later shipd --help ``` Package: `@shipdit/cli`. Binary: `shipd`. ## Global options Global options go before or after the command name and apply to every command. | Option | Type | Default | Description | | - | - | - | - | | `--json` | boolean | `false` | Print results as JSON on stdout. Errors print as JSON on stderr. | | `--yes` | boolean | `false` | Skip confirmation prompts. | | `--ci` | boolean | `false` | Same as `--yes`. | | `--api-url ` | string | the URL saved by `shipd login`; `http://localhost:8000` if none | Control-plane API origin. See [Configuration precedence](#configuration-precedence). | | `--org ` | string | — | Organization slug or ID. With an API key or token, this is a guard: it must match the credential's organization, and it never switches organizations. | | `--project ` | string | the credential's project | Project slug or ID. | | `--env ` | string | the credential's environment | Environment slug or ID. | | `--config ` | string | `.shipd/config.json` | Project settings file. See [`.shipd/config.json`](/reference/config#project-settings-file). | | `--flags-config ` | string | Auto-discovered TypeScript, Go, or JSON config | Path to `shipd.config.ts`, `shipd.config.go`, or `shipd.config.json`. | Confirmation is also skipped when `CI=1`, `CI=true`, or `SHIPD_CI=1`. Without any of these, a command that needs confirmation and has no TTY (for example, a CI job) is cancelled with exit code `1`. ## Configuration precedence Each setting resolves from the first source that has it: | Setting | 1 | 2 | 3 | 4 | 5 | | - | - | - | - | - | - | | API URL | `--api-url` | `SHIPD_API_URL` | `.shipd/config.json` `apiUrl` | global `config.json` `apiUrl` | `apiUrl` in `credentials.json` (saved by `shipd login`) | | Credential | `SHIPD_API_KEY` | `credentials.json` | — | — | — | | Organization | `--org` | `SHIPD_ORG` | `.shipd/config.json` `org` | global `config.json` `org` | — | | Project | `--project` | `SHIPD_PROJECT` | `.shipd/config.json` `project` | global `config.json` `project` | the credential's bound project | | Environment | `--env` | `SHIPD_ENV` | `.shipd/config.json` `env` | global `config.json` `env` | the credential's bound environment | | Flags file | `--flags-config` | `.shipd/config.json` `configFile` | Auto-discovered `shipd.config.ts`, `.go`, or `.json` in the project root | — | — | | Types output | `.shipd/config.json` `typesOut` | TypeScript: `src/generated/flags.ts`; Go: `internal/flags/flags_gen.go` | — | — | — | The project root is the nearest directory, walking up from the current directory, that contains `shipd.config.ts`, `shipd.config.go`, `shipd.config.json`, or `.shipd/config.json`. Relative `configFile` and `typesOut` paths resolve against the current directory, so run `shipd` from the project root. If no source sets the API URL, `shipd login` uses `https://api.useshipd.com` and saves it to `credentials.json`. Every other command falls back to `http://localhost:8000`. > [!WARNING] > > On a machine that never ran `shipd login`, such as a CI runner using `SHIPD_API_KEY`, commands call `http://localhost:8000` unless you set `SHIPD_API_URL=https://api.useshipd.com` or pass `--api-url https://api.useshipd.com`. ## Credentials | File | Contents | Written by | | - | - | - | | `~/.config/shipd/credentials.json` | `apiKey` (the management API key) and `apiUrl` | `shipd login`; removed by `shipd logout` | | `~/.config/shipd/config.json` | Default `org`, `project`, `env` (and optional `apiUrl`, `appUrl`) | `shipd login` | Both files are written with mode `0600`. When `XDG_CONFIG_HOME` is set, the directory is `$XDG_CONFIG_HOME/shipd` instead of `~/.config/shipd`. `SHIPD_API_KEY` overrides the stored key. It accepts a management API key (`shipd_mgmt_…`) or a service account token (`shipd_sa_…`). SDK keys (`shipd_sdk_…`) do not work with the CLI. See [SDK keys, management API keys, and service account tokens](/concepts/keys). ## Environment variables | Variable | Equivalent | Description | | - | - | - | | `SHIPD_API_KEY` | — | Management API key or service account token. Overrides `credentials.json`. | | `SHIPD_API_URL` | `--api-url` | Control-plane API origin. Set to `https://api.useshipd.com` in CI. | | `SHIPD_ORG` | `--org` | Organization guard. | | `SHIPD_PROJECT` | `--project` | Project slug or ID. | | `SHIPD_ENV` | `--env` | Environment slug or ID. | | `SHIPD_CI` | `--ci` | `1` skips confirmation. | | `CI` | `--ci` | `1` or `true` skips confirmation. | | `XDG_CONFIG_HOME` | — | Moves the global config directory. | ## JSON output With `--json`, results print to stdout as pretty-printed JSON. Errors print to stderr as one line: ```json theme={null} { "error": { "code": "conflict", "message": "Flag \"search-variant\" changed remotely (expected version 4, remote 5). Pull and retry, or pass --force.", "details": {} } } ``` `code` is the control-plane error code, or a CLI-side code. See [Errors](/reference/errors#cli-error-codes). ## shipd login Authenticates the CLI through browser device authorization and stores a management API key. ```bash theme={null} shipd login [--api-url ] ``` | Option | Type | Default | Description | | - | - | - | - | | `--api-url ` | string | resolved as in [Configuration precedence](#configuration-precedence), else `https://api.useshipd.com` | API origin to authenticate against. | **Behavior.** 1. Prints a verification URL and a one-time code, then polls until you approve or the code expires. 2. In the browser you choose an organization, a project, and an environment. The key is bound to exactly those three. 3. Writes the key and API URL to `credentials.json`. 4. Saves the organization, project, and environment slugs as defaults in the global `config.json`. Later commands need no `--project` or `--env`. Run `shipd login` again to switch the default project or environment. ```text Output theme={null} Open the following URL in your browser and enter the code: https://app.useshipd.com/auth/device/code?user_code=WDJB-MJHT Code: WDJB-MJHT Waiting for approval… Logged in successfully (fieldkit / web-app / production). ``` With `--json`, the code and URL print to stderr as JSON and the result prints to stdout. **Exit codes.** `0` on success. `1` if authorization is denied, expires, or times out. **Related:** [`shipd logout`](#shipd-logout) · [`shipd whoami`](#shipd-whoami) · [Keys](/concepts/keys) ## shipd logout Deletes `credentials.json`. ```bash theme={null} shipd logout ``` Default `org`, `project`, and `env` in the global `config.json` are kept. The key is not revoked on the server; revoke it in the dashboard under **Management keys**. **Exit codes.** `0`. ## shipd whoami Prints the identity behind the current credential. ```bash theme={null} shipd whoami ``` ```text Output theme={null} API key: key_01 Organization: fieldkit (org_01) Project: web-app (proj_01) Environment: production (env_01) ``` The first line is `API key: ` for a `shipd login` key, `Service account: (token )` for a service account token, or `User: ` for a user session. Project and environment lines appear only when the credential is bound to them. **Exit codes.** `0`, or `1` if unauthenticated. ## shipd push Plans the changes needed to make the server match `shipd.config.ts`, asks for confirmation, applies them, and regenerates flag types. ```bash theme={null} shipd push [--prune] [--force] [--adopt] ``` | Option | Type | Default | Description | | - | - | - | - | | `--prune` | boolean | `false` | Archive remote flags that are missing from `shipd.config.ts`. | | `--force` | boolean | `false` | Apply even if a flag changed on the server since the plan was computed. Audited. | | `--adopt` | boolean | `false` | Deprecated no-op. Accepted for older scripts. | Also uses the global `--yes` / `--ci`, `--project`, `--env`, `--flags-config`, and `--json`. ### Sequence 1. Load and validate the selected TypeScript, Go, or JSON flag config (see [validation rules](/reference/config#validation-rules)). 2. Ask the server for a plan against the target project and environment. Print it. 3. If the plan is empty, print `Nothing to push.` and exit `0`. Types are **not** regenerated. 4. Confirm (`Apply this plan? [y/N]`) unless `--yes`, `--ci`, or `CI` is set. 5. Save the plan with the flag versions seen in step 2. Production targeting becomes a draft; publish it from the dashboard’s **Across environments** table. Definitions and unprotected non-production targeting apply immediately. 6. Regenerate types to `typesOut` from the local file. ```text Output theme={null} Plan: + create flag "new-checkout" ~ update flag "search-variant" tags: ["search"] -> ["search","experiment"] ~ update flag "max-retries" default: 3 -> 5 Note: definition changes (type, variants, tags, lifecycle, description, clientAvailable) apply to all environments. Note: definition/ownership changes apply to all environments (requires production permission). Apply this plan? [y/N] y Saved 3 change(s). Wrote types for 4 flag(s) to /home/dev/web-app/src/generated/flags.ts ``` ### What each change does | Plan line | When | Effect | | - | - | - | | `+ create flag` | Key is in the file, not on the server | Creates the flag with `managedBy: code`. In the **target environment** it is enabled and its fallthrough is set to `default`. In every other environment it is disabled with a disabled fallthrough, so SDKs there receive the type's zero value (`false`, first variant, `0`, `{}`). | | `~ update flag` | Definition fields or `default` differ | Updates project-global fields, then rewrites the target environment's fallthrough if `default` changed. Sets `managedBy: code`. | | `- archive flag` | Key is on the server, not in the file, and `--prune` is set | Archives the flag. Archive is not a hard delete. | | (warning only) | Key is on the server, not in the file, no `--prune` | Left alone. The CLI prints `Warning: N remote flag(s) not in local config (pass --prune to archive)`. | ### Field scope | Field | Scope | Written by push to | | - | - | - | | `type`, `variants`, `description`, `tags`, `deprecated` (lifecycle) | Project-global | The flag definition, for every environment | | `default` | Per environment | The target environment's fallthrough only when targeting is omitted | | `targeting` | Per environment | Enabled state, ordered rules, and fallthrough for the target environment | | `traits` | Project-global | The flag's trait contract across all environments | | `clientAvailable` | Project-global | Explicit `true` or `false` updates browser availability; omission preserves the remote setting, and new flags default to private | Without a `targeting` block, changing `default` replaces the target environment's fallthrough with that fixed value, including a weighted fallthrough set in the dashboard. Rules and the **Enabled in \** switch are not changed. Because the plan compares against the live fallthrough, pushing a file that still has an old `default` reverts a fallthrough edited in the dashboard. Run [`shipd pull`](#shipd-pull) or read the `default:` line in the plan first. Optional `targeting` synchronizes rules, rollouts, enabled state, and fallthrough. See [Targeting sync](#targeting-sync). ### managedBy `managedBy` (`code` or `dashboard`) records which surface last changed a flag. It is attribution, not a lock: `shipd push` updates dashboard-edited flags, and the dashboard edits code-managed flags. `--adopt` does nothing. ### Permissions Push checks permissions against the whole plan. The credential needs: | Action | Required when | | - | - | | `flag.update` | Always. | | `flag.create` | The plan creates flags. | | `flag.archive` | The plan archives flags (`--prune`). | | `flag.production.toggle` | The target environment is production, or the plan creates, archives, or changes definition fields. | | `flag.state.update` | The plan only changes `default` in a non-production environment. | A management API key from `shipd login` acts with your role in its project. Service account tokens need these actions as scopes; see [Sync flags in CI](/config-as-code/ci#create-a-service-account-token) for scope names. Service account tokens bound to a single environment cannot create, update, or archive flags because those changes are project-wide; bind CI tokens to the project. ### Conflicts Apply is a compare-and-swap. The CLI sends the definition version and environment-state version of every flag it plans to change. If either changed on the server after the plan, the server rejects the whole push with `409 conflict` (exit `3`) and applies nothing: ```text theme={null} Error: Flag "search-variant" changed remotely (expected version 4, remote 5). Pull and retry, or pass --force. ``` `--force` skips the version check, applies the local definitions over the remote ones, and records the push in the [audit log](/reference/audit-log) with the reason `Forced CAS override`. It does not bypass permissions or approvals. See [Why did shipd push return a conflict?](/config-as-code/conflicts). ### Approvals When an [approval policy](/reference/approvals) covers the target environment: * A `default` change, or the enable-and-fallthrough step of a new flag, is queued as an approval request instead of applied. Push exits `5` and prints `N environment change(s) queued for approval.` The queued state is not live. * Changes that no policy matches in the same push still apply. * A second push for a flag that already has a pending request in that environment fails with `409 conflict` (exit `3`). * A definition change (create, archive, or a project-global field) when a policy covers any environment in the project cannot be submitted for review. The whole push fails with `409 conflict` (exit `3`) and nothing applies. `--yes`, `--ci`, and `--force` never approve anything. ### Limits * At most 500 flags per push. Larger files fail validation. * Flag keys must be unique. * Apply is transactional. A conflict, permission error, or invalid flag applies nothing and queues no approval requests. * Creating flags counts against your plan's flag allowance. See [Usage and limits](/reference/usage-and-limits). ### JSON output ```json theme={null} { "plan": { "creates": [], "updates": [], "archives": [], "unlinked": [], "conflicts": [] }, "remoteOnly": [], "forced": false, "approvalRequests": ["apr_01"], "outcome": "pending_approval", "types": { "written": "/home/dev/web-app/src/generated/flags.ts", "flagCount": 4 } } ``` `outcome` is `applied`, `draft`, or `pending_approval`. `drafts` lists flag keys with saved production targeting waiting for **Publish changes** in the dashboard. When the plan is empty, only `plan` and `remoteOnly` are printed. ```bash Example theme={null} shipd push --yes --project web-app --env staging ``` **Exit codes.** `0` applied or nothing to push · `1` error, or confirmation declined · `3` conflict · `5` some changes are pending approval. If generated output cannot be written after apply, the remote changes remain applied. Fix the output path or permissions and run `shipd types gen` to regenerate the local output. **Related:** [`shipd diff`](#shipd-diff) · [`defineFlags`](/reference/config) · [Push, pull, and diff](/config-as-code/sync) ## shipd diff Prints the plan `shipd push --prune` would apply, without changing anything. ```bash theme={null} shipd diff [--exit-code] ``` | Option | Type | Default | Description | | - | - | - | - | | `--exit-code` | boolean | `false` | Exit `2` when the plan is not empty, `4` when it contains unlinked flags. | **Behavior.** `diff` needs only `flag.read`, so any credential that can read the environment works, including a `shipd login` key. Remote flags missing from the file appear as `- archive flag` lines, and the CLI adds `Note: N remote flag(s) are missing locally. shipd push leaves them alone unless you pass --prune.` They count as drift for `--exit-code`. ```text Output theme={null} Plan: ~ update flag "max-retries" default: 3 -> 5 - archive flag "welcome" ``` A clean diff prints `No drift.` With `--json`, prints `{ creates, updates, archives, unlinked, conflicts, remoteOnly }`. ```bash Example theme={null} shipd diff --exit-code --project web-app --env production ``` **Exit codes.** `0` no drift, or `--exit-code` not set · `1` error · `2` drift (with `--exit-code`) · `4` unlinked (with `--exit-code`). Current servers do not report unlinked flags because `managedBy` is not a lock. **Related:** [`shipd push`](#shipd-push) · [Sync flags in CI](/config-as-code/ci) ## shipd pull Overwrites the selected flag config with the flags on the server, preserving TypeScript, Go, or JSON format, then regenerates TypeScript types or Go accessors. Go input defaults to Go output unless `typesLanguage` overrides it. ```bash theme={null} shipd pull [--force] ``` **Behavior.** * Writes every non-archived flag in the project, with the target environment's published `targeting` block and project-global trait declarations. Rules, weighted fallthroughs, and disabled state are preserved in all formats. The legacy `default` is derived from a concrete fallthrough value, the first non-disabled weighted variation, or a synthetic value for disabled fallthroughs. * The file is regenerated from scratch. Comments, formatting, helper code, and custom imports are lost. * Needs only `flag.read`. * Rejects unsynced targeting changes against the local baseline with exit `3`. `--force` explicitly replaces them. See [Targeting sync](#targeting-sync). ```text Output theme={null} Wrote 4 flag(s) to /home/dev/web-app/shipd.config.ts Wrote types for 4 flag(s) to /home/dev/web-app/src/generated/flags.ts ``` > [!WARNING] > > Commit or stash the selected flag config (`shipd.config.ts`, `shipd.config.go`, or `shipd.config.json`) before you pull. **Exit codes.** `0` success · `1` general error · `3` unsynced targeting conflict. If writing generated output fails, the config may already have been replaced. Fix the output path or permissions and run `shipd types gen` to regenerate it. **Related:** [`shipd push`](#shipd-push) · [Why did shipd push return a conflict?](/config-as-code/conflicts) ## shipd types gen Writes TypeScript types or Go accessors from the local TypeScript, Go, or JSON flag config. Does not contact the server. Loading `shipd.config.go` requires Go 1.23+ on `PATH`; Go input selects Go output unless `typesLanguage` or `--language` says otherwise. ```bash theme={null} shipd types gen [-o ] [--language typescript|go] [--package ] ``` | Option | Type | Default | Description | | - | - | - | - | | `-o, --out ` | string | Configured output, or the selected language's default | Output file. Parent directories are created. | | `--language ` | `typescript` or `go` | `typesLanguage`, else inferred from the config file | Output language for this invocation. | | `--package ` | string | `typesPackage`, else `flags` | Package name for generated Go output. | ```text Output theme={null} Wrote types for 4 flag(s) to /home/dev/web-app/src/generated/flags.ts ``` **Exit codes.** `0`, or `1` if the file, language, package name, or generated identifiers are invalid. **Related:** [Generate flag types](/config-as-code/types) · [Generated types](/reference/config#generated-types) Go generation needs no credentials: ```bash theme={null} shipd types gen --language go --out internal/flags/flags_gen.go ``` If `--language` switches away from the configured language, its default output path is used unless `--out` is supplied. Set `typesLanguage` in project settings to select Go output for push and pull too. ## shipd flags list Lists flags in the project, one per line: key, type, lifecycle, `managedBy`. ```bash theme={null} shipd flags list ``` ```text Output theme={null} new-checkout boolean active code search-variant variant active dashboard ``` Needs a project (`--project` or a project-bound credential). **Exit codes.** `0` or `1`. ## shipd flags create Creates one flag without editing `shipd.config.ts`. ```bash theme={null} shipd flags create --key [--type ] [--variants ] [--name ] [--description ] ``` | Option | Type | Default | Description | | - | - | - | - | | `--key ` | string | required | Flag key. | | `--type ` | `boolean` \| `variant` \| `number` \| `json` | `boolean` | Flag type. | | `--variants ` | string | — | Comma-separated variant names. Repeatable. Required with `--type variant`; rejected with any other type. Duplicates are removed. | | `--name ` | string | the key | Display name. | | `--description ` | string | — | Description. | **Behavior.** The flag is created in every environment with a disabled fallthrough. Requires `flag.create`. Add the flag to `shipd.config.ts` (or run `shipd pull`) so the next push does not report it as remote-only. ```bash Example theme={null} shipd flags create --key search-variant --type variant --variants control,semantic,hybrid ``` **Exit codes.** `0` or `1`. ## shipd flags archive Archives a flag after confirmation. ```bash theme={null} shipd flags archive --key ``` | Option | Type | Default | Description | | - | - | - | - | | `--key ` | string | required | Flag key. | Requires `flag.archive`. Archive is not a hard delete. **Exit codes.** `0`, or `1` (including when confirmation is declined). ## shipd projects list Lists projects in the organization: slug, name, ID. ```bash theme={null} shipd projects list ``` **Exit codes.** `0` or `1`. ## shipd environments list Lists environments in the project: slug, name, `production` or the environment type, ID. ```bash theme={null} shipd environments list ``` An environment-bound credential sees only its own environment. **Exit codes.** `0` or `1`. ## shipd snapshots publish Publishes the environment's current configuration again when an earlier publication failed. ```bash theme={null} shipd snapshots publish ``` This retries publication of live configuration; it does not publish saved targeting drafts. Check [Troubleshooting](/resources/troubleshooting) before using this recovery command. Requires `snapshot.publish`. See [Publish a snapshot](/operations/publish-a-snapshot). ## shipd snapshots outbox Lists publication jobs for the environment. Use this to check whether a saved change is waiting to publish or has failed. `dead_lettered` means automatic retries have stopped; contact support if failures persist. ```bash theme={null} shipd snapshots outbox [--status ] ``` | Option | Type | Default | Description | | - | - | - | - | | `--status ` | `pending` \| `processing` \| `published` \| `failed` \| `dead_lettered` | all | Filter by status. | ```text Output theme={null} #118 v42 dead_lettered attempts=8 — KV write failed ``` Requires `snapshot.publish`. ## shipd snapshots requeue Retries publication jobs that stopped after repeated failures. Use this after the cause of a publication failure has been resolved, or when support directs you to retry. ```bash theme={null} shipd snapshots requeue ``` ```text Output theme={null} Requeued 1 dead-lettered row(s). ``` Requires `snapshot.publish`. ## shipd snapshots rebuild Requests a rebuild of the current published configuration without changing its version. Use this when support asks you to rebuild an environment; it does not roll back or change flag values. ```bash theme={null} shipd snapshots rebuild [--project] ``` | Option | Type | Default | Description | | - | - | - | - | | `--project` | boolean | `false` | Rebuild every environment in the project instead of one. | Requires `snapshot.publish`. Environment-bound credentials cannot rebuild a whole project. ## shipd snapshots publications Lists publication history for the environment. Use the version and time to check whether a recent change published, and share publication details with support when troubleshooting update delivery. ```bash theme={null} shipd snapshots publications ``` Requires `snapshot.read` (admins and owners), which project- or environment-bound credentials cannot use. `snapshot.publish` is held by every role that can update flags (editor, admin, owner). ## Exit codes This is the single list of `shipd` exit codes. Causes and fixes are in [Errors](/reference/errors#cli-exit-codes). | Code | Meaning | Returned by | | - | - | - | | `0` | Success, nothing to do, or no drift | all | | `1` | General error: authentication, permission, validation, not found, network, usage error, or declined confirmation | all | | `2` | Drift | `diff --exit-code` | | `3` | Sync conflict or server `409`: local/remote targeting edits, stale version, pending approval, or unsupported protected operation | `push`, `pull`, and any command that receives `409` | | `4` | Unlinked flags | `diff --exit-code` | | `5` | Some changes are pending approval; they are not live | `push` | **Related:** [`defineFlags` and config files](/reference/config) · [Errors](/reference/errors) · [Sync flags in CI](/config-as-code/ci) ## Targeting sync `shipd push --env ` applies a flag's complete `targeting` block only to the selected environment. Omitting targeting preserves existing rules and enabled state; an explicit empty rule array clears rules. Trait declarations are shared across environments. Code-owned targeting changes publish in the selected environment when approval policy allows, including production. Production defaults without `targeting` retain the dashboard draft flow. Policy-protected changes require review and publication. `targeting.environments[slug]` replaces the base block for that environment. Dashboard targeting edits are blocked while code owns the environment. `--force` bypasses sync conflicts, never permissions or approvals. After pull or a successful immediate push, the CLI stores a local targeting baseline under `.shipd/sync/`, scoped to API origin, project, environment, and config path. Ignore this directory in Git. Later pushes reject dashboard targeting changes that differ from both the baseline and local state. Pull rejects unsynced local targeting edits. Reconcile the changes before continuing; `shipd push --force` deliberately overwrites remote state and `shipd pull --force` deliberately overwrites local state. Both sides converging to identical targeting is allowed. A new checkout has no baseline: the first push shows the live diff and requires confirmation (or explicit CI mode). Review that plan. Keep CI baselines in a cache if you need conflict detection across runs. Server version checks still protect every planned write against concurrent edits between planning and applying. Pending drafts and approval requests do not advance the published-state baseline. Pull exports published targeting; publish a draft before pulling it into code. During an active progressive rollout, pull retains the stored code declaration so generated exposure steps do not overwrite the repository plan. Pull regenerates TypeScript, Go, or JSON source and replaces comments and helper declarations. Keep custom code outside generated configs or review the diff after every pull. The targeting guard protects tracked targeting changes, not arbitrary source edits. ## rollout status|pause|resume|abort Observe or control a progressive rollout associated with a release record. ```bash theme={null} shipd rollout status shipd rollout resume --note "Begin rollout" shipd rollout pause --note "Investigating support reports" shipd rollout abort --note "Restore control" ``` **Returns** the release version, rollout plan, active step, latest guard decision and metric snapshot. `status --json` also includes the next check time and pending approval ID. Mutation commands read the current version and reject concurrent edits. **Fallback.** Missing or insufficient Sentry data prevents advancement. `pause` keeps checking guards at the current exposure. `abort` restores the configured default; guard failures do this automatically even in production. Resuming a proposal starts controller checks and does not approve any policy-protected step. **Errors.** The controller must be enabled with `code-release-control`. Stale versions and terminal releases conflict. Production controls require production permission. Review and publish pending approvals through the human approval flow. Agents cannot invoke these mutation commands through MCP. **Related:** [Rollout configuration](/reference/config#signal-driven-rollout) · [Release records](/reference/releases) # Configuration files Source: https://docs.useshipd.com/reference/config defineFlags, shipd.config.ts, shipd.config.go, CLI settings, and generated flag types: exact types, validation rules, and field scope. ## Overview Config as code supports TypeScript and Go. `shipd.config.ts` holds flag definitions written with `defineFlags`, `.shipd/config.json` holds optional project settings for the CLI, and `src/generated/flags.ts` holds the types the CLI generates from the definitions. Go definitions live in `shipd.config.go`, and Go accessors default to `internal/flags/flags_gen.go`. This page is the contract for these formats. For what `shipd push` does with them, see [`shipd push`](/reference/cli#shipd-push). ## shipd.config.ts The file must default-export the result of `defineFlags`. The CLI loads it with [jiti](https://github.com/unjs/jiti), so TypeScript runs without a build step. It lives in the project root by default. Override the location with `configFile` in `.shipd/config.json` or `--flags-config`. ```ts TypeScript theme={null} // shipd.config.ts import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, description: "Redesigned checkout flow", tags: ["checkout"], }, "search-variant": { type: "variant", variants: ["control", "semantic", "hybrid"] as const, default: "control", }, "max-retries": { type: "number", default: 3 }, "checkout-payload": { type: "json", default: { mode: "strict", showPromo: true }, }, }); ``` ```go Go theme={null} // shipd.config.go package main import "github.com/alasti-company/shipd-go/config" var Config = config.ShipdConfig{ "new-checkout": {Type: "boolean", Default: false, Description: "Redesigned checkout flow", Tags: []string{"checkout"}}, "search-variant": {Type: "variant", Default: "control", Variants: []string{"control", "semantic", "hybrid"}}, "max-retries": {Type: "number", Default: 3}, "checkout-payload": {Type: "json", Default: map[string]any{"mode": "strict", "showPromo": true}}, } ``` For Go, the CLI reads this file directly. Go 1.23+ must be installed to load it. ## Go ShipdConfig Import `github.com/alasti-company/shipd-go/config`. It's part of the Go SDK module, so `go get github.com/alasti-company/shipd-go` installs both, and it has no dependencies on the runtime client. `ShipdConfig` is a named map so flag keys can appear directly in a composite literal; each value is a `FlagDefinition` struct: ```go theme={null} // Import "github.com/alasti-company/shipd-go/config". var Config = config.ShipdConfig{ "new-checkout": { Type: "boolean", Default: false, Description: "Redesigned checkout flow", }, } ``` Go field names are exported and capitalized. JSON uses lowercase names through struct tags. ```go theme={null} type ShipdConfig map[string]FlagDefinition type FlagDefinition struct { Type string Default any Variants []string Description string Tags []string Deprecated bool Disabled bool Targeting *Targeting Traits map[string]TraitDefinition } func (c ShipdConfig) Validate() error func (c ShipdConfig) MarshalJSON() ([]byte, error) func (c ShipdConfig) Defaults() (map[string]any, error) ``` **Validation.** Types and defaults must agree. Variant defaults must belong to a nonempty variant list. Values must be JSON-compatible. Keys cannot be empty, whitespace-only, or `__proto__`. At most 500 flags are accepted. `Deprecated` becomes `lifecycle: "deprecated"`; omitted tags normalize to `[]`. `Disabled` preserves an intentionally disabled environment fallthrough. **CLI loading.** The CLI reads `shipd.config.go` directly and automatically generates Go accessors. Define an exported `var Config = config.ShipdConfig{...}` in a self-contained Go file inside your module. The CLI evaluates that file with Go; imported packages and helper declarations in the same file are supported. It does not load sibling Go files, so keep application dependencies in imported packages. Do not define `main` in the definition file. `shipd pull` rewrites the Go definitions and regenerates accessors; review the resulting diff because comments and helper code are replaced. **Defaults.** `Defaults` validates and returns a detached map for `shipd.Options.Defaults`; numbers decode as `float64`. Mutating that map does not change the definitions. Unlike the generated `flags.Defaults()` helper, this method returns an error because the definitions have not yet been validated. **Mutation.** A `ShipdConfig` literal remains editable. Methods validate its current values each time; do not mutate it concurrently with validation or extracting defaults. ## shipd.config.json A language-neutral document with `version: 1` and a `flags` object. The CLI validates every entry with the same sync schema as TypeScript. This optional format can be authored directly; Go projects use `shipd.config.go`. ```json shipd.config.json theme={null} { "version": 1, "flags": { "new-checkout": {"type": "boolean", "default": false, "tags": ["checkout"], "lifecycle": "active"}, "search-variant": {"type": "variant", "variants": ["control", "semantic"], "default": "control"} } } ``` JSON fields use the same lowercase names as normalized TypeScript definitions. `tags` defaults to `[]`, `lifecycle` defaults to `"active"`, and `description` is optional. `deprecated: true` is accepted as shorthand for a deprecated lifecycle when `lifecycle` is omitted. Pull writes normalized `lifecycle` values and preserves the optional `disabled` field for intentionally disabled environment fallthrough. Discovery checks `shipd.config.ts`, `shipd.config.go`, then `shipd.config.json`. Set `configFile` or `--flags-config` to select a file explicitly. Pull preserves the selected format. ## defineFlags Validates flag definitions, normalizes them for the CLI, and keeps flag keys and variant names as literal types. ```ts theme={null} import { defineFlags } from "shipdit/config"; function defineFlags>( definitions: SatisfyFlagDefinitions & T, ): FlagsConfig; ``` **definitions** `Record\` *required* An object whose keys are flag keys and whose values are flag definitions. **Returns** `FlagsConfig`: `{ version: 1, flags: { [key]: NormalizedFlag } }`. **Errors.** Throws a Zod validation error, or `Error('flag key "__proto__" is reserved')`, when a definition breaks a [validation rule](#validation-rules). The CLI reports load failures as `Failed to load config : ` with exit code `1`. `defineFlags` is exported only from `shipdit/config`, not from the `shipdit` root. ### Definition types ```ts theme={null} type FlagType = "boolean" | "variant" | "number" | "json"; type CommonAuthoringFields = { clientAvailable?: boolean; description?: string; tags?: readonly string[]; deprecated?: boolean; targeting?: ConfigTargeting; // accepts readonly authoring data traits?: TraitDefinitions; }; type BooleanFlagDefinition = CommonAuthoringFields & { type: "boolean"; default: boolean; }; type VariantFlagDefinition< V extends readonly [string, ...string[]] = readonly [string, ...string[]], > = CommonAuthoringFields & { type: "variant"; variants: V; default: V[number]; }; type NumberFlagDefinition = CommonAuthoringFields & { type: "number"; default: number; }; type JsonFlagDefinition = CommonAuthoringFields & { type: "json"; default: unknown; }; type FlagDefinition = | BooleanFlagDefinition | VariantFlagDefinition | NumberFlagDefinition | JsonFlagDefinition; ``` ### Fields **type** `"boolean" | "variant" | "number" | "json"` *required* The value type. Selects the SDK reader: `isEnabled`, `getVariant`, `getNumber`, or `getJson`. **default** `boolean | string | number | JSON value` *required* When `targeting` is omitted, the value the target environment's fallthrough serves. On every `shipd push` without explicit targeting, if `default` differs from the target environment's current fallthrough, push sets that fallthrough to `default`, replacing a fallthrough edited in the dashboard (including a weighted split). Other environments are untouched. Run `shipd pull` first, or update `default`, to keep a dashboard edit. See [Field scope](#field-scope). **variants** `readonly [string, ...string[]]` Required for `variant` flags, ignored otherwise. Write it `as const` so variant names stay literal types. **clientAvailable** `boolean` TypeScript and JSON only. Explicitly allow or disable public browser delivery across all environments. Omission preserves existing remote availability on push; new flags default to private. See [Client availability](#client-availability). **description** `string` Shown in the dashboard. **tags** `readonly string[]` Labels for filtering in the dashboard. Normalized to `[]` when omitted. **deprecated** `boolean` `true` sets the flag's lifecycle to `deprecated`. Omitted or `false` means `active`. Optional `targeting` declares the complete selected environment state. Optional `traits` declares this flag's evaluation inputs. See [Targeting in code](#targeting-in-code). Unknown fields are ignored; check spelling before pushing. ### Client availability In TypeScript or version-1 JSON configs, set `clientAvailable` explicitly to manage browser delivery from code: ```ts shipd.config.ts theme={null} import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, clientAvailable: true }, "max-retries": { type: "number", default: 3, clientAvailable: false }, }); ``` The field accepts only a boolean. `true` permits public client keys to request evaluated values; `false` disables delivery after snapshot publication. Omission preserves the existing remote setting on push, including dashboard edits. New flags remain server-only when omitted. `shipd pull` writes explicit values to TypeScript and JSON configs. Availability applies across all environments and uses definition permissions and version checks; see [CLI field scope](/reference/cli#field-scope). The current Go `FlagDefinition` struct does not include this field. Go projects can use a version-1 JSON flag config to manage availability from code; pushing a Go config with the field omitted preserves remote availability. Upgrade the SDK, CLI, and control plane together before using the setting. Client identity remains untrusted, and availability changes propagate asynchronously; see [Browser](/sdks/browser#client-availability-and-evaluation). ### Normalized output ```ts theme={null} type FlagLifecycle = "active" | "deprecated"; type NormalizedFlag = { clientAvailable?: boolean; key: string; type: FlagType; default: unknown; // narrowed per type variants?: string[]; // variant flags only description?: string; tags: string[]; lifecycle: FlagLifecycle; }; type FlagsConfig = { version: 1; flags: { [K in keyof T]: NormalizedFlag /* with K, default, and variants kept literal */ }; }; ``` ## Validation rules `defineFlags` checks these at runtime when the file loads. The CLI and the server re-check them before a diff or push. | Rule | Enforced by | Error message | | - | - | - | | Definitions are a plain object | `defineFlags` | `flag definitions must be an object` | | Key is not empty or whitespace-only | `defineFlags`, server | `flag key must not be empty or whitespace-only` | | Key is not `__proto__` | `defineFlags`, server | `flag key "__proto__" is reserved` | | `type` is one of the four types | `defineFlags`, server | Zod discriminated-union error | | `boolean`: `default` is a boolean | `defineFlags`, server | `boolean flag default must be a boolean` (server) | | `number`: `default` is a finite number | `defineFlags`, server | `number flag default must be a finite number` (server) | | `variant`: `variants` is a non-empty array of strings | `defineFlags`, server | `variant flag requires a non-empty variants array` (server) | | `variant`: `default` is one of `variants` | TypeScript, `defineFlags`, server | `default "v3" must be one of variants: control, semantic, hybrid` | | `json`: `default` is a JSON value | `defineFlags`, server | `default must be JSON-serializable` | | `description` is a string, `tags` is an array of strings, `deprecated` is a boolean | `defineFlags` | Zod type error | | Keys are unique | CLI, server | `duplicate flag key ""` | | At most 500 flags | server | `422 validation_error` | | The file default-exports a `defineFlags` result | CLI | `Flag config must contain a flags object (defineFlags result or version-1 JSON)` | A JSON value is `null`, a boolean, a string, a finite number, an array of JSON values, or a plain object of JSON values. TypeScript authoring rejects functions, `undefined`, symbols, symbol keys, class instances (including `Date` and `Map`), `NaN`, `Infinity`, and circular references. Flag keys have no other format rule. `new-checkout`, `checkout.v2`, and `max_retries` are all valid. For naming advice, see [Name and retire flags](/flags/naming-and-lifecycle). For TypeScript definitions, the variant check also runs at compile time. This is a type error: ```ts theme={null} "search-variant": { type: "variant", variants: ["control", "semantic"] as const, default: "hybrid", // Type '"hybrid"' is not assignable to type '"control" | "semantic"'. }, ``` ## Field scope A flag definition is shared by every environment in the project. Its default is not. | Field | Scope | Effect of `shipd push --env ` | | - | - | - | | `type` | Project-global | Changes the flag in every environment | | `variants` | Project-global | Changes the flag in every environment | | `description` | Project-global | Changes the flag in every environment | | `tags` | Project-global | Changes the flag in every environment | | `deprecated` (lifecycle) | Project-global | Changes the flag in every environment | | `default` | Per environment | Sets the fallthrough of `` only when targeting is omitted | | `targeting` | Per environment | Replaces enabled state, ordered rules, and fallthrough of `` | | `traits` | Project-global | Updates this flag's trait contract for every environment; omission preserves it | | `clientAvailable` | Project-global | Updates public browser availability for every environment; omission preserves the remote setting | When push creates a flag, `` gets the explicit targeting or, if omitted, enabled state with a fallthrough set to `default`. Production targeting changes remain drafts until published. Every other environment gets the flag disabled with a disabled fallthrough. The full rules, including what happens when `default` changes on an existing flag, are in [`shipd push`](/reference/cli#field-scope). `shipd pull` reads the other way: it writes each flag's `default` from the target environment's fallthrough. ## Project settings file `.shipd/config.json` holds optional project settings for the CLI. The CLI finds it by walking up from the current directory. Point to another file with `--config `. Flags and `SHIPD_*` environment variables override it; it overrides the global config written by `shipd login`. See [Configuration precedence](/reference/cli#configuration-precedence). ```ts theme={null} interface ShipdProjectConfig { apiUrl?: string; // control-plane API origin appUrl?: string; // dashboard origin org?: string; // organization slug (guard only with an API key or token) project?: string; // project slug or ID env?: string; // environment slug or ID configFile?: string; // path to shipd.config.ts, shipd.config.go, or shipd.config.json typesOut?: string; // path for generated types or Go accessors typesLanguage?: "typescript" | "go"; // inferred from configFile typesPackage?: string; // Go package name; default "flags" } ``` ```json .shipd/config.json theme={null} { "org": "fieldkit", "project": "web-app", "env": "development", "typesOut": "src/generated/flags.ts" } ``` Relative paths resolve against the current directory. `typesLanguage` selects TypeScript (`src/generated/flags.ts`) or Go (`internal/flags/flags_gen.go`) default output. `typesOut` can only be set here; `shipd types gen -o` overrides it for one run. Do not put credentials in this file. Use `SHIPD_API_KEY` or `shipd login`. ## Generated Go accessors With Go input or `typesLanguage: "go"`, push, pull, and type generation write one function per flag, key constants, named variant string types and constants, and `Defaults() map[string]any`. Number accessors return `float64`; JSON accessors return `any`. Go names use the alphanumeric parts of keys in PascalCase. Names that do not begin with an uppercase Unicode letter receive a `Flag` prefix. Flag and variant names that collide with another generated declaration cause a validation error. Package names must be valid ASCII Go identifiers and cannot be keywords or `_`. Generated accessors use the canonical Go SDK module path. Go variants are named string types, not closed unions. See [Go output](/config-as-code/types#go-output) for usage. ## Generated types `shipd push`, `shipd pull`, and `shipd types gen` write `typesOut` from the local TypeScript, Go, or JSON config. Unless overridden by `typesLanguage` or `typesOut`, TypeScript and JSON use `src/generated/flags.ts`, while Go uses `internal/flags/flags_gen.go`. The file is overwritten on every run. Do not edit it by hand. See [Generate flag types](/config-as-code/types). ```ts src/generated/flags.ts theme={null} /* eslint-disable */ /* This file is generated by shipd types gen. Do not edit. */ export interface FlagDefinitions { "new-checkout": { type: "boolean"; default: false; }; "search-variant": { type: "variant"; variants: "control" | "semantic" | "hybrid"; default: "control"; }; "max-retries": { type: "number"; default: 3; }; "checkout-payload": { type: "json"; default: {"mode":"strict","showPromo":true}; }; } export type FlagKey = keyof FlagDefinitions; export type BooleanFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "boolean" ? K : never; }[FlagKey]; export type VariantFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "variant" ? K : never; }[FlagKey]; export type NumberFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "number" ? K : never; }[FlagKey]; export type JsonFlagKey = { [K in FlagKey]: FlagDefinitions[K]["type"] extends "json" ? K : never; }[FlagKey]; ``` | Export | Type | | - | - | | `FlagDefinitions` | One entry per flag with `type`, `default` as a literal type, and `variants` as a union for variant flags | | `FlagKey` | Union of all flag keys | | `BooleanFlagKey`, `VariantFlagKey`, `NumberFlagKey`, `JsonFlagKey` | Keys of each flag type | Pass `FlagDefinitions` as the type argument to `createClient()` from `shipdit` or `shipdit/client`, and to `createShipdReact()` from `shipdit/client/react`. Without it, any string key type-checks. **Related:** [`shipd push`](/reference/cli#shipd-push) · [Define flags in code](/config-as-code/define-flags) · [Generate flag types](/config-as-code/types) · [SDK reference](/reference/sdk) ## Targeting in code Add `targeting` to a flag definition to manage its enabled state, ordered rules, and fallthrough together. Omit it to preserve dashboard rules and enabled state. `rules: []` explicitly clears rules. Rule IDs must be nonempty and unique within a flag; keep IDs stable when editing or reordering. First matching rule wins. Rule conditions are ANDed; use a group for OR. An empty condition array never matches. ```ts TypeScript theme={null} // shipd.config.ts import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, traits: { plan: { type: "string", values: ["free", "pro"], required: true } }, targeting: { enabled: true, rules: [{ id: "pro-customers", conditions: [{ kind: "attribute", attribute: "plan", operator: "eq", value: "pro" }], serve: { kind: "boolean", value: true }, }], fallthrough: { kind: "boolean", value: false }, }, }, }); ``` ```go Go theme={null} // shipd.config.go package main import "github.com/alasti-company/shipd-go/config" var Config = config.ShipdConfig{ "new-checkout": { Type: "boolean", Default: false, Traits: map[string]config.TraitDefinition{ "plan": {Type: "string", Values: []string{"free", "pro"}, Required: true}, }, Targeting: &config.Targeting{ Enabled: true, Rules: []config.Rule{{ ID: "pro-customers", Conditions: []config.Condition{{Kind: "attribute", Attribute: "plan", Operator: "eq", Value: "pro"}}, Serve: config.Serve{Kind: "boolean", Value: true}, }}, Fallthrough: config.Serve{Kind: "boolean", Value: false}, }, }, } ``` `targeting.fallthrough` overrides `default` for environment sync. `default` still supplies generated SDK defaults. Pull exports the published environment state, including weighted fallthroughs and disabled state; it does not export pending drafts. Conditions and serves use the same serializable shapes as the [targeting API](/flags/targeting). Audience references use existing audience keys and must exist in the project. This config does not create audiences. ### Trait contracts `traits` is project-global flag metadata. Omit it for unrestricted legacy targeting; `{}` explicitly permits only built-in traits (`userId`, `country`, `region`, `city`, `timezone`). Other declared traits support `string`, `number`, and `boolean`. Built-in trait types must remain strings. Strings can declare a nonempty `values` enum: equality and membership operators require enum members, while text operators accept partial strings. Ordered comparisons accept numbers and strings, including numeric strings and ISO timestamps; text operators require strings. Declarations validate rules and custom bucketing attributes in the CLI and API, including dashboard targeting edits. Changing a contract must remain compatible with published targeting and saved drafts in every environment, including when the push also supplies replacement targeting. To remove or narrow a trait, first publish rules that no longer depend on it, then update the contract. `required: true` describes an application input contract. It does not change missing-attribute evaluation or make SDK reads throw. Use `TraitsFor` from `shipdit/config` for typed application attributes. TypeScript checks authored condition values, operators, flag serve types, and variant names. Runtime checks remain necessary for dashboard and JSON inputs. Go generates a per-flag `Traits` struct with pointer fields and a `Context(userID)` method returning `(shipd.EvaluationContext, error)`. Missing required pointers return an error; explicit zero values remain valid, and nil optional pointers stay absent. Enum strings use named types; Go enums remain open string types. Sync and conflict behavior is defined in [CLI reference](/reference/cli#targeting-sync). ### Environment overrides `targeting.environments` maps environment slugs to complete replacements. Other environments use the base block. Rules retain their order and support audience references (`kind: "segment"`), attributes, nested groups, percentage conditions, and weighted serves. ```ts shipd.config.ts theme={null} import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, targeting: { enabled: true, rules: [], fallthrough: { kind: "boolean", value: false }, environments: { staging: { enabled: true, rules: [], fallthrough: { kind: "boolean", value: true }, }, }, }, }, }); ``` Run `shipd diff --env staging` and `shipd diff --env production` to review each environment's effective plan. Push each environment separately. Go uses `Targeting.Environments map[string]*config.Targeting`; JSON uses the same fields as TypeScript. Pushing `targeting` makes that environment code-owned. Dashboard and API targeting edits return a conflict; change the config and push again. Removing `targeting` and pushing returns control to the dashboard while preserving published rules and enabled state. `managedBy` remains last-writer attribution and does not determine ownership. Code targeting publishes immediately when policy allows, including production. Policy-protected changes use the existing approval and publication flow. Published rules and control metadata are included in signed snapshots. ### Signal-driven rollout The `code-release-control` feature flag enables the progressive controller. Define the safe default and an explicit treatment, then use a release record to propose and start it. Pushing a plan alone does not start exposure. ```ts shipd.config.ts theme={null} import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, targeting: { enabled: true, rules: [], fallthrough: { kind: "boolean", value: false }, }, rollout: { provider: "sentry", connection: "checkout-production", treatment: { kind: "boolean", value: true }, steps: [ { percentage: 1, minDwellSeconds: 300 }, { percentage: 10, minDwellSeconds: 600 }, { percentage: 50, minDwellSeconds: 900 }, { percentage: 100, minDwellSeconds: 900 }, ], guards: [ { metric: "error_rate", threshold: 0.01, minSamples: 100 }, { metric: "p95_latency", threshold: 500, minSamples: 100 }, { metric: "custom", field: "avg(tags[cart_value,number])", operator: "gte", threshold: 20 }, ], }, }, }); ``` Go uses `config.Rollout`, `config.RolloutStep`, and `config.RolloutGuard`. The CLI reads the same shape from JSON. Percentages must strictly increase and end at 100. Dwell times are seconds, from 1 to 604800. Guards default to `operator: "lte"` and `minSamples: 20`. Error rate is a fraction of failed root transactions, p95 latency is milliseconds, and custom fields use a Sentry aggregate expression. Treatment must match the flag type and declared variants. Connection names refer to project-scoped Sentry credentials configured by your shipd operator. Never put tokens in the config. The provider queries the release commit and environment in Sentry's spans dataset. Instrument transactions with a Sentry `release` equal to the release record's commit SHA and the matching environment slug. Without matching telemetry, the controller holds exposure. A one-minute ingestion allowance is added to the minimum dwell. A ready release must associate the flag and have one stage per rollout step. `release_proposeProgressiveRollout` proposes the pushed plan; a human starts it with `shipd rollout resume`. Review [release records](/reference/releases) for the API and [CLI controls](/reference/cli#rollout-status%7Cpause%7Cresume%7Cabort). The controller compiles each step into ordinary percentage rules; SDK evaluation stays local. It checks guards throughout dwell, holds on missing or insufficient data, and restores the configured default on failure, including production. Approval policies can require human review before increasing exposure. Agents can propose and inspect, but cannot approve production. `pause` freezes advancement while guards continue checking; `abort` restores the default and terminates the rollout. Active controllers block config pushes until aborted. After the final step passes its dwell and guards, the release completes and continuous monitoring ends. # Control-plane API Source: https://docs.useshipd.com/reference/control-plane-api Versioning, authentication, errors, pagination, retries, and compatibility for the shipd management API. ## Overview The dashboard, `shipd` CLI, and automation clients share the same versioned API at `https://api.useshipd.com/api/v1`. RPC routes accept JSON with `POST` and return JSON. > [card] [OpenAPI 3.1 document](https://api.useshipd.com/api/v1/openapi.json) > > Every route, request body, and response schema: `https://api.useshipd.com/api/v1/openapi.json`. Generate a client from it or import it into your API tool. Successful RPC responses use one envelope: ```json theme={null} { "data": { "id": "project_01", "name": "Web app" } } ``` ## Versioning and compatibility The major version is part of every public path. Within `/api/v1`, shipd may add optional request fields, response fields, routes, error codes, and enum values. It does not remove fields, change their meaning, or make an optional field required without a new major version. Use the OpenAPI document as the machine-readable contract to generate clients and validate requests and responses. When a route or authentication mode is deprecated, its reference entry names the replacement and earliest removal date. A replacement remains available for at least one published migration window. ## Authentication and route restrictions Send credentials with `Authorization: Bearer …` or `x-api-key`. Do not put long-lived credentials in URLs. | Credential | Intended use | Restrictions | | - | - | - | | Dashboard session | Interactive administration | Active organization, role, team, project, and environment access apply. | | Management API key (`shipd_mgmt_…`) | Personal CLI and compatible automation | Bound to one organization, project, and environment. It cannot administer organization-wide keys, billing, members, teams, SSO, service accounts, audit, or snapshot-wide reads. | | Service account token (`shipd_sa_…`) | CI and automation | Limited by its explicit scopes and optional project/environment binding. Approval review, SDK-key creation, service-account lifecycle, team rosters, device authorization, SSO, and SCIM settings require a user session. | | SDK key (`shipd_sdk_…`) | Data-plane snapshot and event traffic | Valid only on `https://edge.useshipd.com/sdk/v1`; it is not a control-plane credential. | Resource lookups are organization-scoped. Where a resource identifier would reveal access to another project or organization, the API returns the same `404 not_found` response used for a missing resource. ## Errors Every non-success response has a stable, machine-readable envelope. Internal exceptions and stack traces are logged server-side and are not returned. ```json theme={null} { "error": { "code": "validation_error", "message": "Request validation failed", "requestId": "req_01", "details": {} } } ``` Branch on `error.code`, not on `message`. Common codes are `unauthenticated` (401), `forbidden` (403), `not_found` (404), `conflict` (409), `validation_error` (422), and `rate_limited` (429). Report `requestId` to support for any `500 internal`. See [Errors](/reference/errors) for every status, code, and CLI exit code. ## Pagination Growing collections use cursor pagination. Send `limit` and, after the first page, the prior response's `Next-Cursor` header as `cursor`. Do not parse or construct string cursors. Audit and snapshot operational collections use monotonically ordered numeric cursors; treat those as opaque too. ```http theme={null} POST /api/v1/rpc/evaluatedEntity/list Content-Type: application/json { "projectId": "project_01", "limit": 100, "cursor": "W1wi…" } ``` If `Next-Cursor` is absent, the page is complete. Naturally bounded configuration collections may return arrays without a cursor. ## Safe retries Retriable control-plane mutation routes accept `Idempotency-Key` with up to 256 characters. Generate a unique value per logical operation and reuse it only when retrying that operation. shipd stores the request hash and response for 24 hours, scoped to the authenticated principal and route. The OpenAPI operation declares the header when it is supported. Usage ingest instead requires an idempotency key on every event; evaluated-entity ingest is an upsert by environment and external id. * A completed duplicate replays the original status and body with `Idempotency-Replayed: true`. * Reusing a key with a different body returns `409 conflict`. * A concurrent duplicate still being processed returns `409 conflict`; retry it with backoff and the same key. * A server failure is not cached, so the same key can retry safely. [Release record mutations](/reference/releases#authentication-and-retries) are an unreleased exception: they require an idempotency key and commit their durable retry receipt atomically with the release action. Their receipts have no time-based expiry, and concurrent identical retries serialize rather than returning an in-progress conflict. Do not apply the general 24-hour replay-window assumptions to those operations. Read `Retry-After` before retrying `429`, `503`, or asynchronous `202` responses. Rate-limited responses also include `RateLimit-Limit`, `RateLimit-Remaining`, and the Unix timestamp `RateLimit-Reset`. Use exponential backoff with jitter when `Retry-After` is absent. ## Asynchronous operations `snapshot/rebuild` queues rebuild work and returns `202`, `Location`, and `Retry-After`. SCIM connection decommissioning returns `202` with the current connection state while directory cleanup continues; poll the route named by `Location` after `Retry-After`. A completed SCIM decommission returns `200`. ## Conditional requests Control-plane RPC results are private and use `Cache-Control: no-store`. Snapshot payloads on the data plane return an `ETag`; send it in `If-None-Match` to receive `304 Not Modified`. See [Edge API](/reference/edge-api). ## Bulk operations | Operation | Maximum | Failure behavior | | - | -: | - | | Flag `diff` / `push` | 500 flags | Validation rejects the entire request. Apply is transactional: a conflict or invalid flag applies none of the batch. The response reports planned/applied changes and approval request IDs. | | Evaluated-entity ingest | 100 entities | Validation rejects the entire request before writes. Duplicate identities coalesce by environment and external id. | | Usage ingest | 500 events | Each event carries an idempotency key; accepted and duplicate counts are returned. Invalid input rejects the request. | | Project team assignment | 100 teams | Assignment is atomic; cross-organization team IDs reject the request. | | SDK events | 100 events and 256 KiB | Validation rejects malformed or oversized batches. Accepted identity events are queued before `202`. | ## Client consistency The dashboard and CLI call these same `/api/v1/rpc` contracts through the shared API client. Automation should follow the same resource binding, approval, idempotency, error, and retry rules; no separate automation semantics exist. Related: [Errors](/reference/errors) · [CLI](/reference/cli) · [Service account tokens](/reference/service-account-tokens) · [SDK keys, management API keys, and service account tokens](/concepts/keys) · [Audit log](/reference/audit-log). # Customer events and webhooks Source: https://docs.useshipd.com/reference/customer-events Publishing contracts, signature verification, delivery guarantees, limits, and endpoint lifecycle. ## Overview Publish application events to subscribed HTTPS endpoints. Customer webhooks are a limited beta; ask support to enable your organization. They have a separate contract from audit destinations and snapshot callbacks. Start with [Receive customer events](/operations/receive-customer-events). ## API Every operation is a JSON POST under `/api/v1/rpc/`. Authenticate with an existing management API key, service-account token, or dashboard session. Evaluation SDK keys do not authorize this API. A service-account publisher only needs `{ "customer_event": ["publish"] }` and can be bound to one project/environment. Viewer/editor roles can inspect endpoints and deliveries; admin/owner roles can manage endpoints and publish. Non-user credentials need corresponding explicit scopes unless they are existing unrestricted management keys. Inspection scopes use `{ "event_webhook": ["read"] }`; endpoint administration, tests, and redelivery use `{ "event_webhook": ["manage"] }`. Scope credentials to the intended project and environment. Successful results are wrapped in `{ "data": ... }`. | Operation | Body | Result | | - | - | - | | `eventWebhook/create` | `environmentId`, `name`, `url`, `eventTypes` | Endpoint and signing secret, returned once | | `eventWebhook/eventTypes` | `environmentId`, optional `after` | Up to 100 retained non-test types in `items`, with `nextCursor` | | `eventWebhook/list` | `environmentId` | Active endpoints; no secrets | | `eventWebhook/update` | `environmentId`, `endpointId`, optional `enabled`, `eventTypes`, `rotateSecret` | Endpoint; new secret only on rotation | | `eventWebhook/delete` | `environmentId`, `endpointId` | Cancels pending work and soft-deletes endpoint | | `event/publish` | `environmentId`, `type`, `data` | `202` receipt with `eventId`, `matchedEndpoints`, `acceptedAt` | | `eventWebhook/test` | `environmentId`, `endpointId` | `202` receipt for a platform test event | | `eventWebhook/deliveries` | `environmentId`, optional `eventId`, `limit` (1–100, default 50) | Most recent deliveries; no customer payloads | | `eventWebhook/attempts` | `environmentId`, `deliveryId` | HTTP codes, sanitized errors, timing, attempt numbers | | `eventWebhook/redeliver` | `environmentId`, `deliveryId` | `202` new delivery for the same event and endpoint | | `eventWebhook/usage` | `environmentId` | Organization-wide usage and limits; additionally requires billing-read access | Use exact event names in `eventTypes`, such as `["order.completed"]`, or `["*"]` to subscribe to all customer events. Event names start with a letter and contain letters, digits, underscores, periods, or hyphens, up to 120 characters. `data` is a JSON object. Endpoint URLs must be HTTPS without embedded credentials or fragments; endpoint URLs cannot be edited currently. Replace an endpoint to change its URL. DNS/IP checks on every delivery prohibit private networks, metadata addresses, HTTP, and redirects, independently of audit URL exceptions. Publish, test, and redelivery require an `Idempotency-Key` header (1–256 characters). Publish keys are scoped to the organization/environment for 24 hours; JSON object key ordering is ignored. Reusing a key with different content returns `409`. Idempotent retries return the original receipt without consuming more usage or ingestion capacity. Redelivery keys are scoped to the environment/redelivery operation and remain valid for the retained delivery's lifetime. Test keys use a separate namespace. Use a new key for each distinct operation. ```sh Publishing examples theme={null} # Create an endpoint. Save the returned signingSecret privately. curl "$SHIPD_API_URL/api/v1/rpc/eventWebhook/create" \ -H "Authorization: Bearer $SHIPD_MANAGEMENT_KEY" \ -H 'Content-Type: application/json' \ -d '{"environmentId":"env_123","name":"Orders","url":"https://example.com/shipd","eventTypes":["order.completed"]}' # Publish an event with a stable key for retries of this application operation. curl "$SHIPD_API_URL/api/v1/rpc/event/publish" \ -H "Authorization: Bearer $SHIPD_MANAGEMENT_KEY" \ -H 'Content-Type: application/json' \ -H 'Idempotency-Key: order-123-completed' \ -d '{"environmentId":"env_123","type":"order.completed","data":{"orderId":"ord_123"}}' ``` ## Usage and limits Webhook allowances are separate from pooled SDK requests. New subscriptions receive these organization-wide hard caps; Pro Annual and Teams Annual receive the same monthly allowances as their monthly plans. | Plan | Deliveries/month | Endpoints | Retention | Accepted requests/month | Requests/minute | Reserved storage | | - | -: | -: | -: | -: | -: | -: | | Free | 1,000 | 1 | 7 days | 2,000 | 60 | 16 MiB | | Pro | 10,000 | 5 | 14 days | 20,000 | 300 | 128 MiB | | Teams | 50,000 | 15 | 30 days | 100,000 | 1,000 | 512 MiB | | Enterprise default | 100,000 | 100 | 30 days | 200,000 | 1,000 | 1,024 MiB | Enterprise contracts can override grants. Operational ceilings remain 100 endpoints, 30 days of retention, 1,000 accepted requests per minute, and 1 GiB of reserved storage, even for unlimited billing grants. Explicit zero grants are enforced; zero retention prevents new events, tests, and redeliveries. Existing subscriptions with explicit beta grants retain 1,000 deliveries, one endpoint, and seven-day retention until migrated. Missing webhook grants fall back to the plan's allowances above. Your organization's effective usage view shows the applicable limits. Migration preserves month-to-date reservations and accepted work. ### Environment ingestion rates Each environment also has a fixed UTC minute limit: **30 accepted requests/minute for production**, **10 for development**. The `isProduction` mark selects the default; free-form environment labels do not. The effective cap is the smaller of this value and your organization's ingestion rate shown above. Environment buckets are independent; the organization cap still protects total traffic and does not reserve capacity for any environment. Set `webhookIngestionPerMinute` through `environment/create` or `environment/update` to override the default with an integer from `0` to `1000`. Set it to `null` to restore the default; `0` pauses new work in that environment. Existing environment management permissions apply. Changing the production mark changes the default immediately; an explicit override remains in effect. Changing a limit does not reset the current bucket. Publishing, free tests, and manual redeliveries each consume one request from both minute buckets and monthly ingestion. Automatic delivery retries and idempotent retries consume no extra capacity. Admission is atomic across API instances: rejection stores no event or delivery and charges no quota. `429 rate_limited` identifies the organization or environment cap; `Retry-After` gives whole seconds (rounded up, minimum one) until the rejected UTC minute ends. Wait before retrying with the same idempotency key. `eventWebhook/usage` returns the organization cap as `ingestionLimitPerMinute` and the requested environment's effective cap as `environmentIngestionLimitPerMinute`. The existing organization webhook rollout gate applies before admission; disabling it rejects new work without consuming capacity while accepted deliveries continue. Reserved storage counts each stored UTF-8 envelope plus 1 KiB of event metadata and 8 KiB per logical delivery, including its complete automatic retry budget. This is a storage allowance unit, not a physical disk measurement. Manual redelivery reserves another 8 KiB. Events with no subscribers reserve their envelope and metadata too. Expired records release storage when purged; storage does not reset at the start of a month. Existing stored work can temporarily exceed a downgraded cap. Each matching endpoint reserves one delivery unit in the acceptance transaction. Retries are included, even if an endpoint never succeeds. Manual redelivery reserves another unit. Platform test events and their redeliveries are free but share monthly ingestion, ingestion rate, and storage caps. Events with no subscribers are accepted with zero delivery units and still count against ingestion and reserved-storage limits. Event request bodies are limited to 64 KiB. All-or-nothing acceptance rejects a publish if its full fan-out would exceed the allowance, returning `quota_exceeded` (`403`) with the exhausted allowance in the message. Rejection stores no event or delivery and charges no usage. Check `eventWebhook/usage` for `storageBytes`, `storageLimitBytes`, `ingested`, and `ingestionLimitPerMonth`. Accepted deliveries continue after quota exhaustion or a downgrade. Monthly delivery and ingestion counters reset at 00:00 UTC on the first day of each calendar month, including annual subscriptions. Reservations survive event expiry and endpoint deletion. If a downgrade leaves more endpoints than allowed, remove excess endpoints before publishing, testing, or requesting new redeliveries. Existing endpoints are not automatically disabled or deleted, and accepted work keeps its original expiry. Idempotent retries of accepted requests still return their original receipt at the cap. Paid webhook overage is not available; SDK additional-usage settings never authorize it. New work refreshes your billing grants before admission. If billing cannot be reached, new endpoint creation, publishing, tests, and manual redelivery return `503` until it recovers. Reads and already accepted deliveries continue. A downgrade applies to requests that observe the new active grant; work already being accepted can finish under the grant it read. Check your organization's effective limits before rollout. ## Delivery and receiver verification The immutable JSON envelope contains `id`, `specVersion: "1"`, `type`, `organizationId`, `projectId`, `environmentId`, `acceptedAt`, `test`, and `data`. Subscription matching happens once at acceptance. Later subscription edits only affect future events. Test events have type `shipd.webhook.test`, `test: true`, and are sent only to the selected enabled endpoint. Delivery headers: * `x-shipd-event-id`: stable across retries and manual redelivery. * `x-shipd-delivery-id`: stable across automatic retries; new on manual redelivery. * `x-shipd-timestamp`: Unix seconds, refreshed for each attempt. * `x-shipd-signature`: `sha256=` HMAC-SHA256 of `timestamp.eventId.rawBody`. * `x-shipd-signature-previous`: the same signature using the previous secret, supplied during a 24-hour rotation overlap. Verify against the exact raw request bytes before parsing JSON. Reject timestamps outside a five-minute tolerance, compare signature bytes in constant time, and deduplicate processing using the event ID. Persist or enqueue the event before acknowledging a `2xx` response. At-least-once delivery can produce duplicates; ordering is not guaranteed. A successful webhook response records delivery, not completion of the receiver's business workflow. A rotation returns the new secret once. Receivers using the old secret can verify the previous-signature header during the overlap while updating their stored secret. Another rotation is rejected until the overlap ends. Never put signing secrets or full customer payloads in logs. Each endpoint has one leased in-flight delivery across workers. Attempts time out after ten seconds. Network failures, `429`, and `5xx` retry with jitter around 5 seconds, 30 seconds, 2 minutes, 10 minutes, 30 minutes, 1 hour, and 2 hours. There are at most eight claimed attempts, including attempts interrupted by a worker crash. Other non-`2xx` HTTP statuses fail immediately. A dead worker's 30-second lease can be reclaimed; stale completions cannot overwrite a later claim. Crash-interrupted attempts may have no HTTP result in attempt history. Disabling an endpoint pauses queued work; re-enabling resumes retained work. Deleting an endpoint cancels queued work. Already in-flight requests can finish at the remote receiver. Archived projects/environments are not delivered until restored. Pending work remains reserved while paused. Project transfer removes webhook endpoints and customer event payloads before changing ownership; source usage stays charged. Customers must configure new endpoints in the destination organization. Expired event payloads and their delivery/attempt history are purged hourly by the webhook worker once every delivery has completed, failed, or been cancelled. Pending deliveries keep their payload past expiry and remain eligible for retries; paused work can therefore fill the storage allowance and block new admission. Resume or delete the endpoint to resolve paused work. Cleanup never evicts pending work to make room. Changing retention affects new events only currently. ## Rollout availability When customer webhooks are disabled for your organization, endpoint creation, publishing, tests, and manual redelivery return `403` without accepting work or reserving usage. Endpoint and delivery reads, attempt inspection, usage, endpoint updates, and deletion remain available under normal permissions. Previously accepted deliveries continue, and retention still applies. A hidden dashboard navigation entry does not mean existing deliveries stopped. ## Export delivery logs Enterprise organizations can download retained delivery logs from **Webhooks** → **Delivery history** → **Export logs** for the selected environment. The JSON file includes delivery and event IDs, endpoint IDs, event types, test markers, statuses, timestamps, and completed attempt results (HTTP status, error, and duration). Payloads and signing secrets are excluded. You need `eventWebhook.read` access. The typed management client exposes `eventWebhook.export({ environmentId, limit?, cursor? })`. Each response contains `items` and `nextCursor`; pass `nextCursor` unchanged as `cursor` until it is `null`. Pages default to 500 deliveries and allow up to 1,000. Each exported page creates an audit event. Pagination excludes deliveries created after the first page's cutoff. Statuses and attempts reflect each page's read time; this is not a single database snapshot across pages. Expired events are excluded and normal retention continues during export. Export remains available when webhook publishing is disabled. # Edge API Source: https://docs.useshipd.com/reference/edge-api Data-plane HTTP and WebSocket routes the SDK uses. ## Overview The edge is the data plane: Server SDKs download snapshots; browser SDKs request evaluated values. Both send events and open realtime streams here. The TypeScript SDK calls these routes for you; use this page when you write your own client or debug traffic. | | Value | | - | - | | Base URL | `https://edge.useshipd.com` (local: `http://localhost:8787`) | | WebSocket gateway | `wss://ws.useshipd.com` (path `/sdk/v1/stream`) | | Authentication | `Authorization: Bearer shipd_sdk_…` | | Rate limit | 6,000 requests per minute per SDK key at the edge rate limiter (`429` with `Retry-After` when exceeded). A separate per-minute admission limit also applies, and your plan's monthly allowance is in [Usage and limits](/reference/usage-and-limits). | ## Authentication Only SDK keys work on the edge. Each key is bound to one organization, project, and environment, and carries explicit data-plane scopes: | Scope | Routes | Key types | | - | - | - | | `snapshot:read` | `GET /sdk/v1/snapshot` | Server only | | `snapshot:read` | `POST /sdk/v1/evaluate` | Server and client | | `events:write` | `POST /sdk/v1/events` | Server and client | | `stream:connect` | `POST /sdk/v1/stream-ticket`, `WS /sdk/v1/stream` | Server and client | | `identity:read` | `GET /sdk/v1/identity` | Server only | A missing scope returns `403`. A management API key, service account token, or any other credential returns the same generic `401` as an invalid SDK key. Authenticated traffic is limited per key by Cloudflare's distributed rate limiter. The edge usage rollup sends only key ids (never secrets) to the control plane and updates each key's `lastUsedAt` at most once per minute. See [SDK keys, management API keys, and service account tokens](/concepts/keys). ## GET /sdk/v1/snapshot Returns the current snapshot for the key's environment. Requires a server SDK key; client keys receive `403`. ```http theme={null} GET /sdk/v1/snapshot HTTP/1.1 Host: edge.useshipd.com Authorization: Bearer shipd_sdk_server_… If-None-Match: "snapshot-42" ``` **Authorization** `string` *required* `Bearer` followed by an SDK key with `snapshot:read`. **If-None-Match** `string` The `ETag` from the previous response. The edge returns `304` if the snapshot has not changed. **Responses** | Status | Meaning | | - | - | | `200` | Body is a `FlagSnapshot`. Headers: `ETag: "snapshot-"`, `Cache-Control: no-cache`. | | `304` | Unchanged since `If-None-Match`. | Browser evaluation merges privacy-safe edge geolocation under explicit attributes when `automaticTraits` is enabled. Raw IP addresses and coordinates are never returned. ```json Example 200 body theme={null} { "schemaVersion": 1, "environmentKey": "production", "version": 42, "flags": { "new-checkout": { "key": "new-checkout", "type": "boolean", "enabled": true } } } ``` The example is abbreviated. See [Snapshots](/concepts/snapshots) for the full envelope. **Errors** | Status | Cause | | - | - | | `401` | Invalid, revoked, or non-SDK credential | | `403` | Key lacks `snapshot:read` | | `404` | No snapshot has been published for this environment yet | | `429` | Rate limit exceeded; retry after `Retry-After` | **Related:** [Snapshots](/concepts/snapshots) · [Local evaluation](/concepts/local-evaluation) ## POST /sdk/v1/evaluate Evaluates requested flags at the edge using the key's environment. Returns values and reasons, excluding targeting rules, audience definitions, rule ids, alternative values, and unrequested flags. Requires `snapshot:read` and `Content-Type: application/json`. ```json Example request body theme={null} { "keys": ["new-checkout"], "userId": "usr_8f2k19", "attributes": { "plan": "pro" }, "automaticTraits": true } ``` `keys` accepts up to 100 strings, each 1–256 characters. Optional `userId` has the same length bound. Optional `attributes` accepts up to 100 scalar traits, with keys up to 128 characters and strings up to 1,024 characters. Optional `segmentIds` accepts up to 100 strings of 1–256 characters. `automaticTraits` defaults to `true`; explicit attributes override edge geolocation. Bodies are limited to 256 KiB. ```json Example 200 body theme={null} { "version": 42, "environmentId": "env_production", "values": { "new-checkout": { "value": true, "reason": "rule_match" } } } ``` **Returns** `200` with `Cache-Control: no-store`. Unknown keys return `{ "reason": "not_found" }` without a value. Errors: `401` for invalid credentials, `403` for missing scope, `404` before publication, `413` for oversized bodies, `422` for invalid input, and `429` for rate limits. Public client keys do not authenticate application users. Keep secret flags and access control behind your own authenticated server endpoint. **Related:** [Browser SDK](/sdks/browser) · [Keys](/concepts/keys) ## POST /sdk/v1/events Accepts a batch of evaluation, diagnostic, and `identify` events. ```http theme={null} POST /sdk/v1/events HTTP/1.1 Host: edge.useshipd.com Authorization: Bearer shipd_sdk_server_… Content-Type: application/json ``` **Content-Type** `string` *required* Must be `application/json`. **sentAt** `string` ISO-8601 time the batch was sent. Optional. When present it must be an ISO-8601 timestamp. The TypeScript SDK always sends it. **events** `Event[]` *required* 1–100 events. The whole body must be 256 KiB or smaller. Evaluation events with a `userId` also register or update the evaluated entity, even without an `identify` event. Anonymous-only evaluations do not create named entities. Every event has a `type` and an ISO `ts`. Evaluation, error, unregistered-flag, identify, and timing events also carry `snapshotVersion`, which may be `null` before a snapshot is available. | `type` | Extra fields | | - | - | | `evaluation` | `key`, `reason`, `value`, `userId`, `traits`, `snapshotVersion` | | `unregistered_flag` | `key`, `snapshotVersion` | | `error` | `message`, `snapshotVersion` | | `version_skew` | `previousVersion`, `currentVersion` | | `identify` | `userId`, `traits`, `snapshotVersion` | | `timing` | `stage`, `durationMs`, `snapshotVersion` | ```json Example request body theme={null} { "sentAt": "2026-08-18T16:04:00.000Z", "events": [ { "type": "evaluation", "ts": "2026-08-18T16:03:59.900Z", "key": "new-checkout", "reason": "fallthrough", "value": true, "userId": "usr_8f2k19", "snapshotVersion": 42 }, { "type": "unregistered_flag", "ts": "2026-08-18T16:03:59.910Z", "key": "typo-flag", "snapshotVersion": 42 }, { "type": "error", "ts": "2026-08-18T16:03:59.920Z", "message": "snapshot fetch failed: HTTP 503", "snapshotVersion": 42 }, { "type": "version_skew", "ts": "2026-08-18T16:03:59.930Z", "previousVersion": 41, "currentVersion": 42 }, { "type": "identify", "ts": "2026-08-18T16:03:59.940Z", "userId": "usr_8f2k19", "traits": { "plan": "pro" }, "snapshotVersion": 42 } ] } ``` **Responses** | Status | Meaning | | - | - | | `202` | Accepted. The edge validates every event before accepting the batch. `identify` events are durably enqueued before the response. | Evaluation analytics are stored only for production environments when analytics is configured; non-production evaluation events are never stored. Client SDK `identify` events also pick up `country`, `region`, `city`, and `timezone` from the request; explicit traits win. Server SDK keys are not enriched. Disable events in the SDK with `events: false`. **Errors** | Status | Code | Cause | | - | - | - | | `401` | | Invalid, revoked, or non-SDK credential | | `403` | | Key lacks `events:write` | | `413` | `payload_too_large` | Body larger than 256 KiB | | `422` | `validation_error` | Wrong `Content-Type`, or a malformed batch or event | | `429` | `rate_limited` | Rate limit exceeded; retry after `Retry-After` | | `500` | `internal` | The queue failed. The error is retryable; the edge never acknowledges data it did not queue. | **Related:** [Identify users](/flags/identify-users) · [Usage and limits](/reference/usage-and-limits) ## POST /sdk/v1/stream-ticket Mints a short-lived HMAC ticket for authenticating the WebSocket stream. Browsers cannot set `Authorization` on a WebSocket, so the SDK mints a ticket with the Bearer header first. ```http theme={null} POST /sdk/v1/stream-ticket HTTP/1.1 Host: edge.useshipd.com Authorization: Bearer shipd_sdk_client_… ``` **Authorization** `string` *required* `Bearer` followed by the same SDK key you use for snapshot fetches. Requires `stream:connect`. **Responses** | Status | Meaning | | - | - | | `200` | Body: `{ "ticket", "expiresAt", "ttlSeconds" }`. Header: `Cache-Control: no-store`. The default TTL is five minutes. | ```json Example 200 body theme={null} { "ticket": "…", "expiresAt": "2026-08-18T16:09:00.000Z", "ttlSeconds": 300 } ``` **Errors** | Status | Cause | | - | - | | `401` | Invalid, revoked, or non-SDK credential | | `403` | Key lacks `stream:connect` | | `429` | Rate limit exceeded; retry after `Retry-After` | **Related:** `WS /sdk/v1/stream` (below) ## GET /sdk/v1/identity Returns the stored trait overlay for an identified user to server SDK keys with `identity:read`. Client SDK keys receive 403. Current server SDKs do not fetch the overlay automatically; pass traits in the evaluation context. Browser clients cannot load it with their client SDK key. ```http theme={null} GET /sdk/v1/identity?userId=usr_8f2k19 HTTP/1.1 Host: edge.useshipd.com Authorization: Bearer shipd_sdk_server_… ``` **userId** `string` *required* The user id passed to `identify()`. **Authorization** `string` *required* `Bearer` followed by a **server** SDK key with `identity:read`. **Responses** | Status | Meaning | | - | - | | `200` | Body: `{ "attributes", "name", "updatedAt" }`. Header: `Cache-Control: no-store`. | ```json Example 200 body theme={null} { "attributes": { "plan": "pro" }, "name": "Ada Lovelace", "updatedAt": "2026-08-18T16:03:59.940Z" } ``` **Errors** | Status | Cause | | - | - | | `401` | Invalid, revoked, or non-SDK credential | | `403` | Client SDK key, or key lacks `identity:read` | | `404` | No overlay stored for this user. The SDK keeps its local context. | | `422` | `userId` is missing | **Related:** [Identify users](/flags/identify-users) · [SDK](/reference/sdk) ## WS /sdk/v1/stream Pushes snapshot invalidations for one environment. The channel never carries snapshots or analytics payloads; after an invalidation, you fetch the snapshot over HTTP. ```text theme={null} wss://ws.useshipd.com/sdk/v1/stream?ticket=… ``` **ticket** `string` *required* A ticket from `POST /sdk/v1/stream-ticket`. **1. Mint a ticket** Call `POST /sdk/v1/stream-ticket` with your SDK key. The TypeScript SDK does this before each connect. **2. Connect** Open `wss://ws.useshipd.com/sdk/v1/stream?ticket=…`. The ticket must be valid, unexpired, and bound to the environment of an active SDK key. **3. Receive connected** Wait for `connected` with `connectionId`, `environmentId`, and `snapshotVersion`. The socket is already bound to that environment's fanout. **4. Recover gaps (optional)** Send `subscribe` with the same `environmentId` and a stale `lastKnownVersion` only when you need gap recovery, for example when configuration changed between `connected` and client registration. Subscribing to another environment is rejected. **5. Handle updates** On `snapshot.updated` or `snapshot.resync`, fetch the snapshot with `GET /sdk/v1/snapshot`. | Message | Direction | Fields | | - | - | - | | `connected` | Server → client | `connectionId`, `environmentId`, `snapshotVersion` | | `subscribe` | Client → server | `environmentId`, `lastKnownVersion` | | `snapshot.updated` | Server → client | `environmentId`, `version` | | `snapshot.resync` | Server → client | `reason` (`version_gap`), sent when a `subscribe` reveals more than one missed version | | `ping` / `pong` | Client → server / server → client | Application keepalive | | `error` | Server → client | `code`, `message` | Application ping/pong plus a transport heartbeat keep the socket alive. **Errors.** Client-facing authentication errors are generic. Revoked keys are disconnected. **Revocation.** Revoked keys stop authorizing new HTTP calls as revocation propagates. Existing sockets revalidate at least every 60 seconds. The end-to-end revocation target is 120 seconds. **Deprecated: `?sdkKey=` authentication.** Passing the SDK key in the URL is deprecated because URLs can end up in proxy and access logs. Migrate to `POST /sdk/v1/stream-ticket` and `?ticket=`. Legacy authentication is rejected by default. Compatibility support will not be removed before March 1, 2027; migrate clients to tickets before connecting. **Related:** [Architecture](/concepts/architecture) · [What happens if shipd is down?](/concepts/local-evaluation#what-happens-if-shipd-is-down) ## Compatibility The SDK supports snapshot schema `1` and stream protocol `1`. It rejects newer schemas and keeps the last good snapshot. Related: [SDK](/reference/sdk) · [Node.js and server runtimes](/sdks/node) · [Browser](/sdks/browser) · [Errors](/reference/errors) # Enterprise identity Source: https://docs.useshipd.com/reference/enterprise-identity OIDC, organization access, account linking, sessions, and recovery rules. ## Overview Identity configuration belongs to an organization. OIDC authenticates users; optional inbound SCIM manages membership. SAML is not supported. ## Authentication rules | Control | Behavior | | - | - | | OIDC | Signed ID token, issuer, client audience, expiry, state, nonce and PKCE checks | | Domain routing | Requires verified ownership and an enabled provider; ambiguous selection requires a provider ID | | Linking | Work email must belong to the provider's verified domain; SCIM linking preserves an existing verified account's profile | | Provisioning | New members receive `viewer`; active SCIM requires an active directory identity matched by OIDC subject | | Enforced SSO | Checked for the destination organization, including existing browser and CLI sessions | | Owner recovery | Independent password/passkey remains available; required shipd MFA still applies | | MFA | A successful shipd challenge is required; enrollment or IdP MFA claims alone do not satisfy it | | Provider change/removal | Provider sessions must authenticate again; removal requires independent credentials and directory decommissioning | | Password compatibility | Password login remains available; it does not unlock an enforcing organization for non-owners | ## Offboarding Directory deactivation removes ordinary and administrator memberships. Owners remain for recovery and must be removed or transferred explicitly. Directory-inactive owners cannot authenticate through that SCIM identity. IdP logout alone does not end shipd sessions; revoke sessions or deactivate through SCIM. ## Errors and audit Login failures show a generic error. Provider secrets and tokens are excluded from audit payloads. Provider configuration, domain verification, enforcement, provisioning, and recovery policy changes are audited. Related: [Connect organization single sign-on](/enterprise/sso) · [Provision members with SCIM](/enterprise/scim) · [SCIM provisioning](/reference/scim). # Errors Source: https://docs.useshipd.com/reference/errors Every shipd error in one place: CLI exit codes and error codes, control-plane API errors, edge API statuses, and SDK errors. ## Overview This page lists every error shipd returns and how to fix it: `shipd` exit codes and error codes, the control-plane API error envelope, edge API statuses, and the errors the `shipdit` SDK throws or reports to `onError`. For symptoms such as "my flag isn't updating", start with [Troubleshooting](/resources/troubleshooting). ## CLI exit codes | Code | Meaning | Common causes | Fix | | - | - | - | - | | `0` | Success | Push applied or had nothing to do; diff found no drift | — | | `1` | General error | Not authenticated; `403 forbidden`; invalid `shipd.config.ts`; project or environment not found; confirmation declined or no TTY; unreachable API; command usage error | Read the `Error:` line. See [CLI error codes](#cli-error-codes). | | `2` | Drift | `shipd diff --exit-code` found creates, updates, or remote-only flags | Run `shipd push`, or `shipd pull` if the server is right. | | `3` | Sync conflict or server `409` | Unsynced local targeting on pull; remote targeting changes since the last baseline; a flag changed on the server after the plan; a pending approval request already exists for the flag and environment; a definition change touches a project with an approval policy | See [Why did shipd push return a conflict?](/config-as-code/conflicts) | | `4` | Unlinked | `shipd diff --exit-code` found unlinked flags. Current servers do not report them. | Treat like `2`. | | `5` | Pending approval | `shipd push` queued one or more changes for review. They are not live. | Ask a reviewer to approve the request. See [Approvals](/operations/approvals). | Exit codes are defined per command in the [CLI reference](/reference/cli#exit-codes). ## CLI error codes Human output prints `Error: ` on stderr. With `--json`, stderr gets: ```json theme={null} { "error": { "code": "validation_error", "message": "Environment is required. Pass --env, set SHIPD_ENV, or use a management key / service-account token bound to an environment." } } ``` Errors from the API keep their [control-plane code](#control-plane-api-errors). The CLI adds these on its own: | Code | Message | Fix | | - | - | - | | `validation_error` | `Project is required. Pass --project, set SHIPD_PROJECT, or use a management key / service-account token bound to a project.` | Pass `--project` or bind the credential to a project. | | `validation_error` | `Environment is required. Pass --env, set SHIPD_ENV, or use a management key / service-account token bound to an environment.` | Pass `--env`. | | `validation_error` | `Organization mismatch: API key is bound to "", but --org/SHIPD_ORG is "". …` | Remove `--org` / `SHIPD_ORG`, or use a credential for that organization. | | `validation_error` | `Failed to load config : ` | Fix the TypeScript or `defineFlags` error in `shipd.config.ts`. See [validation rules](/reference/config#validation-rules). | | `validation_error` | `shipd.config.ts must export defineFlags(...) result` | `export default defineFlags({ … })`. | | `validation_error` | `Invalid flag definitions: : ` | Fix the named flag. | | `validation_error` | `Invalid sync baseline: ` | Restore the baseline from a valid copy; do not treat corrupted state as proof of a successful sync. | | `conflict` | `Flag "" targeting changed in the dashboard since the last sync.` | Reconcile code and dashboard targeting, or deliberately overwrite with `push --force`. | | `conflict` | `Pull would overwrite local targeting changes for "".` | Save those edits separately and reconcile, or deliberately replace them with `pull --force`. | | `validation_error` | `Push cancelled (pass --yes or --ci to apply non-interactively)` | Answer `y`, or pass `--yes` in scripts. | | `validation_error` | `Archive cancelled` | Answer `y`, or pass `--yes`. | | `validation_error` | `Variant flags require --variants (e.g. --variants control,treatment)` | `shipd flags create` with `--type variant` needs `--variants`. | | `validation_error` | `--variants is only valid with --type variant (got --type )` | Drop `--variants`. | | `validation_error` | `Unsupported flag type: ` | Use `boolean`, `variant`, `number`, or `json`. | | `validation_error` | Command usage error (unknown option, missing argument) | Run `shipd --help`. | | `not_found` | `Config file not found: ` | Run from the project root or pass `--flags-config`. | | `not_found` | `Project not found: ` / `Environment not found: ` | Check `shipd projects list` / `shipd environments list`, and the credential's binding. | | `unauthenticated` | `Device authorization timed out` / `Device authorization failed` | Run `shipd login` again and approve within the time limit. | | `unauthenticated` | `Device authorization did not return a management API key. Approve org, project, and environment in the browser.` | Choose all three in the browser. | | `internal` | Any unexpected error, such as a network failure | Check `--api-url` / `SHIPD_API_URL`. In CI it must be `https://api.useshipd.com`. | ## Control-plane API errors Every non-success response from `https://api.useshipd.com/api/v1` has this envelope. Stack traces are never returned. ```json theme={null} { "error": { "code": "validation_error", "message": "Request validation failed", "requestId": "req_01", "details": {} } } ``` | Status | Code | Meaning | CLI exit | | - | - | - | - | | 401 | `unauthenticated` | Credential is missing, invalid, expired, revoked, or has no active organization. | `1` | | 403 | `forbidden` | The principal cannot perform the action. Includes environment-bound credentials attempting `flag.create`, `flag.update`, or `flag.archive`. | `1` | | 403 | `quota_exceeded` | An SDK or bulk quota is exhausted. | `1` | | 404 | `not_found` | The resource is missing or hidden from this principal. | `1` | | 409 | `conflict` | Version, uniqueness, approval, or idempotency state conflicts. | `3` | | 413 | `payload_too_large` | A documented batch or body limit was exceeded. | `1` | | 422 | `validation_error` | The request does not match its schema. | `1` | | 429 | `rate_limited` | Retry after the delay in `Retry-After`. | `1` | | 500 | `internal` | Unexpected failure. Report `requestId` to support. | `1` | | 503 | `tenant_migrating`, `tenant_unavailable` | Organization data is temporarily unavailable. Retry safely. | `1` | Retry, idempotency, and pagination rules are in [Control-plane API](/reference/control-plane-api). ### Push conflict messages `shipd push` returns these `409 conflict` messages. None of them applies any part of the push. | Message | Cause | | - | - | | `Flag "" changed remotely (expected version , remote ). Pull and retry, or pass --force.` | The flag definition changed after the plan. | | `Flag "" environment state changed remotely (expected environment version , …). Pull and retry, or pass --force.` | The target environment's state (fallthrough, rules, enabled) changed after the plan. | | `A pending approval request already exists for this flag in this environment` | An earlier push or dashboard edit is waiting for review. | | `This operation affects an environment protected by approval policy and cannot be submitted for review. No changes were applied.` | A create, archive, or definition change in a project with an approval policy. | | `Flag "" was created concurrently. Pull and retry.` | Someone created the same key during your push. | ## Edge API statuses Returned by `https://edge.useshipd.com/sdk/v1`. The SDK handles all of them without throwing. | Status | Code | Meaning | SDK behavior | | - | - | - | - | | 304 | — | Snapshot unchanged since the sent `ETag` | Keeps the current snapshot. | | 401 | — | SDK key is invalid or revoked, or the credential is not an SDK key | Keeps the last good snapshot, else defaults. Reports `snapshot fetch failed: HTTP 401`. | | 403 | — | The SDK key lacks the scope for the route (for example, `identity:read` with a client key) | Reports the failure to `onError`. | | 413 | `payload_too_large` | Events batch over 100 events or 256 KiB | Reports `events flush failed: HTTP 413`. | | 422 | `validation_error` | Malformed events batch | Reports `events flush failed: HTTP 422`. | | 429 | — | Over the per-key rate limit (6,000 requests per minute at the edge rate limiter). `Retry-After` is set. | Keeps the last good snapshot, reports `snapshot fetch failed: HTTP 429`, and retries on the next poll. | See [Edge API](/reference/edge-api). ## SDK errors ### Thrown errors Only these throw. Evaluation methods (`isEnabled`, `getVariant`, `getNumber`, `getJson`) never throw, and `ready()` never rejects for network errors. | Message | Thrown by | Fix | | - | - | - | | `shipdit: sdkKey is required` | `createClient` | Pass `sdkKey`. Check that the environment variable is set where the code runs. | | ``shipdit: `endpoint` was removed…`` | `createClient` | Remove `endpoint`. For shipd development and tests only, use `overrides.unsafeEndpoint`. | | ``shipdit: `streamEndpoint` was removed…`` | `createClient` | Replace it with `stream: true`. To use another gateway, set `overrides.streamEndpoint`. | | `shipdit: overrides.unsafeEndpoint must…` / `shipdit: overrides.streamEndpoint must…` | `createClient` | Pass an absolute URL (`https://…`; the stream also accepts `wss://`) without credentials, a query, or a fragment. | | `shipdit: identify requires userId` | `identify` | Pass a non-empty `userId`. Use `reset()` on logout instead of `identify({ userId: "" })`. | | `shipdit: useShipdClient must be used within ShipdProvider` | `useShipdClient` and the hooks built on it | Render the component inside `ShipdProvider`. | ### onError messages Background failures go to the `onError` option as `Error` objects. The client keeps serving the last good snapshot, a cached or bootstrapped snapshot, or `defaults`. | Message | Meaning | | - | - | | `snapshot fetch failed: HTTP ` | The edge returned a non-2xx status other than `304`. `401` means the key is invalid or revoked. | | `snapshot fetch timed out` | No response within `fetchTimeoutMs` (default 10,000 ms). | | `snapshot fetch aborted` | The request was cancelled, usually by `close()`. | | `Unsupported snapshot schema version ; SDK supports version ` | The snapshot format is newer than this SDK. Upgrade `shipdit`. | | `malformed snapshot ignored` | The response was not a valid snapshot. | | `shipdit: snapshot version still below notified after 5 attempts` | A realtime update announced a version the edge did not serve after 5 fetches. The next poll catches up. | | `fetch is not available in this runtime` | No global `fetch`. Pass the `fetch` option. | | `identity fetch failed: HTTP ` / `identity fetch timed out` / `identity fetch aborted` | Loading remote traits after `identify()` failed. Local evaluation continues with session traits. | | `stream ticket mint failed: HTTP ` | Minting a WebSocket ticket failed. Polling continues. | | `stream ticket mint failed: invalid body` / `: missing ticket` / `: missing expiry` | The ticket response was malformed. Polling continues. | | `stream ticket mint timed out` / `stream ticket mint aborted` | Ticket request timed out or was cancelled. | | `shipdit: WebSocket is not available in this runtime` | `stream` is `true` but there is no `WebSocket`. On Node 20, pass the `WebSocket` option (for example, from `ws`) or omit `stream`. Polling continues. | | `shipdit stream: : ` | The WebSocket gateway sent an error. | | `shipdit stream: unauthenticated` | The gateway rejected the key. The stream closes; polling continues. | | `shipdit stream: unsupported_protocol` | The gateway does not support this SDK's stream protocol. Upgrade `shipdit`. | | `Unsupported WebSocket protocol version ; SDK supports version ` | The gateway uses a newer stream protocol. Upgrade `shipdit`. | | `shipdit stream: unsupported binary frame` / `shipdit stream: malformed server message` | The gateway sent a frame the SDK cannot read. The stream closes; polling continues. | | `events flush failed: HTTP ` / `events flush timed out` / `events flush aborted` | Sending diagnostic events failed. Evaluation is unaffected. | ```ts TypeScript theme={null} // src/flags.ts import { createClient } from "shipdit"; import type { FlagDefinitions } from "./generated/flags"; export const shipd = createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, defaults: { "new-checkout": false }, onError: (error) => console.warn("[shipd]", error), }); ``` ```go Go theme={null} // Check New and Ready errors, then inspect LastError for background request failures. client, err := shipd.New(shipd.Options{ SDKKey: os.Getenv("SHIPD_SDK_KEY"), Defaults: map[string]any{"new-checkout": false}, }) if err != nil { return err } defer func() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if err := client.Shutdown(ctx); err != nil { log.Printf("shipd events: %v", err) } }() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := client.Ready(ctx); err != nil { log.Printf("using defaults: %v", err) } if err := client.LastError(); err != nil { log.Printf("shipd request: %v", err) } ``` **Related:** [CLI reference](/reference/cli) · [Control-plane API](/reference/control-plane-api) · [Edge API](/reference/edge-api) · [SDK reference](/reference/sdk) · [Reliability and data](/reference/reliability-and-data) # Glossary Source: https://docs.useshipd.com/reference/glossary One definition for every shipd term. The docs use these words and only these words. ## Overview Each term below has exactly one meaning across the shipd docs, dashboard, CLI, and SDK. If another tool calls it something else, that name is listed under **Also called** so you can map it — the docs themselves don't use those names. ## Terms | Term | Definition | Also called | | - | - | - | | **Flag** | A named value your app reads at runtime: boolean, variant, number, or JSON. | feature flag, feature toggle, switch, gate | | **Flag definition** | A flag's key, type, variants, description, tags, and lifecycle. Written in `shipd.config.ts`. Shared by every environment in the project. | flag schema | | **Flag state** | Whether a flag is enabled, its targeting rules, and its fallthrough in one environment. Declared in an optional targeting block, or edited in the dashboard when targeting is omitted. | environment config | | **Boolean flag** | A flag whose value is `true` or `false`. Read with `isEnabled`. | feature gate | | **Variant flag** | A flag whose value is one of a fixed list of strings. Read with `getVariant`. | multivariate flag, experiment | | **Number flag** | A flag whose value is a number. Read with `getNumber`. | numeric config | | **JSON flag** | A flag whose value is any JSON value. Read with `getJson`. | remote config, dynamic config | | **`shipd.config.ts`** | The file that declares your project's flag definitions with `defineFlags`. | flagfile, manifest | | **Default** | In `shipd.config.ts`: the fallthrough `shipd push` sets in the environment it targets (it resets the fallthrough whenever they differ). In the SDK's `defaults` option: the value returned when the SDK has no snapshot or the flag isn't in it. | fallback value | | **Fallthrough** | What an environment serves when no targeting rule matches. Also served, skipping all rules, when the flag is disabled. | default serve, default rule, off variation | | **Targeting rule** | An ordered condition list plus a serve. The first rule whose conditions all match decides the value. | rule, targeting | | **Serve** | The value a rule or fallthrough returns: a fixed value or a weighted serve. | variation, return value | | **Weighted serve** | A serve that splits users across values by percentage, stickily. Used for A/B tests. | percentage split, traffic allocation | | **Percentage rollout** | A rule condition that matches a stable percentage of users, bucketed by flag key and `userId`. | gradual rollout, canary | | **Audience** | A reusable set of conditions defined once per project and referenced from rules. Evaluated locally. The condition kind is `segment`. | segment, cohort | | **Evaluation context** | Who is asking: `userId`, `attributes`, and `segmentIds`. Passed per call or set with `identify`. | user context, user object | | **Attribute** | A key-value pair in the evaluation context, such as `plan: "pro"`. Rules match on attributes. | trait, property, custom attribute | | **`identify`** | An SDK call that sets the user for later evaluations on a client. Its `traits` become attributes. | set user, login context | | **Evaluation** | Computing a flag's value for a context, in memory, from a snapshot. | flag check | | **Local evaluation** | shipd's model: the SDK evaluates in your process, never over the network. | in-process evaluation | | **Snapshot** | The JSON document containing everything needed to evaluate every flag in one environment. Versioned per environment. | ruleset, config payload | | **Organization** | Your company account: members, roles, billing, SSO. | tenant, account | | **Project** | A product or codebase inside an organization. Owns flag definitions. | app, workspace | | **Environment** | A deployment target inside a project, such as `development` or `production`. Owns flag state, SDK keys, and a snapshot. At most one per project is marked production. | stage | | **SDK key** | A credential that lets an SDK download one environment's snapshot. `shipd_sdk_server_…` or `shipd_sdk_client_…`. | client-side ID, mobile key, SDK token | | **Management API key** | A personal credential for the CLI and API, bound to one organization, project, and environment. `shipd_mgmt_…`. Created by `shipd login`. | personal API key, access token | | **Service account token** | A credential for CI and automation with explicit scopes. `shipd_sa_…`. | bot token, CI token | | **Push** | `shipd push`: apply `shipd.config.ts` to shipd, then generate types. | deploy, sync | | **Pull** | `shipd pull`: rewrite `shipd.config.ts` from shipd. | export | | **Archive** | Remove a flag from use without deleting its history. Archived flags leave the snapshot. | delete | | **Approval policy** | A rule that requires review before certain flag state changes apply. | change request, four-eyes | | **Edge** | The globally distributed service SDKs download snapshots from: `https://edge.useshipd.com`. | CDN, data plane, relay | | **Control plane** | The API, dashboard, and database where you define and change flags: `https://api.useshipd.com`. | management API, backend | ## Related * [Core concepts](/core-concepts) * [Keys and tokens](/concepts/keys) # Go SDK reference Source: https://docs.useshipd.com/reference/go-sdk Go client options, evaluation methods, identify events, and lifecycle methods. ## Overview Import `github.com/alasti-company/shipd-go` as `shipd`. All evaluation methods are safe to call concurrently and run locally. See [Go](/sdks/go) for a complete example or [OpenFeature](/integrations/openfeature#go) to register shipd with an OpenFeature client. ## New ```go theme={null} func New(options Options) (*Client, error) ``` **options.SDKKey** `string` *required* The environment's server SDK key. | Option | Default | | - | - | | `Defaults` | JSON-compatible values by flag key | | `Context` | Default evaluation context. Per-request values take precedence | | `RefreshInterval` | `30 * time.Second` | | `ReadyTimeout` | `5 * time.Second`. A negative value returns immediately from `Ready` | | `FetchTimeout` | `10 * time.Second` | | `DisableFetchTimeout` | `false`. Set to `true` to use caller and lifecycle deadlines | | `DisablePolling` | `false`; initial fetch still runs | | `Stream` | `false`. Enable WebSocket updates with polling as a fallback | | `Cache` | None. Provide a `SnapshotCache` adapter to load and save validated snapshots and ETags | | `OnError` | None. Provide a callback for background fetch, stream, cache, and diagnostic delivery errors | | `DisableEvents` | `false` | | `FlushAt` | `50`; flush once this many events are buffered (at most 200). Negative flushes on the interval only | | `FlushInterval` | `5 * time.Second`. Negative disables timed flushes | | `Bootstrap` | None. A snapshot (the JSON body of `GET /sdk/v1/snapshot`) served until a newer one is fetched. Makes the client ready immediately; invalid snapshots fail `New` | | `Overrides.UnsafeEndpoint` | Empty, which uses `https://edge.useshipd.com` (`shipd.DefaultEndpoint`). **Unsafe:** for shipd development and tests only, because the URL receives your SDK key. Surrounding whitespace and trailing slashes are trimmed; a plaintext `http` URL to a non-local host logs a warning | | `Overrides.StreamEndpoint` | `https://ws.useshipd.com` | | `HTTPClient` | Default HTTP client, which rejects redirects | Zero durations select defaults. Negative `RefreshInterval` and `FetchTimeout` values are rejected; negative flush options behave as shown above. Custom HTTP clients must honor request contexts and control their own redirect behavior. **Returns** a client that immediately starts fetching a snapshot. **Errors.** Invalid configuration returns an error. Background fetch failures are exposed through `LastError`. ## Evaluation methods ```go theme={null} func (c *Client) IsEnabled(key string, ctx EvaluationContext) bool func (c *Client) GetVariant(key string, ctx EvaluationContext) string func (c *Client) GetNumber(key string, ctx EvaluationContext) float64 func (c *Client) GetJSON(key string, ctx EvaluationContext) any func (c *Client) Evaluate(key string, ctx EvaluationContext) Result func (c *Client) EvaluateDetails(key string, ctx EvaluationContext) EvaluationDetails ``` **key** `string` *required* The flag key, such as `new-checkout`. **ctx** `EvaluationContext` *required* Request-scoped `UserID`, scalar `Attributes`, and optional `SegmentIDs`. Use `shipd.EvaluationContext{}` for anonymous evaluation. Set `UserIDPresent: true` to compare an explicitly empty `UserID`; empty IDs do not satisfy `exists` or provide a rollout bucket. **Returns** the evaluated value. `Evaluate` also returns `Reason`, `RuleID`, and a nullable `SnapshotVersion`. `EvaluateDetails` adds the flag's declared `FlagType` from the same snapshot. JSON values are copied, and JSON numbers decode as `float64`. **Fallback.** Before a snapshot loads or for an unknown key, configured defaults apply. Built-in typed defaults are `false`, `"control"`, `0`, and an empty JSON object. Disabled flags use the snapshot default. Boolean, variant, and number getters use a correctly typed configured default, or their built-in default, when the resulting value has the wrong type. `Evaluate` uses `nil` for an unknown key without a configured default. **Errors.** Evaluation methods return values without errors. Failed refreshes keep the last valid snapshot. Evaluation continues after `Close` with the last snapshot or defaults. Evaluation values that exceed the event payload limit are omitted from telemetry. ## Ready ```go theme={null} func (c *Client) Ready(ctx context.Context) error ``` Waits for the initial snapshot fetch. Provide a deadline to bound startup waiting. **Returns** `nil` once a snapshot loads. A bootstrap or cached snapshot can satisfy readiness before the first network response. **Errors.** Returns the initial fetch error as soon as that attempt fails. The client then serves defaults, and polling (unless disabled) keeps trying. Returns the context error on timeout or cancellation while the first fetch is still in flight, or `ErrClosed` after close, even if a snapshot previously loaded. ## Refresh ```go theme={null} func (c *Client) Refresh(ctx context.Context) error ``` Fetches the current snapshot with ETag support. Concurrent refreshes are serialized. Lower snapshot versions are ignored. Snapshots with malformed evaluation data are rejected as a whole. **Returns** `nil` for a successful fetch or `304` response with an existing snapshot. **Errors.** Request, response, and parsing errors are returned and stored in `LastError`. Returns `ErrClosed` after close. ## Identify ```go theme={null} func (c *Client) Identify(identity Identity) error ``` Queues an identify event for audience insights. It does not change the evaluation context. **identity.UserID** `string` *required* A nonempty user ID of at most 256 UTF-16 code units. `Name` is optional and limited to 256 UTF-16 code units. `Traits` supports at most 100 entries: nonempty keys up to 128 UTF-16 code units, with scalar JSON values or `nil`. Strings are limited to 1024 UTF-16 code units. **Returns** `nil` after queueing, including when events are disabled. **Errors.** Invalid identity data or identify events that exceed the payload limit return a validation error. Returns `ErrClosed` after close. ## Flush ```go theme={null} func (c *Client) Flush(ctx context.Context) error ``` Sends queued evaluation and identify events. The client also flushes automatically every `FlushInterval` and as soon as `FlushAt` events are buffered. The buffer retains at most 200 events. Failed batches are requeued, with the oldest entries dropped on overflow (see `DroppedEvents`). After a failed delivery, automatic retries wait for the next interval. Evaluation events include values, user IDs, and up to 100 scalar traits. Flush splits batches to respect the edge limit of 100 events and 256 KiB per request. **Returns** `nil` after success, with an empty buffer, or when events are disabled. **Errors.** Delivery errors are returned and stored in `LastError`. Returns `ErrClosed` after close, including when events are disabled. Use a bounded context for shutdown flushing. ## LastError ```go theme={null} func (c *Client) LastError() error ``` **Returns** the most recent request failure, or `nil`. A successful refresh or flush, including an empty flush, clears it. ## SnapshotVersion ```go theme={null} func (c *Client) SnapshotVersion() (version int64, ok bool) ``` **Returns** the loaded snapshot's version. `ok` is `false` until the first valid snapshot arrives. Unlike `Evaluate`, it records no event, so it suits health checks. ## DroppedEvents ```go theme={null} func (c *Client) DroppedEvents() uint64 ``` **Returns** how many events were discarded because the 200-event buffer was full, for example while the edge was unreachable. ## Shutdown ```go theme={null} func (c *Client) Shutdown(ctx context.Context) error ``` Stops accepting events, attempts to deliver retained pending events within `ctx` (including events from a background flush that is still in progress), then closes the client even if delivery fails. Events already discarded on buffer overflow cannot be delivered; check `DroppedEvents`. Events recorded after `Shutdown` starts are not delivered. Use it for graceful shutdown with a bounded context. Repeated calls are safe. **Returns** `nil` after events are delivered, or when events are disabled. **Errors.** Returns the flush error if delivery fails or `ctx` expires. The client is closed either way. ```go theme={null} ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if err := client.Shutdown(ctx); err != nil { log.Printf("shipd events: %v", err) } ``` ## Close ```go theme={null} func (c *Client) Close() error ``` Cancels requests, stops background work, and waits for completion, without delivering pending events; use `Shutdown` to deliver them first. `Close` implements `io.Closer`. Repeated calls are safe. **Returns** `nil`. ## Errors | Error | Returned by | Meaning | | - | - | - | | `ErrClosed` | `Ready`, `Refresh`, `Flush`, `Identify` | The client was closed. | | `ErrMalformedSnapshot` | `Refresh`, `Ready`, `New` (with `Bootstrap`) | The snapshot failed validation. The client keeps its last valid snapshot. | | `ErrUnsupportedSchema` | `Refresh`, `Ready`, `New` (with `Bootstrap`) | The snapshot schema is newer than this SDK. Upgrade the SDK. The message includes both versions. | Match them with `errors.Is`, because returned errors may wrap them: ```go theme={null} if errors.Is(client.LastError(), shipd.ErrUnsupportedSchema) { log.Print("upgrade the shipd Go SDK") } ``` **Related:** [Local evaluation](/concepts/local-evaluation) · [Go](/sdks/go) ## Flag definitions Go flag definitions live in the `github.com/alasti-company/shipd-go/config` subpackage of the same module. Declare `config.ShipdConfig` directly; the runtime SDK only evaluates flags. See [Go config reference](/reference/config#go-shipdconfig) for its types, validation, export, and defaults methods. # MCP tools Source: https://docs.useshipd.com/reference/mcp The operational MCP tool surface, access boundaries, version checks, and seven-day mutation retry contract. ## Overview The remote MCP endpoint is `https://mcp.useshipd.com/mcp`. Each connection delegates one user's current permissions within one organization and optionally selected projects. [Connect an agent](/operations/connect-an-agent) for client setup. ## Available tools | Resource | Tools | | - | - | | Projects | `project_list`, `project_create`, `project_update` | | Environments | `environment_list`, `environment_create`, `environment_update` | | Flags | `flag_list`, `flag_get`, `flag_create`, `flag_update`, `flag_listEnvironmentStates`, `flag_updateEnvironment`, `flag_toggleEnvironment`, `flag_publishEnvironments` | | Audiences | `segment_list`, `segment_get`, `segment_create`, `segment_update`, `segment_listEnvironmentStates`, `segment_updateEnvironment` | | Evaluated identities | `evaluatedEntity_list`, `evaluatedEntity_get` | | Evaluation diagnostics | `evaluationFact_list`, `evaluationFact_byRule`, `evaluationFact_projectSummary` | | Change review | `mcp_history`, `mcp_approvalStatus`, `mcp_proposeDeletion` | | Progressive rollouts | `release_proposeProgressiveRollout`, `release_rolloutStatus`, `release_explainRolloutDecision` | | Manual release records | `release_list`, `release_get`, `release_create`, `release_update`, `release_transition`, `release_startStage`, `release_assessHealth`, `release_listHealthValidations`, `release_completeStage`, `release_addEvidence` | | Observability connections | `observabilityConnection_list` | Read-only connections discover only read tools. Every call is independently authorized; a tool appearing in discovery does not mean your role permits its use. Project creation requires an all-projects connection. Environment creation defaults to a development environment. Admins and owners with write connections can pass `isProduction: true` to `environment_create`, or `isProduction: true | false` to `environment_update`. Promoting an existing environment removes production status from the project's previous production environment. Production status changes require existing permissions. Approval policies can block production status updates and govern production flag changes; environment creation does not check approval policies. After saving draft changes, call `flag_listEnvironmentStates`, then `flag_publishEnvironments` with the flag ID, selected environments and each state’s `expectedVersion`, plus an `idempotencyKey`. This publishes saved drafts through the existing production permissions and approval policies. Direct deletion and archive tools, billing, identity/security administration, credential issuance, webhook management, and snapshot recovery are outside this surface. [Release records](/reference/releases) keep release intent, manually reported progress, and evidence separate from deployment, publication, approval, and exposure. The [progressive rollout tools](/reference/releases#code-defined-progressive-rollouts) propose a code-defined rollout and explain its decisions. They cannot start exposure or approve production. Legacy release mutations use permanent transactional retry receipts; progressive proposals use the general seven-day MCP replay mechanism described below. ## Mutation inputs ```ts theme={null} // Additional inputs required for MCP mutations. type Mutation = { idempotencyKey: string; // 1–256 printable ASCII characters, without spaces }; type Update = Mutation & { expectedVersion: number; // version returned by the latest resource read }; ``` Use a unique idempotency key for each logical mutation. Read before updating. Use the flag definition version for `flag_update`; use the environment-state version for flag or audience environment updates. Project and environment list responses include metadata versions, distinct from snapshot versions. **Errors.** A stale version returns a conflict. Read the resource again, revise the proposed change, and use a new key for that new operation. There is no force-overwrite tool. ## Retries Mutation outcomes are retained for seven days, scoped to the authorization, organization, and operation. Refreshing an access token does not change this scope. Repeat the same key and unchanged input to retrieve a completed outcome. Changed input under the same key returns a conflict. Concurrent or uncertain outcomes remain in progress so a retry cannot apply the mutation twice. An approval submission retry returns the original request, rather than creating another. If an outcome stays in progress after a service failure, reconcile the resource and change history before taking another action. After seven days, reconcile state before retrying; the replay record may have expired. ## Pending approval A protected flag change returns `outcome: "pending_approval"`, the approval request, and a dashboard review link. It has not been applied. `mcp_approvalStatus` reports the status of your submitted request, subject to current project access. MCP cannot approve, reject, or relax policies. ## Deletion review `mcp_proposeDeletion` (unreleased pending merge and deployment) proposes permanent deletion of a flag, project, environment, or audience. It never deletes directly. Pass the resource's current definition version: ```ts theme={null} type DeletionProposal = { resourceType: "flag" | "project" | "environment" | "segment"; resourceId: string; projectId: string; expectedVersion: number; idempotencyKey: string; }; ``` Open the returned `reviewUrl` in the authenticated dashboard's **Approvals → Deletions** tab. Review the resource, dependent records, consequences, authorizing user and MCP connection. Another person must approve. Every applicable approval policy is enforced, with at least one admin or owner approval; self approval is disabled even if a flag-change policy permits it. Each policy's approval count must be satisfied by its currently eligible reviewers. A changed resource, dependency, environment or approval policy makes the request stale. Submit a new proposal after reading the new state. The authorizing user's current permissions, project access, organization identity policy and connection write grant are checked again before deletion. MCP cannot approve or relax these requirements. Revoke active SDK keys through the dashboard before proposing project or environment deletion. Resolve audience references and other blocking dependencies first. Proposals with more than 1,000 dependent records in any one resource group are rejected. Unlike archive, permanent deletion cannot be restored. Deletion receipts do not expire. Reuse the same key and unchanged input to retrieve the original request; do not rotate the key after an uncertain outcome. Requests expire after seven days without approval. Use `mcp_approvalStatus` to reconcile the outcome. Dashboard deletion history and audit events remain after the resource is gone and identify the authorizing user, client, connection, approvals and outcome without credential values. ## Eligibility and history Active, trialing, and past-due Pro, Teams, and Enterprise organizations qualify. Downgrades remove access when the subscription snapshot is refreshed. Entitlements normally refresh after ten minutes; during a billing outage, a previously verified snapshot is accepted for at most one hour. Unknown eligibility denies access. `mcp_history` returns operational events within your current project access and the organization’s effective audit retention window. It filters operational actions before pagination: ```ts theme={null} type HistoryPage = { events: AuditEvent[]; nextCursor: number | null; }; ``` Pass `nextCursor` as `cursor` on the next call. A null cursor means there are no more events. Changes identify the authorizing user and MCP client/connection. Credential values are redacted. ## OAuth scopes Clients request `shipd:read` for read-only access or `shipd:read shipd:write` for write access. A write-only scope request is rejected. Browser authorization uses S256 PKCE; clients must bind token requests to the MCP resource `https://mcp.useshipd.com/mcp`. # Release records Source: https://docs.useshipd.com/reference/releases Record release plans, evidence, and the action history for manual and authorized rollouts. ## Overview A release record keeps a project's release plan, progress, and supporting evidence in one environment. Manual actions record operator declarations. When configured and explicitly authorized, the controller can publish scoped flag changes and record their results. > [!NOTE] > > Signal-driven progressive rollouts require the `code-release-control` feature flag and a configured Sentry connection. ## Separate intent from observation Release state tracks progress. A manual lifecycle transition records the operator's declaration. When the controller runs an authorized release, it records each flag publication and its read-back result in the action history. Use that history together with deployment and flag state to verify what customers are seeing. The progress response explicitly reports deployment observation as `unknown` and flag, approval, and exposure observations as `not_checked`. Check the deployment system, [flag environment states](/reference/mcp), and [approval status](/reference/approvals) separately. Attach the results as evidence, clearly distinguishing reported claims from verified observations. ## Plan a release ```ts theme={null} // Release plan input, shared by the API and MCP. type ReleasePlan = { title: string; flagIds: string[]; // existing flags in this project; at most 50, no duplicates pullRequest: string | null; // HTTPS URL without credentials commitSha: string | null; // full 40-character hexadecimal SHA deploymentRef: string | null; // external reference, not an execution request audiences: string[]; stages: { id: string; // unique within the plan name: string; audience: string; successCriteria: string[]; healthPolicy?: ReleaseHealthPolicy; // see assessHealth }[]; successCriteria: string[]; }; ``` Include at least one audience, stage, and success criterion. Stage IDs are stable identifiers, not flag targeting rules. A plan can describe an audience without creating or changing it. You can revise the plan only in `preparation` or `awaiting_deployment`; it is frozen from `ready` onward. ## State transitions | Current state | Allowed next states | | - | - | | `preparation` | `awaiting_deployment` | | `awaiting_deployment` | `preparation`, `ready` | | `ready` | `rolling_out`, `paused`, `rolled_back` | | `rolling_out` | `paused`, `rolled_back`, `complete` | | `paused` | `rolling_out`, `rolled_back` | | `rolled_back` | None | | `complete` | None | Every manual transition requires a note. Moving to `ready` requires a PR URL, commit SHA, and deployment reference. Complete stages in plan order while `rolling_out`. All stages must be recorded complete before moving to `complete`. Terminal records still accept evidence. Use the controller commands for pauses and resumes while an authorization is active. ## Authentication and retries All routes use `POST /api/v1/rpc/release/…` with the usual control-plane authentication. Reads require flag-read access. Manual ledger writes require flag-update access. Controller commands require flag state write access. Access is scoped to the release's project and environment. MCP also enforces the connection's organization, project restrictions, write access, and current user permissions. [Control-plane authentication](/reference/control-plane-api#authentication-and-route-restrictions) Every manual mutation requires an `Idempotency-Key` header. MCP callers pass `idempotencyKey` in tool input instead. Generate one key per logical mutation and retain it unchanged with the original input for retries. Manual mutations except creation also require the latest release `expectedVersion`. Provider ingestion uses its event identity instead. The record, action, audit event, and retry receipt commit atomically. Retry identity is scoped to the immutable project, authenticated actor or credential, operation, and key; independent projects do not share keys. Service account tokens and MCP grants have independent retry namespaces. Project transfers preserve retry identity while current organization access still governs replay. Receipts have no time-based expiry in this version, unlike the general API and MCP replay windows. A completed retry returns the saved result without adding an action or evidence twice; changed input under the same key conflicts. Concurrent identical retries serialize and return the same saved result. Current authorization still applies to a replay. On a stale-version conflict, read again and decide whether a new operation is appropriate before submitting revised input with a new key. Do not blindly generate new keys after a timeout. ## create Creates a release in `preparation` within one project and environment. ```ts theme={null} // POST /api/v1/rpc/release/create · MCP release_create create(input: ReleasePlan & { projectId: string; environmentId: string }) ``` **Returns** the created release result in the API's `data` envelope. **Errors.** Invalid or cross-project references are rejected. Creation does not create flags, PRs, or deployments. ## update Replaces the plan before it is frozen. ```ts theme={null} // POST /api/v1/rpc/release/update · MCP release_update update(input: { releaseId: string; expectedVersion: number; plan: ReleasePlan }) ``` **Returns** the updated release result. **Errors.** A stale version or an attempt to revise a frozen plan conflicts. ## transition Records a manual lifecycle transition and its reason. ```ts theme={null} // POST /api/v1/rpc/release/transition · MCP release_transition transition(input: { releaseId: string; expectedVersion: number; state: "preparation" | "awaiting_deployment" | "ready" | "rolling_out" | "paused" | "rolled_back" | "complete"; note: string; }) ``` **Returns** the updated release result. It does not execute the named operational step. **Errors.** Invalid transitions, missing readiness references, incomplete stages, and stale versions are rejected. ## completeStage Records completion of the next planned stage. ```ts theme={null} // POST /api/v1/rpc/release/completeStage · MCP release_completeStage completeStage(input: { releaseId: string; expectedVersion: number; stageId: string; note: string; }) ``` **Returns** the updated release result. **Errors.** The record must be `rolling_out` without an active controller authorization. Unknown, already completed, or out-of-order stages and stale versions are rejected. Manual stage completion records the operator's assessment. ## addEvidence Appends evidence without editing earlier actions. ```ts theme={null} // POST /api/v1/rpc/release/addEvidence · MCP release_addEvidence addEvidence(input: { releaseId: string; expectedVersion: number; evidence: | { kind: "note"; text: string } | { kind: "link"; text: string; url: string }; // text: nonempty, at most 8,000 characters // url: HTTPS, at most 2,048 characters, no credentials }) ``` **Returns** the updated release result, with its version incremented. **Errors.** Invalid evidence and stale versions are rejected. Links require `url`; notes reject a `url` field. Evidence supports bounded notes and links, not arbitrary blobs or uploaded files. Links are not fetched or verified. Attached evidence containing credentials recognized by shipd's shared secret-redaction patterns is rejected before persistence, including recognized bearer tokens and credential-bearing query parameters. This is not an arbitrary-secret detector: do not put credentials, private telemetry payloads, or secrets in any release text or URL. Accepted evidence is preserved after input trimming; existing MCP response redaction still applies and may normalize JSON-looking text or redact recognized secret-like content. Add a new note to correct a previous claim; do not treat a link as proof that its contents were checked. ## ingestEvidence Appends a structured provider event using `POST /api/v1/rpc/release/ingestEvidence`. This automation endpoint uses the normal control-plane authentication and release write permissions. ```ts theme={null} ingestEvidence(input: GitHubEvidenceEvent | SnapshotDeliveryObservation) type GitHubEvidenceEvent = { releaseId: string; environmentId: string; // must match the release commitSha: string; // full lowercase SHA matching the release plan source: "github_actions" | "github_deployments"; eventId: string; // immutable provider event identity kind: "ci" | "deployment" | "verification"; subject: string; // component or check name occurredAt: string; // provider UTC timestamp outcome: "success" | "failure" | "cancelled" | "skipped" | "pending" | "in_progress" | "inactive" | "unknown"; url: string; // HTTPS provider reference without credentials } ``` **Returns** the updated release. No `expectedVersion` or `Idempotency-Key` is required. Event identity is scoped to project, release, source, and event ID, independent of the delivering credential. Identical events replay the original response without adding another action. Changed content under a used identity conflicts. Events, audit, and receipts commit atomically. Terminal releases accept ingestion. An ingested event alone cannot advance a stage. **Errors.** Invalid scope, mismatched commit, recognized secrets, and invalid URLs are rejected. Source is provenance reported by an authenticated collector, not independent verification by shipd. Provider links are never fetched. For `source: "sdk_delivery"`, call the same endpoint with an environment-bound service account. Send a service-wide observation for the release deployment. Use a distinct event ID for each observation and reuse it on retry. ```ts theme={null} type SnapshotDeliveryObservation = { source: "sdk_delivery"; releaseId: string; environmentId: string; commitSha: string; eventId: string; deploymentRef: string; service: string; observedAt: string; publishedVersion: number; appliedVersion: number | null; appliedSince: string | null; lastSuccessfulReadAt: string | null; lastFailedReadAt: string | null; }; ``` Use UTC timestamps with milliseconds. Report when the SDK began continuously serving the applied version. Use `null` when you cannot establish the applied version or the time it took effect. Successful polling, including a `304`, counts as a read during a stream reconnect. Report a snapshot read failure separately from a stream reconnect. Keep the observation limited to version and delivery metadata. ## startStage Records when you started exposure for the current manual rollout stage. Call this after you verify the audience is exposed. Each stage has its own start, and resuming a paused release requires recording a new start. ```ts theme={null} // POST /api/v1/rpc/release/startStage · MCP release_startStage startStage(input: { releaseId: string; expectedVersion: number; stageId: string; note: string }) ``` **Returns** the updated release and increments its version. Recording a start begins a new observation window. **Errors.** A stale version, a stage out of order, or an active rollout controller conflicts. The release must be `rolling_out`. ## assessHealth Records an advisory recommendation using the current stage's policy. Set the policy while planning the release, before it reaches `ready`. ```ts theme={null} // POST /api/v1/rpc/release/assessHealth · MCP release_assessHealth assessHealth(input: { releaseId: string; expectedVersion: number }) type ReleaseHealthPolicy = { version: string; observationSeconds: number; deploymentMaxAgeSeconds: number; snapshotMaxAgeSeconds: number; deployment: { source: "github_actions" | "github_deployments"; subject: string }; verification?: { source: "github_actions" | "github_deployments"; subject: string }[]; snapshotServices: string[]; application: { connection: string; maxAgeSeconds: number; // age of the latest sample for each metric, at least 61 seconds baselineCommitSha?: string; cohort?: { tag: string; // Sentry span tag carrying cohort attribution exposedValues: string[]; // exposed cohort tag values controlValues?: string[]; // optional in-window control cohort tag values (mutually exclusive with baselineCommitSha) }; guards: { metric: "error_rate" | "p95_latency"; threshold: number; minSamples: number; maxBaselineIncrease?: number; }[]; }; }; ``` Set `deploymentRef` to the deployment evidence URL, and use the provider subjects in `evidence.latest` to select deployment and verification events. The full observation window must follow the recorded stage start and deployment, and the required services must have applied the current environment snapshot throughout. Sentry queries use the configured project observability connection (managed through `/api/v1/rpc/observabilityConnection/*` with `SENTRY_ROLLOUT_CONNECTIONS_JSON` fallback), environment slug, and exact release SHA. When `cohort` is configured, queries also scope to the exposed cohort tag values (and optional in-window control cohort values on the same release); if spans exist for the release without the configured cohort tag, the assessment records `cohortAttribution.status = "unavailable"` (`reason: "tag_missing"`) and holds with `application_attribution_unavailable`. When `cohort` is omitted, observations are release-wide (`attribution: "release"`) with `cohortAttribution.status = "unavailable"` (`reason: "not_configured"`). The window ends at least one minute before the assessment; when Sentry reports a healthy `completeThrough` watermark earlier than that cutoff, the assessor retries once with a complete window that still satisfies stage coverage and freshness limits, and records the actual evaluated window. When complete, fresh evidence is unavailable or Sentry reports stalled or unknown ingestion, the assessment yields `hold`. When ingestion metadata is omitted, the one-minute delay and sample freshness checks apply. The sample count uses observed spans with extrapolation disabled. `error_rate` is a fraction and `p95_latency` is in milliseconds. A baseline compares either another commit (`baselineCommitSha`) or a control cohort (`cohort.controlValues`) in the same environment and window. The release-level `sourceUrl` gives the scope, and each metric's `queries` identifies the requests used to calculate it. **Returns** the release with its incremented version. Read `get` for the saved policy, scope, reasons, observation window, and evidence. The recommendation is `advance` when every check passes, `rollback` when complete evidence crosses a guard threshold, and `hold` when required evidence cannot establish a result. Operators decide whether to change exposure or complete a stage. **Errors.** A missing stage policy, inactive release, active rollout controller, stale release version, or changed environment snapshot during evaluation conflicts. ## listHealthValidations Lists accepted release health validations for a project. Filter optionally by environment, policy version, or revocation state. ```ts theme={null} // POST /api/v1/rpc/release/listHealthValidations · MCP release_listHealthValidations listHealthValidations(input: { projectId: string; environmentId?: string; policyVersion?: string; includeRevoked?: boolean; }) ``` **Returns** validation records with `id`, `environmentId`, `flagId`, `policyVersion`, `summary`, `scenarios`, `status` (`active`, `expired`, or `revoked`), and acceptance/revocation audit metadata. ## acceptHealthValidation Records an operator-accepted health validation so opt-in releases in the target project and environment can authorize hosted rollout execution against that `policyVersion`. Requires project admin/owner authority (`release.health_validation.manage`, plus production toggle permission for production environments) from a user session or an environment-bound admin management API key; MCP grants and service accounts cannot self-accept validations. ```ts theme={null} // POST /api/v1/rpc/release/acceptHealthValidation acceptHealthValidation(input: { projectId: string; environmentId: string; flagId?: string; policyVersion: string; summary: string; scenarios: ( | "healthy" | "regression" | "low_traffic" | "missing_telemetry" | "stale_telemetry" | "provider_outage" | "conflicting_evidence" )[]; evidenceReleaseId?: string; evidenceActionIds?: string[]; expiresAt?: string; }) ``` **Returns** the persisted validation record. Pass its `id` as `validationId` in `release/authorizeRollout`. ## revokeHealthValidation Revokes an accepted release health validation. New authorizations using that `validationId` are rejected immediately, and active rollouts referencing it hold with `validation_unavailable` on their next check. ```ts theme={null} // POST /api/v1/rpc/release/revokeHealthValidation revokeHealthValidation(input: { projectId: string; validationId: string; reason: string; }) ``` **Returns** the updated validation record in `revoked` status. ## authorizeRollout Opts a ready release in to the controller when an accepted health validation (`release/acceptHealthValidation`) matches the project, environment, optional flag scope, and `policyVersion`, and every authorized stage defines a `healthPolicy` with the same `version` and `observationSeconds >= observeForSeconds`. Use a service account token bound to the release's project and environment. Production requires production toggle permission. ```ts theme={null} // POST /api/v1/rpc/release/authorizeRollout authorizeRollout(input: { releaseId: string; expectedVersion: number; expectedFlagVersion: number; expectedFlagEnvironmentVersion: number; authorization: { flagId: string; maxPercentage: number; allowRollback: boolean; validationId: string; policyVersion: string; expiresAt: string; stages: { stageId: string; percentage: number; cohort: { kind: "all" } | { kind: "attribute"; attribute: string; values: string[] }; observeForSeconds: number; }[]; }; }) ``` **Returns** the release in `rolling_out`. Read `get` for the active authorization, decisions, and publication results. Attribute cohorts use exact text values. Numeric and boolean spellings such as `"001"` and `"true"` are rejected because SDK targeting can coerce them. The attribute name and values must have no surrounding whitespace. **Errors.** The stages must form an ordered prefix of the plan and fit within the authorized percentage cap. The associated boolean flag must already serve explicit `false` control with no rules, draft, or pending review. Stale versions, missing validation, and insufficient permissions prevent authorization. ## controlRollout Pauses or resumes controller checks, or stops automation and returns progression to manual actions. ```ts theme={null} // POST /api/v1/rpc/release/controlRollout controlRollout(input: { releaseId: string; expectedVersion: number; command: "pause" | "resume" | "stop"; note: string; }) ``` **Returns** the updated release. Each command leaves the current published flag state in effect. Resuming runs a new assessment before any publication. **Errors.** An inactive authorization or stale release version conflicts. Resuming requires an unexpired authorization. In production it also requires production toggle permission. ## get Reads the release, action history, next actions, and remaining stages. ```ts theme={null} // POST /api/v1/rpc/release/get · MCP release_get get(input: { releaseId: string }) ``` **Returns** a progress result with `release`, `actions`, `nextActions`, `remainingStages`, and `observed`. `evidence.latest` summarizes structured events for the current plan commit by source, kind, and subject. Provider occurrence time determines the latest result; receipt order does not. Contradictory events at the same timestamp yield `ambiguous`. Entries preserve their supporting events. All events remain in `actions[].payload.event`; action `createdAt` records receipt time. Missing evidence means unknown. These are last reported provider results for this release commit, not a live serving inventory across later releases. `health` returns the latest assessment for the current stage and policy, or `null` when none exists. Use `health.recommendation` for the current decision. An expired assessment or one invalidated by a changed snapshot, a restarted stage, or adverse new evidence returns `hold` with `staleReason`. The original decision remains in the action history. Release versions are independent of flag and deployment versions. Actions identify the authenticated actor, source, time, action type, and recorded payload; callers cannot supply an authoritative actor identity. The `rollout` field gives the authorization, status, active stage, and next check. Controller decisions record their evidence separately from execution results. A `published` result includes the flag and snapshot revisions read back from the control plane. Client delivery and application health are evaluated in the subsequent assessment. **Errors.** Missing or inaccessible records are not readable. This version returns the entire action history in one response; actions do not have pagination or a retention policy. Keep evidence concise. List pagination below applies to release records, not their actions. ## list Lists records within one authorized project and environment. ```ts theme={null} // POST /api/v1/rpc/release/list · MCP release_list list(input: { projectId: string; environmentId: string; limit?: number; // at most 100 cursor?: string; }) ``` **Returns** `{ releases, nextCursor }`. Pass a non-null `nextCursor` as `cursor` to continue; null means the page is complete. Treat the cursor as opaque. ## Limits Each controller authorization covers one boolean flag in the release's environment. The controller holds when evidence is missing or conflicting, the target changes, permission is lost, or an approval policy applies. For a protected change, stop automation before using the existing review and publication flow. A flag rollback restores control behavior. Migrations, purchases, and external side effects require their own recovery. Related: [MCP tools](/reference/mcp) · [Approval workflows](/reference/approvals) · [Install shipd agent skills](/operations/agent-skills). ## Code-defined progressive rollouts The signal-driven controller uses the flag's pushed [`rollout` configuration](/reference/config#signal-driven-rollout). It is gated by `code-release-control`. It stores a frozen checkpoint separately from legacy controller authorizations. ```ts theme={null} // POST /api/v1/rpc/release/proposeProgressiveRollout // MCP release_proposeProgressiveRollout { releaseId, flagId, expectedVersion } // POST /api/v1/rpc/release/rolloutStatus // MCP release_rolloutStatus or release_explainRolloutDecision { releaseId } // POST /api/v1/rpc/release/controlProgressiveRollout // Available through shipd rollout; unavailable through MCP { releaseId, expectedVersion, command: "pause" | "resume" | "abort", note } ``` **Returns** `{ releaseId, version, rollout }`. Status includes `nextCheckAt`. The rollout contains the frozen plan, zero-based step (`-1` before exposure), status, observation start, pending approval ID, and the most recent decision reason. When a guard query produces a metric snapshot, the decision also includes its window, values, samples and thresholds. Proposals, manual controls, and pre-exposure checks may have no metric snapshot. The release progress response includes the same public checkpoint as `progressive`. Every proposal, control, hold, advance, completion and rollback appends a release action and an audit event. **Fallback.** Missing signals hold the current exposure and retry. A guard failure restores the configured default automatically without approval. The controller ignores advancement permissions for that safety action. Normal policy review and publication are required for a protected advance; agents cannot approve it. An active rollout prevents manual stage completion or config pushes. Manual pause continues guard checks. **Errors.** Proposals require a ready release, published code-owned targeting serving the configured default with no rules, and one release stage per configured step. Another controller cannot own the same flag and environment. Plans, definitions or environment changes invalidate the checkpoint. Completion stops guard monitoring. # Reliability and data handling Source: https://docs.useshipd.com/reference/reliability-and-data Customer expectations for delivery, backups, incidents, rollback, access, and deletion. ## Overview SDKs evaluate flags locally and keep their last good snapshot when refresh or streaming fails. Flag changes publish automatically, with retries for failed publication. See [Local evaluation](/concepts/local-evaluation) for startup defaults and outage behavior. ## Backups and restore The standard database backup target is one encrypted off-site dump every 24 hours with 35-day retention, plus a daily automated restore verification. Shipd manages database recovery and republication of flag configuration. These are engineering targets, not a contractual SLA; ask support for the latest drill evidence and your contracted RPO/RTO. Extended retention and point-in-time recovery are not generally available. ## Incidents and rollback During an incident, check the service status/support channel, stop repeated writes, preserve request and approval ids, and keep SDKs on their last good snapshot. Flag rollback is a new audited change: revert the config, run `shipd diff`, then `shipd push`; an approval policy may queue it. Platform rollback and restore are operator actions. Never bypass an approval or force a conflict unless your incident procedure authorizes it. ## Operator access Customer organization access is role-controlled and audited. Infrastructure access is limited to authorized operators through provider controls; it is not a hidden product role. Support cannot ask for your management, SDK, service-account, SCIM, SSO, storage, or encryption secrets. ## Data deletion Archiving a flag or environment is not immediate physical deletion. Removing a SCIM user removes organization membership, not a global account used by other organizations. Audit rows intentionally survive organization deletion and expire under the effective retention policy. Backup copies age out under their lifecycle after primary deletion. Broad account/organization export and complete erasure currently require operator coordination. Contact support and identify the organization and subject without sending secrets. See [Access control](/enterprise/access-control), [Audit log](/reference/audit-log), and [Isolation tiers](/enterprise/isolation-tiers). # SCIM provisioning Source: https://docs.useshipd.com/reference/scim Tenant URL, bearer auth, externalId mapping, membership rules, and audit actions. ## Overview Use this page to look up inbound SCIM 2.0. SSO still authenticates. SCIM owns organization membership. Related: [Provision members with SCIM](/enterprise/scim). ## Endpoint | Item | Value | | - | - | | Tenant URL | `{tenant URL}` (copy from **Settings → Security → Directory (SCIM)**) | | Auth | Bearer token shown once on generate or rotate | | RBAC | `sso.read` / `sso.manage` | | Entitlement | Enterprise `scim`, plus at least one enabled, domain-verified SSO provider | | Limits | 300 requests/minute per IP and normalized request path; 1 MiB request body; `/Bulk` is not supported | Every error uses the SCIM Error schema with a string `status` and a `detail`. Bulk requests are not supported. ```bash curl theme={null} curl -sS '{tenant URL}/Users' \ -H 'Authorization: Bearer {token}' \ -H 'Accept: application/scim+json' ``` ```http HTTP theme={null} GET {tenant URL}/Users Authorization: Bearer {token} Accept: application/scim+json ``` ## User mapping | Field | What you send | | - | - | | Email | The person's work email. New access must belong to an enabled provider's verified domain. An existing organization member can still be linked after a domain change. Otherwise, shipd links an existing account only when its email is verified. Entra placeholder addresses are rejected. | | `externalId` | The IdP subject so later SSO can match: Entra `oid`, Okta user id | An active (or decommissioning) SCIM connection disables SSO JIT. SSO looks up `externalId` from the OIDC `sub` and, for Entra, the verified `oid` claim. Inactive, missing, or tombstoned identities are rejected (`SCIM_USER_NOT_ACTIVE`) unless the person has a manually managed membership. SCIM never rewrites the global profile of an account it linked. ## Membership | Directory event | What shipd does | | - | - | | Active user | Creates a SCIM-owned `viewer` membership, or preserves an existing manual membership. Cancels pending invites for that email. | | Inactive / removed user | Deletes only a SCIM-owned `viewer` membership, its organization team links, and the user's existing sessions. | | Manual role change | Transfers the membership to manual ownership, so a later directory deactivation does not delete it. | | Groups | Stores `POST /Groups` and membership changes. Explicit mappings synchronize membership in existing organization teams. Groups do not grant organization roles or create teams. | Repeated provisioning does not create duplicate organization memberships. ## Group to team mappings Admins and owners with `sso.manage` can map directory groups to existing teams under **Settings → Security → Directory (SCIM) → Group to team mappings**. Adding mappings requires the Enterprise SCIM entitlement. Groups and teams must belong to the same organization. * Each group can populate up to 100 teams by default. Your Enterprise agreement can set a different limit. Multiple groups can populate the same team. * Saving a mapping immediately adds active group members who belong to the organization. Later directory membership changes synchronize automatically. * Removing a group member, deleting a group, removing a mapping, or deactivating a directory user removes team access created by that mapping, unless another active mapped group still grants it. * Existing manual team memberships are preserved when a mapping is removed. Organization deprovisioning follows the separate organization membership rules above. * Unmapped groups do not change team access. Group renames keep their mappings. ## Audit | Action | Actor | | - | - | | `identity.member.*`, `identity.teamMember.*`, `identity.scim_membership_ownership.*` | Directory membership reconciliation | | `identity.scim_group_team_mapping.*` | Dashboard group mapping changes, attributed to the acting admin | | `identity.scim_user.*`, `identity.scim_group.*`, `identity.scim_group_member.*` | SCIM resources and group membership | | `identity.scim_managed_connection.*`, `identity.scim_managed_credential.*` | Connection and credential lifecycle | | `scim.connection.created` / `rotated` / `revoked` / `decommissioned` | Dashboard admin lifecycle actions | Directory and connection changes appear in your organization's audit log. Events can appear shortly after the change; you do not need to repeat a successful provisioning request while waiting for audit history. ## Lifecycle Generate, rotate, and revoke the token on **Settings → Security → Directory (SCIM)**. Tokens are scoped to one connection and organization and are shown only once. Store them securely; rotate a lost token. Revoke and decommission remain available after entitlement loss or SSO-provider disablement. Decommissioning is asynchronous: `202 Accepted` includes `Location` and `Retry-After` while cleanup continues. Poll after that delay; completion returns `200`. Repeated creates and updates do not duplicate resources or memberships. Updates use the resource state that arrives last; SCIM 2.0 does not supply a portable provider sequence number, so an IdP must retry its current authoritative state after delivering requests out of order. # SDK reference Source: https://docs.useshipd.com/reference/sdk Every shipdit export: createClient options, evaluation methods, identity, lifecycle, React hooks, and types. ## Overview This is the canonical reference for the TypeScript SDK, `shipdit`. Guides link here for signatures, options, and fallback behavior. ```bash theme={null} npm install shipdit ``` | Import | Use in | Exports | | - | - | - | | `shipdit` | Node.js, workers, and other server runtimes | `createClient`, types, version constants | | `shipdit/client` | Browsers | `createClient` (edge-evaluated values and a stable anonymous id), types | | `shipdit/client/react` | React client components | `createShipdReact`, types | | `shipdit/config` | `shipd.config.ts` only | `defineFlags` — see [`shipd.config.ts` reference](/reference/config) | Requires Node.js 20 or later. Realtime updates (`stream: true`) need a WebSocket implementation. Node.js 22+ and browsers provide a global `WebSocket`; on Node.js 20, pass a compatible constructor through the `WebSocket` option. **Guarantees.** Getters never throw. Server evaluations use a local snapshot. Browser getters read resolved values in memory and schedule an edge request for new keys or contexts, returning [`defaults`](#defaults) until values arrive. ## Types ```ts theme={null} /** Who is asking. Passed per call, or set with identify() in browsers. */ interface EvaluationContext { userId?: string; attributes?: Record; /** Audience ids the caller already knows it belongs to. */ segmentIds?: string[]; } interface IdentifyInput { userId: string; anonymousId?: string; name?: string; traits?: Record; } /** Generated by the CLI into src/generated/flags.ts */ interface FlagDefinitions { "new-checkout": { type: "boolean"; default: false }; "search-variant": { type: "variant"; variants: "control" | "semantic" | "hybrid"; default: "control"; }; } type BooleanFlagKey = /* keys of F whose type is "boolean" */; type VariantFlagKey = /* keys of F whose type is "variant" */; type NumberFlagKey = /* keys of F whose type is "number" */; type JsonFlagKey = /* keys of F whose type is "json" */; type VariantValue = /* F[K]["variants"] union */; type JsonValue = /* type of F[K]["default"] */; type PartialDefaults = { [K in keyof F]?: F[K]["default"] }; interface SnapshotCache { load(): Promise<{ snapshot: FlagSnapshot; etag: string | null } | null>; save(snapshot: FlagSnapshot, etag: string | null): Promise; clear?(): Promise; } ``` `FlagSnapshot` is documented in [Snapshots](/concepts/snapshots). `FlagDefinitions` is generated into `src/generated/flags.ts`; import it from there. The `FlagDefinitions` type exported by `shipdit/config` is a different type (the loose authoring map `defineFlags` accepts), so don't use it to type a client. | Type | `shipdit` | `shipdit/client` | `shipdit/client/react` | | - | - | - | - | | `EvaluationContext` | Yes | Yes | Yes | | `BooleanFlagKey`, `VariantFlagKey`, `NumberFlagKey`, `JsonFlagKey` | Yes | Yes | Yes | | `VariantValue`, `JsonValue` | Yes | Yes | Yes | | `ShipdClient` | Yes | Yes | Yes | | `ServerShipdClient`, `EvaluationDetails`, `EvaluationValues` | Yes | No | No | | `IdentifyInput`, `PartialDefaults`, `SnapshotCache` | Yes | Yes | No | | `FlagSnapshot` | Yes | Yes | No | | `ClientOptions` | Yes (server options) | Yes (browser options, with `persist`, `storageKey`, `anonymousStorageKey`) | No | | `ShipdReact` | No | No | Yes | ## createClient Creates a server client that evaluates an environment snapshot locally, or a browser client that receives only evaluated values from the edge. ```ts theme={null} import { createClient } from "shipdit"; // server import { createClient } from "shipdit/client"; // browser // Server returns ServerShipdClient, which extends ShipdClient. createClient(options: ClientOptions): ServerShipdClient ``` The server client loads its configured cache first, then fetches the snapshot and refreshes it every `refreshIntervalMs` using `If-None-Match`. Browser clients refresh requested values with `POST /sdk/v1/evaluate` on the same interval. With `stream: true`, it also refreshes as soon as shipd announces a change. Create one client per process (server) or per page (browser) and reuse it. ### Options **sdkKey** `string` *required* An SDK key for one environment: `shipd_sdk_server_…` on servers, `shipd_sdk_client_…` in browsers. See [Keys and tokens](/concepts/keys). **defaults** `PartialDefaults\` Values returned before the first snapshot arrives and for flags missing from the snapshot. Pass one for every flag. See [Defaults](#defaults). **stream** `boolean` (default: false) Open a WebSocket to `https://ws.useshipd.com` for near-instant updates. Polling continues as a fallback. Needs a global `WebSocket` (Node.js 22+, browsers) or the `WebSocket` option. **overrides** `ClientOverrides` Connection overrides. Production apps should not set these. **properties** **streamEndpoint** `string` (default: [https://ws.useshipd.com](https://ws.useshipd.com)) WebSocket gateway origin used when `stream` is `true`. Accepts `https`, `http`, `wss`, or `ws`; validated like `unsafeEndpoint`. **unsafeEndpoint** `string` (default: [https://edge.useshipd.com](https://edge.useshipd.com)) **Unsafe.** For shipd development and test environments only. Replaces the edge origin that receives your SDK key. Must be an absolute `http` or `https` URL without credentials, a query, or a fragment; `createClient` throws otherwise. A plaintext `http` URL to a non-local host logs a warning. **context** `EvaluationContext` Base context merged under every evaluation. **refreshIntervalMs** `number` (default: 30000) Poll interval. Polling continues while the WebSocket is connected. `0` fetches once and never polls. **readyTimeoutMs** `number` (default: 5000) Maximum time `ready()` waits for the first snapshot. **fetchTimeoutMs** `number` (default: 10000) Per-request HTTP timeout for snapshot fetches and event flushes. `0` disables the timeout. **bootstrap** `FlagSnapshot` Server only. A snapshot to evaluate against until the first successful fetch. Never embed a server snapshot in browser HTML. **cache** `SnapshotCache` Server only. Durable store for the last good snapshot. Browser clients reject snapshot cache adapters. **onError** `(error: unknown) =\> void` Receives background fetch, stream, cache, and event-delivery errors. The client keeps working after every error. Messages are listed in [Errors](/reference/errors). **events** `boolean` (default: true) Send evaluation, identify, and diagnostic events to `POST /sdk/v1/events`. **eventsFlushAt** `number` (default: 50) Flush when this many events are buffered. **eventsFlushIntervalMs** `number` (default: 5000) Flush interval. `0` disables timed flushes. **tracking** `TrackingOptions` Server only. Enable [custom event publishing](#track) by passing `environmentId` and a `publishToken` with the `customer_event:publish` permission. The optional `apiUrl` defaults to `https://api.useshipd.com`. **remoteTraits** `boolean` (default: true) Ignored on browser clients (`shipdit/client`), because `GET /sdk/v1/identity` is restricted to server SDK keys. Pass traits in `identify()` or per-call context. **automaticTraits** `boolean` Add `country`, `region`, `city`, and `timezone` under your own attributes. Default `true` in `shipdit/client`, off in `shipdit`. **anonymousId** `string` Stable id for a signed-out visitor. Browser clients generate and persist one if omitted. **onAnonymousId** `(anonymousId: string) =\> void` Called when the client assigns or changes the anonymous id. **WebSocket** `WebSocket constructor` WebSocket implementation for runtimes without a global one (for example, `ws` on Node.js 20). **fetch** `typeof fetch` `fetch` implementation. Useful in tests. Browser-only options (`shipdit/client`): **persist** `boolean` Deprecated. Browser values are kept in memory and never persisted. **storageKey** `string` Legacy snapshot storage key to remove during upgrade. Defaults to a key derived from `sdkKey` and the edge origin. **anonymousStorageKey** `string` (default: shipdit:anonymousId) `localStorage` key for the anonymous id. **Returns** a [`ShipdClient`](#client-methods). The server entry returns `ServerShipdClient`, which also exposes [`evaluate`](#evaluate) and [`track`](#track). **Errors.** Throws synchronously `shipdit: sdkKey is required` when `sdkKey` is empty. Removed `endpoint` or `streamEndpoint` options and invalid `overrides.unsafeEndpoint` values also throw synchronously. `overrides.streamEndpoint` is validated only when `stream` is enabled; network problems go to `onError`. ```ts src/lib/shipd.ts theme={null} import { createClient } from "shipdit"; import type { FlagDefinitions } from "../generated/flags"; export const shipd = createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, stream: true, defaults: { "new-checkout": false, "search-variant": "control", "max-retries": 3, "checkout-payload": { mode: "strict", showPromo: true }, }, onError: (error) => console.warn("[shipd]", error), }); ``` **Related:** [Node.js](/sdks/node) · [Browser](/sdks/browser) · [Keys and tokens](/concepts/keys) ### Defaults `defaults` decides what your users get when shipd can't answer. | Situation | Value returned | | - | - | | Before the first snapshot (and no `bootstrap` or cached snapshot) | `defaults[key]` | | Flag key not in the snapshot (typo, archived, other project) | `defaults[key]`, and an `unregistered_flag` event | | Edge unreachable after a successful fetch | Evaluated against the last good snapshot | | `defaults[key]` not provided | `false` · `"control"` · `0` · `{}` for boolean · variant · number · JSON | The built-in fallbacks exist only so the return type holds. `"control"` may not be one of your variants. Always pass a default for every flag. ## Client methods ### ready Resolves when initial loading finishes, the first fetch fails, or `readyTimeoutMs` elapses. Server clients can also resolve from `bootstrap` or a cached snapshot. Browser clients request keys listed in `defaults`; later keys and new contexts load asynchronously. After browser identity changes, subscribe for fresh values. ```ts theme={null} ready(): Promise ``` **Returns** `Promise`. It never rejects for network errors. Returning on timeout means evaluations use `defaults` until a snapshot arrives. ```ts theme={null} await shipd.ready(); server.listen(3000); ``` **Related:** [Options](#options) · [`useReady`](#useready) ### evaluate Resolves a dynamic flag key with details. Available only on server clients returned by `shipdit`. ```ts theme={null} evaluate( key: string, type: T, defaultValue: EvaluationValues[T], context?: EvaluationContext, ): EvaluationDetails ``` **key** `string` *required* Any flag key, including keys without generated types. **type** `boolean | variant | number | json` *required* The expected declared flag type. Values are never coerced between types. **defaultValue** `EvaluationValues[T]` *required* Default for this call when resolution fails. Overrides SDK-wide `defaults`. **context** `EvaluationContext` Per-call context, merged over the client's default context. **Returns** the value, `snapshotVersion`, optional `flagType` and `ruleId`, and a `reason` of `rule_match`, `fallthrough`, `flag_disabled`, or `error`. Successful results omit error fields. JSON flags may contain JSON primitives or structures. **Fallback.** Errors return the supplied `defaultValue`. Disabled flags return the flag's configured default with reason `flag_disabled`. ```ts Example theme={null} const details = shipd.evaluate("search-variant", "variant", "control", { userId: "usr_8f2k19", attributes: { plan: "pro" }, }); ``` **Errors.** Resolution failures are returned as `errorCode` and `errorMessage`: `PROVIDER_NOT_READY` without a snapshot, `FLAG_NOT_FOUND` for an unknown key, `TYPE_MISMATCH` for a wrong declared or served type, and `GENERAL` for evaluator failures. Each call records one evaluation diagnostic when events are enabled. **Related:** [OpenFeature provider](/integrations/openfeature) · [Evaluation context](/core-concepts) ### isEnabled Returns the value of a boolean flag. ```ts theme={null} isEnabled(key: BooleanFlagKey, context?: EvaluationContext): boolean ``` **key** `BooleanFlagKey` *required* A flag whose `type` is `boolean`. Other keys are a type error. **context** `EvaluationContext` Merged over the identified user and the client `context` for this call only. **Returns** `boolean`. **Fallback.** See [Defaults](#defaults). ```ts theme={null} if (shipd.isEnabled("new-checkout", { userId: "usr_8f2k19", attributes: { plan: "pro" } })) { return renderNewCheckout(); } ``` **Errors.** Never throws. **Related:** [`useFlag`](#useflag) · [Create a boolean flag](/flags/boolean) ### getVariant Returns the value of a variant flag, typed as the union of its variants. ```ts theme={null} getVariant>(key: K, context?: EvaluationContext): VariantValue ``` **key** `VariantFlagKey` *required* A flag whose `type` is `variant`. **context** `EvaluationContext` Per-call context. **Returns** one of the flag's variants, for example `"control" | "semantic" | "hybrid"`. **Fallback.** See [Defaults](#defaults). ```ts theme={null} const engine = shipd.getVariant("search-variant", { userId: "usr_8f2k19" }); ``` **Errors.** Never throws. **Related:** [`useVariant`](#usevariant) · [Run an A/B test](/flags/experiments) ### getNumber Returns the value of a number flag. ```ts theme={null} getNumber(key: NumberFlagKey, context?: EvaluationContext): number ``` **Returns** a finite `number`. A non-finite served value falls back to `defaults[key]`. ```ts theme={null} const retries = shipd.getNumber("max-retries"); ``` **Errors.** Never throws. **Related:** [`useNumber`](#usenumber) · [Number and JSON flags](/flags/number-and-json) ### getJson Returns the value of a JSON flag, typed as its declared default. ```ts theme={null} getJson>(key: K, context?: EvaluationContext): JsonValue ``` **Returns** the served JSON value. The type comes from the `default` in `shipd.config.ts`; the SDK does not validate the served value's shape. ```ts theme={null} const ui = shipd.getJson("checkout-payload"); // { mode: "strict"; showPromo: true } ``` **Errors.** Never throws. **Related:** [`useJson`](#usejson) ### identify Sends an `identify` event. In browsers (`shipdit/client`), it also sets the user for every later evaluation on the client. On servers (`shipdit`), it only sends the event and never changes evaluation context. ```ts theme={null} identify(input: IdentifyInput): void ``` **userId** `string` *required* Your stable user id. Used for targeting and percentage bucketing. **traits** `Record\` Attributes available to targeting rules, such as `plan` or `email`. **name** `string` Display name shown in the dashboard. Also available to rules as the `name` attribute. **anonymousId** `string` Links this user to a signed-out session. **Errors.** Throws `shipdit: identify requires userId` when `userId` is empty. ```ts theme={null} // Browser shipd.identify({ userId: "usr_8f2k19", name: "Jordan Chen", traits: { plan: "pro" } }); shipd.isEnabled("new-checkout"); // evaluated for usr_8f2k19 ``` A server client handles many users, so pass `context` on each call. Server `identify()` records the user's traits for audience insights without affecting other requests. **Related:** [Identify users](/flags/identify-users) ### reset Clears the identified user and starts a new anonymous id in browser clients. Call it on logout. Server clients (`shipdit`) treat `reset()` as a no-op: it does not change the anonymous id or notify subscribers. ```ts theme={null} reset(): void ``` ### track Queue a named application event from the server with shipdit 0.9.0 or later. Enable the customer webhooks beta for your organization and configure `tracking` when you create the client. ```ts theme={null} track(name: string, context?: EvaluationContext, details?: TrackingEventDetails): void ``` Pass `context.userId` for identity and scalar `context.attributes` for targeting attributes. The call context overrides the SDK's base context. Event details accept JSON values and an optional finite numeric `value`. The [OpenFeature integration](/integrations/openfeature#track-custom-events) describes the accepted payload, queue limits, and retries. Subscribe an endpoint to receive the event, and await [`close()`](#close) at shutdown to drain the queue. ### getAnonymousId Returns the anonymous id used to connect signed-out and signed-in sessions, or `null`. ```ts theme={null} getAnonymousId(): string | null ``` ### subscribe Calls `listener` when a new snapshot applies or the identified user changes. ```ts theme={null} subscribe(listener: () => void): () => void ``` **Returns** an unsubscribe function. ```ts theme={null} const unsubscribe = shipd.subscribe(() => render()); ``` ### getVersion Returns the loaded snapshot's version, or `null` before the first snapshot. ```ts theme={null} getVersion(): number | null ``` ### getRevision Returns a counter that increases whenever a snapshot applies or the identity changes. Use it with `useSyncExternalStore`. ```ts theme={null} getRevision(): number ``` ### close Stops polling and the WebSocket, and flushes pending events. Call it on shutdown. Evaluation keeps serving the last snapshot afterward. ```ts theme={null} close(options?: { timeoutMs?: number }): Promise ``` **timeoutMs** `number` (default: 5000) How long to wait for pending events. When it passes, pending sends are aborted and the promise resolves. The promise resolves once the event buffers drain or `timeoutMs` passes. It never rejects. A failed diagnostic send ends the diagnostic drain. If custom event tracking is enabled, its queue drains in parallel and applies its own retry policy. ```ts theme={null} process.on("SIGTERM", async () => { await shipd.close(); }); ``` ## Evaluation context merge The context used for a check is built from three layers. Later layers win. 1. `createClient({ context })` 2. `identify({ userId, traits })` (browser clients only): `traits` become `attributes` 3. The `context` argument on the call `userId` and `segmentIds` are replaced. `attributes` merge key by key. In browsers, automatic `timezone` and location traits sit underneath all three. ## React ### createShipdReact Binds typed hooks and a provider to your `FlagDefinitions`. Call it once, in a client-only module. ```ts theme={null} import { createShipdReact } from "shipdit/client/react"; createShipdReact(): { ShipdProvider, useShipdClient, useReady, useFlag, useVariant, useNumber, useJson } ``` ```ts src/lib/shipd-react.ts theme={null} "use client"; import { createShipdReact } from "shipdit/client/react"; import type { FlagDefinitions } from "../generated/flags"; export const { ShipdProvider, useFlag, useVariant, useNumber, useJson, useReady, useShipdClient } = createShipdReact(); ``` Use hooks from the same `createShipdReact` call as the provider. Requires React 18 or later. **Related:** [React](/sdks/react) · [Next.js](/sdks/nextjs) ### ShipdProvider Makes a client available to hooks below it. ```tsx theme={null} {children} ``` **client** `ShipdClient` *required* A client from `shipdit/client`. ### useFlag `isEnabled` as a hook. Re-renders when a snapshot applies or the identity changes. ```ts theme={null} useFlag(key: BooleanFlagKey, context?: EvaluationContext): boolean ``` ### useVariant ```ts theme={null} useVariant(key: K, context?: EvaluationContext): VariantValue ``` ### useNumber ```ts theme={null} useNumber(key: NumberFlagKey, context?: EvaluationContext): number ``` ### useJson ```ts theme={null} useJson(key: K, context?: EvaluationContext): JsonValue ``` ### useReady Returns `true` once `client.ready()` has resolved. ```ts theme={null} useReady(): boolean ``` ### useShipdClient Returns the provided client. ```ts theme={null} useShipdClient(): ShipdClient ``` **Errors.** Throws when used outside `ShipdProvider`. ## Version constants ```ts theme={null} import { VERSIONS } from "shipdit"; // { snapshotSchema, streamProtocol, sdkPackage, controlPlaneApi } ``` | Constant | Current | Meaning | | - | - | - | | `SNAPSHOT_SCHEMA_VERSION` | `1` | Snapshot format this SDK reads. Newer formats are rejected and the last good snapshot is kept. | | `SDK_STREAM_PROTOCOL_VERSION` | `1` | WebSocket protocol version. | | `SDK_PACKAGE_VERSION` | package version | The installed `shipdit` version. | | `CONTROL_PLANE_API_VERSION` | `1` | Control-plane API major version (`/api/v1`). | ## Related * [Local evaluation](/concepts/local-evaluation): the refresh path and failure behavior * [Edge API](/reference/edge-api): the HTTP and WebSocket routes the SDK calls * [Errors](/reference/errors): `onError` messages # Service account tokens Source: https://docs.useshipd.com/reference/service-account-tokens shipd_sa_ token format, scopes, binding, expiry, and audit attribution. ## Overview Control-plane credentials for automation. Distinct from management keys (`shipd_mgmt_`) and SDK keys (`shipd_sdk_`). Related: [Create a service account](/enterprise/service-accounts). ## Format ``` shipd_sa_{base64url} ``` The dashboard and user-session create API return the secret once. Store it securely. With Terraform registration, supply a secret you generated and stored before applying. [Manage credentials from CI](/reference/terraform#manage-credentials-from-ci). Send it as `Authorization: Bearer shipd_sa_…` or `x-api-key`. ## Scopes Scopes are `{ resource: [verbs] }` matching the RBAC statement (e.g. `{ "flag": ["read", "create"] }`). Empty scopes are rejected. A token cannot receive verbs the minting admin or CI issuer does not have. `me` always works so the CLI can resolve org (and project/environment when bound). ## Binding | Binding | Effect | | - | - | | None | Org-wide. Pass `--project` / `--env` (or `SHIPD_PROJECT` / `SHIPD_ENV`) for commands that need them. | | Project | Requests that name another project are `403`. | | Project + environment | Requests that name another environment are `403`. | Environment-bound tokens only receive rows for their environment. They cannot create environments, perform project-wide flag definition changes, manage organization-wide approval policies, or request a project-wide snapshot rebuild. Resource IDs are resolved inside the token's organization and are checked again against both the project and environment binding. ## Lifecycle | State | Auth result | | - | - | | Revoked | `401` | | Expired | `401` | | Account disabled | `401` | Revocation preserves the token's audit history. Repeated revoke requests succeed, so callers may safely retry them. `rotateToken` atomically creates a replacement with the same scopes and bindings and revokes the old token. The replacement plaintext is shown once. To allow overlap, create a second token and revoke the old one after verifying the consumer. ## Rotation Create a second token with the same minimal scopes and bindings, update the consumer's secret store, verify one successful authenticated operation, then revoke the old token. If the secret is lost, revoke the token and issue a fresh one. Disable the service account when every token must stop immediately. ## Audit Mutations made with a token record `actorType: service_account` and `actorId` = the service account id. `tokenId` identifies which token. Lifecycle events: `serviceAccount.created`, `serviceAccount.updated`, `serviceAccount.disabled`, `serviceAccount.enabled`, `serviceAccount.deleted`, `serviceAccount.token.created`, `serviceAccount.token.revoked`, `serviceAccount.token.rotated`. Successful mutating requests are audited with the token id. Successful authentication also records `serviceAccount.token.used` when `lastUsedAt` advances, at most once per minute. This makes the field a useful activity signal without turning the audit log into a request counter. Service-account tokens are control-plane-only. SDK routes accept only `shipd_sdk_` credentials. # Terraform provider reference Source: https://docs.useshipd.com/reference/terraform Configuration, resources, data sources, imports, and lifecycle behavior for the shipd Terraform provider. ## Overview The `alasti-company/shipd` provider manages shipd resources through the control-plane API. For installation and a complete configuration, see [Manage projects and environments with Terraform](/integrations/terraform). Install the published [alasti-company/shipd provider](https://registry.terraform.io/providers/alasti-company/shipd/latest/docs) with `terraform init`. The v0.1 release manages projects and environments. Webhook resources require a provider release that includes them and API support for `snapshotWebhook/createConfig` and `eventWebhook/createConfig`. Credential resources require a provider release that includes them and a shipd API with credential registration support. ## Provider configuration ```hcl provider.tf theme={null} provider "shipd" { organization_id = "YOUR_ORGANIZATION_ID" } ``` | Argument | Type | Default | Behavior | | - | - | - | - | | `api_key` | Sensitive string | `SHIPD_API_KEY` | Service account token (`shipd_sa_…`) or management API key (`shipd_mgmt_…`). Must be known during planning. | | `api_url` | String | `SHIPD_API_URL` or `https://api.useshipd.com` | HTTPS is required except for localhost or loopback IP addresses. | | `organization_id` | String | `SHIPD_ORGANIZATION_ID` | Optional check that credentials belong to the expected organization. Does not switch organizations. | Prefer `SHIPD_API_KEY` over putting credentials in configuration. SDK keys cannot authenticate the provider. Creating projects requires an organization-wide service account token. Management API keys work within their bindings but cannot create projects. Project-bound service account tokens can manage environments in that project; environment-bound credentials cannot create environments. Read-only consumers need the corresponding `project:read` and `environment:read` scopes. See [token scopes and binding](/reference/service-account-tokens). ## Resources ### shipd_project Creates a project in the credential's organization. | Attribute | Type | Requirement | Behavior | | - | - | - | - | | `name` | String | Required | Display name; updates in place. | | `slug` | String | Required | Project slug, at least three characters; updates in place. | | `id` | String | Computed | Stable project ID. | | `organization_id` | String | Computed | Owning organization ID. | | `version` | Number | Computed | API version used for optimistic concurrency checks. | ### shipd_environment Creates an environment within a project. | Attribute | Type | Requirement | Behavior | | - | - | - | - | | `project_id` | String | Required | Owning project ID. Changing it replaces the environment. | | `name` | String | Required | Display name; updates in place. | | `slug` | String | Required | Unique within the project; updates in place. | | `type` | String | Optional | Free-form classification; defaults to `development`. Does not control permissions. | | `is_production` | Boolean | Optional | Defaults to `false`. Only one environment per project may be production. | | `id` | String | Computed | Stable environment ID. | | `version` | Number | Computed | API version used for optimistic concurrency checks. | ### shipd_snapshot_webhook Sends `snapshot.published` notifications to a Convex HTTP action. Each environment supports one destination. | Attribute | Type | Requirement | Behavior | | - | - | - | - | | `environment_id` | String | Required | Owning environment ID. Changing it replaces the webhook. | | `url` | Sensitive string | Required | HTTPS callback on a `.convex.site` hostname without user information or a fragment. Updates in place. | | `enabled` | Boolean | Optional | Defaults to `true`. Updates in place. | | `id` | String | Computed | Stable destination ID. | Use a service account token with `environment:read` and `snapshot_webhook:read`, plus `snapshot_webhook:manage` for writes. See [Connect Convex](/sdks/convex) for receiver setup. ### shipd_event_webhook Sends customer events to an HTTPS endpoint. The event type set filters which events are delivered. | Attribute | Type | Requirement | Behavior | | - | - | - | - | | `environment_id` | String | Required | Owning environment ID. Changing it replaces the webhook. | | `name` | String | Required | Display name. Changing it replaces the webhook. | | `url` | Sensitive string | Required | HTTPS endpoint without user information or a fragment. Changing it replaces the webhook. | | `event_types` | Set of strings | Required | One to 100 event types. Use `"*"` to match all types. Updates in place. | | `enabled` | Boolean | Optional | Defaults to `true`. Updates in place. | | `id` | String | Computed | Stable endpoint ID. | Use a service account token with `event_webhook:read`, plus `event_webhook:manage` for writes. The organization must have customer event webhooks enabled to create endpoints. See [Receive customer events](/operations/receive-customer-events) for receiver setup. ### Webhook credentials and delivery Terraform manages webhook configuration. Set up signing secrets, test deliveries, view delivery history, and redeliver events in shipd. * **Signing secrets.** shipd generates a secret on creation. Terraform receives and stores only configuration. For a new webhook, set `enabled = false`, use **Rotate secret** for a Convex destination or **Rotate signing secret** for an event endpoint, and save the returned secret in the receiver's secret manager. Then set `enabled = true` and apply. Existing webhooks keep their signing secret when imported or updated. Replacing a webhook creates a new secret. * **Destination URLs.** Terraform marks URLs sensitive and stores each complete URL in plans and state. Use URLs without credentials, including credentials in paths or query strings. Protect plan and state files if you import an existing URL that contains a credential. * **Drift and deletion.** Refresh reads the current configuration, including enabled state and event subscriptions. Terraform plans to recreate webhooks deleted outside Terraform. Destroy deletes the webhook. Deleting an event endpoint also cancels its pending deliveries. * **Interrupted creation.** The provider reuses the request's idempotency key during retries. If an apply stops before it records the webhook in state, check the environment in shipd and import any webhook the apply created. ## Data sources Read existing objects without taking ownership of their lifecycle: ```hcl data.tf theme={null} data "shipd_project" "app" { slug = "web-app" } data "shipd_environment" "production" { project_id = data.shipd_project.app.id slug = "production" } ``` Both data sources accept exactly one of `id` or `slug`. The environment data source also requires `project_id`. | Data source | Returned attributes | | - | - | | `shipd_project` | `id`, `slug`, `name`, `organization_id`, `version` | | `shipd_environment` | `id`, `slug`, `name`, `project_id`, `type`, `is_production`, `version` | ## Import existing resources Declare the matching resource blocks first, then import: ```bash theme={null} terraform import shipd_project.app PROJECT_ID terraform import shipd_environment.production PROJECT_ID/ENVIRONMENT_ID terraform import shipd_snapshot_webhook.convex ENVIRONMENT_ID/DESTINATION_ID terraform import shipd_event_webhook.invoices ENVIRONMENT_ID/ENDPOINT_ID terraform plan ``` Set `type` and `is_production` explicitly when importing an environment whose values differ from the defaults (`development` and `false`). Set `enabled = false` in configuration when importing a disabled webhook. Review the plan before applying changes. ## Lifecycle and drift * **Ownership.** Terraform manages only resources declared in configuration. Data sources leave ownership with shipd. * **Destroy.** Destroy archives projects and environments. Recovery and slug reservation last seven days. Creating again does not automatically restore or adopt it: restore through the dashboard and import, choose another slug, or wait for the reservation to expire. Archiving a project also makes its child resources inaccessible. * **Protection.** Use `lifecycle { prevent_destroy = true }` for important resources. Approval policies may block archive or production changes; the provider returns the API error and retains state. It does not approve requests. * **Production changes.** To move production to another environment, first set `is_production = false` on the current one and apply. Then set `is_production = true` on the replacement and apply again. Implicit demotion is rejected, including during concurrent writes. Setting `type = "production"` alone does not designate production. * **Drift.** External changes appear in the next plan. Project and environment updates use the refreshed API version. A concurrent project or environment change returns a conflict; run a fresh plan before retrying. * **Reads.** Objects that no longer exist are removed from Terraform state. Authorization and transport failures return errors instead of treating objects as missing. * **Interrupted creation.** Retries reuse an idempotency key within one operation. If creation commits but the process stops or response retries are exhausted, inspect shipd and import the existing ID before retrying. Environment updates require API support for `environment/updateWithoutHandoff`. Older servers reject the operation instead of falling back to an update that could demote another environment. ## Manage credentials from CI Use Terraform 1.11 or later for `shipd_sdk_key` and `shipd_service_account_token`. Use a dashboard-created [service account token](/enterprise/service-accounts) as `SHIPD_API_KEY` and keep that bootstrap account and token outside the configuration they authenticate. If Terraform also manages the workload account, grant the separate service account administration scopes required by `shipd_service_account`. | Credential | CI permissions | Binding and expiry | | - | - | - | | Client and server SDK keys | `sdk_key:create` to register, `sdk_key:read` to refresh, `sdk_key:revoke` to destroy | Each key belongs to one project and environment. Scope the CI token to those IDs when possible. Set `expires_at` for automatic expiry, or omit it for a non-expiring key. | | Workload service account tokens | `service_account_token:create` to register, `service_account_token:read` to refresh, `service_account_token:revoke` to destroy | Use an organization-wide bootstrap token with no project or environment binding. For registration and revocation, the bootstrap token must hold every scope on the workload token. Workload tokens cannot receive `service_account_token` or `apiKey` scopes through Terraform. Bind each workload token as narrowly as its job allows and set a future `expires_at`. | | Management API keys | Supported as provider authentication within their existing bindings | Create, rotate, and revoke these user-bound keys through the existing user-session workflows. Use a service account token for CI-managed credentials. | Set `scopes` explicitly. SDK keys accept `snapshot:read`, `events:write`, and `stream:connect`. Server SDK keys can also receive `identity:read`. Service account token scopes use the [resource-to-verbs map](/reference/service-account-tokens#scopes). For example, a token that reads projects needs only `project = ["read"]`. Use RFC3339 timestamps for expiry. ### Generate and deliver a secret Generate a lowercase UUIDv4 for the credential's `id`. Use the prefix `shipd_sdk_client_`, `shipd_sdk_server_`, or `shipd_sa_`, followed by 32 random bytes encoded as unpadded base64url, a dot, and the first 32 lowercase hex characters of the organization ID's SHA-256 digest. ```python generate_credential.py theme={null} import hashlib import secrets def generate_credential(prefix: str, organization_id: str) -> str: tag = hashlib.sha256(organization_id.encode("utf-8")).hexdigest()[:32] return f"{prefix}{secrets.token_urlsafe(32)}.{tag}" ``` Save the generated secret in a versioned secret store before applying. Set `secret_version` to the nonsecret version identifier and use that same version for every attempt. Pass the secret value to Terraform through a sensitive, ephemeral variable and the `secret_wo` argument. After registration succeeds, configure the consumer to read the same secret-store version. On a self-hosted installation, deploy the matching edge and WebSocket gateway builds before using registered SDK keys. ```hcl sdk-key.tf theme={null} variable "runtime_sdk_key_id" { type = string } variable "runtime_sdk_key_version" { type = string } variable "runtime_sdk_key" { type = string sensitive = true ephemeral = true default = null } resource "shipd_sdk_key" "runtime" { id = var.runtime_sdk_key_id organization_id = var.organization_id project_id = var.project_id environment_id = var.environment_id name = "Runtime" key_type = "server" scopes = ["snapshot:read"] secret_version = var.runtime_sdk_key_version secret_wo = var.runtime_sdk_key } ``` Use the same write-only pattern for `shipd_service_account_token`. Set `service_account_id` and `expires_at`, supply a scope map, and omit `key_type`. CI can load the secret from its store into `TF_VAR_runtime_sdk_key` with shell command tracing disabled. The secret is required when creating or replacing a credential. Refresh and destroy can run with the ephemeral variable set to null. **Terraform state and saved plans.** These resources persist IDs, names, bindings, scopes, expiry, the secret-store version identifier, key type for SDK keys, and revocation status. They store no plaintext, lookup prefixes, or hashes, and expose no secret output. Terraform keeps the version identifier locally. The provider sends the prefix and SHA-256 digest to shipd for lookup and verification. `SHIPD_API_KEY` keeps the bootstrap token outside Terraform configuration. Terraform's `sensitive` marking only masks display output. Use an ephemeral input and write-only argument to keep a credential out of plans and state. An ordinary sensitive variable, output, or secret store resource elsewhere in your configuration may still persist its value. ### Recover an interrupted apply If a request times out or an apply ends before writing state, rerun with the original UUID, original metadata, and same secret-store version. The API compares the UUID, lookup prefix, hash, and credential metadata before acknowledging the existing record. For SDK keys, it also retries edge publication. Concurrent or repeated registrations produce one credential and one creation audit event. Changing the secret or metadata under the same ID produces a conflict. The provider never replays a response containing a secret. If the original secret-store version is gone, wait for any in-flight apply to settle, then revoke the old credential by UUID in shipd before registering a new UUID and secret. If the interrupted run never wrote state, use the dashboard or call `sdkKey/revoke` with `keyId` and `orgId`, or `serviceAccount/revokeToken` with `tokenId`, `serviceAccountId`, and `orgId`. You can apply the exact original configuration to recover ownership of a live Terraform registration. Importing credentials created through other workflows with `terraform import` is unsupported. Existing service account identities can still be imported. ### Rotate, retire, and replace 1. Create a second resource with a fresh UUID and secret. Apply while the old resource stays in configuration. 2. Switch the consumer to the new secret-store version and verify an authenticated request. 3. Remove the old resource and apply to revoke it, then retire its secret-store version. Both credentials remain usable between the two applies, up to either credential's expiry. Choose and enforce the overlap in CI. shipd applies no automatic grace period. CI can revoke an SDK key by ID after its project is archived. SDK key revocation takes effect as it propagates to the edge. Open WebSocket connections revalidate at least every 60 seconds. Service account tokens fail control-plane authentication when revoked, expired, or attached to a disabled account. See [credential revocation behavior](/concepts/keys#rotate-or-revoke-a-credential). Changing the secret version or another immutable property requires a fresh UUID and secret. Keep the secret-store version immutable because Terraform cannot diff the write-only value. Replacing one resource address uses Terraform's default destroy-first ordering and can interrupt workloads. Use the two-resource sequence for overlap. Avoid forcing replacement with `-replace` on the same UUID, since revoked registrations cannot be reused. Refresh shows `revoked = true` for a credential revoked outside Terraform. Expiry and external revocation require an explicit rotation. # Usage and limits Source: https://docs.useshipd.com/reference/usage-and-limits Understand current usage, plan quotas, rate limits, and what happens when your plan changes. ## Overview Use this page to understand what counts toward your plan, when usage resets, and what happens at a limit. Usage charts can lag behind enforcement; short-window rate limits are separate from your monthly allowance. ## View usage Open **Settings → Usage** to see your organization's current resource counts, daily activity, monthly SDK requests, plan limits, and the next UTC reset date. Counts include activity from the dashboard, CLI, management API, SDK keys, and service accounts. Usage charts can lag by about one minute plus the scheduled aggregation interval. Monthly limits apply even while the chart catches up. ## What is counted | Usage | Definition | | - | - | | Projects, flags, environments, audiences, entities, and teams | Live, non-archived resources in the organization | | Members | Active members with editor, admin, or owner access; viewers do not consume a seat | | SDK requests | One organization-wide pool: configuration requests plus accepted event batches during the UTC calendar month | | Configuration requests | Authenticated snapshot, stream-ticket, and identity-read requests admitted by the SDK service; a cached snapshot response still counts | | Event requests | Accepted SDK event batches; one batch counts as one request regardless of event count | | Dropped event batches | Batches discarded by sampling or the monthly limit; excluded from the pool | | Snapshot requests | Successful attempts to fetch a published configuration snapshot | | Evaluation events | Evaluation records accepted from SDK event batches | | WebSocket connections | Accepted connection attempts and connected seconds | | Peak connections | Highest observed concurrent WebSocket count in the period, not a sum | Application logs, errors, latency, and infrastructure metrics are operational telemetry. They are not added to product usage or billing totals. ## Quotas and rate limits A product quota is part of your plan, such as a maximum number of projects or monthly SDK requests. Creating a resource at its limit returns the stable error code `quota_exceeded`. A rate limit protects service availability over a short window. It is separate from plan usage and returns `rate_limited`. Reducing request bursts does not increase a product quota. ## Shared monthly SDK allowance | Plan | Pooled requests per UTC month | | - | - | | Free | 1,000,000 | | Pro | 10,000,000 | | Teams | 50,000,000 | | Enterprise | Custom agreement (unlimited by default) | The allowance is shared across all projects, environments, and SDK keys in your organization. Configuration and event requests have separate usage meters within that single pool. Local flag evaluations and WebSocket update messages do not consume additional SDK requests. You can continue fetching configuration even beyond 100% usage. You must still stay within the short-window abuse rate limits. | Pooled usage | Event ingestion behavior | | - | - | | Below 80% | You can ingest every valid batch | | 80% to below 100% | You ingest a random 50% sample of your batches | | 100% or higher | You cannot ingest batches until reset or an allowance increase | You receive sampling decisions for whole batches, including evaluation and identify events. When sampling or the monthly limit drops your batch, you receive HTTP `202` with `accepted: 0`, a dropped event count, and `reason: "sampled"` or `"quota"`. Do not retry these batches. Read the `X-Shipd-Event-Sample-Rate` response header for the acceptance rate: `1`, `0.5`, or `0`. During sampling, you collect incomplete analytics, and you lose any identify updates in dropped batches because shipd does not persist them. **Settings → Usage** shows the pooled total, separate configuration and event totals, dropped batches, and reset date. Notices appear at 70%, 80%, 90%, and 100%. These reports can lag behind enforcement by about one minute plus hourly aggregation. Monthly allowances also reset monthly on annual plans. No automatic overage charge is configured; upgrade or contact support if you need a larger pool. ## Plan changes Upgrades allow new activity after the entitlement refresh reaches the relevant service. Downgrades prevent new resources or premium mutations that exceed the new plan, but do not delete existing resources or make existing configuration, audit history, or approval history unreadable. Plan and entitlement changes appear in the audit log. ## Retries, outages, and corrections Retries of the same usage event do not increase your recorded total. Usage recording is isolated from flag evaluation. If usage ingestion is temporarily unavailable, evaluation and snapshot delivery continue and queued events retry. Raw events are retained for 35 days; daily and monthly totals remain until the organization is deleted. Contact support if you need a usage correction, particularly for activity older than that 35-day window. Related: [Control-plane API](/reference/control-plane-api) · [Edge API](/reference/edge-api) · [Errors](/reference/errors). ## Customer webhooks Customer events use separate delivery, endpoint, ingestion, retention, and reserved-storage allowances. Hard caps apply; SDK additional-usage settings do not authorize webhook overage. Automatic retries are included; manual redelivery reserves another delivery unit. Check the [customer webhook limits](/reference/customer-events#usage-and-limits) and your organization’s effective usage before enabling a producer. # Migrate from environment variables Source: https://docs.useshipd.com/resources/migrate-from-env-vars Replace FEATURE_X environment variables with shipd flags, keeping the variable as the default during the switch. ## Overview If you gate features with checks like `process.env.FEATURE_NEW_CHECKOUT === "true"`, each variable maps to a flag. In this guide you replace one with the boolean flag `new-checkout`, keep the variable as the SDK default while you migrate, then delete it. ## Map variables to flag types | Environment variable | Flag | | - | - | | `FEATURE_NEW_CHECKOUT=true` | `type: "boolean"` → [`isEnabled`](/reference/sdk#isenabled) | | `SEARCH_MODE=semantic` (fixed set of values) | `type: "variant"` → [`getVariant`](/reference/sdk#getvariant) | | `MAX_RETRIES=3` | `type: "number"` → [`getNumber`](/reference/sdk#getnumber) | | `CHECKOUT_CONFIG='{"mode":"strict"}'` | `type: "json"` → [`getJson`](/reference/sdk#getjson) | Per-deploy values (`.env.staging`, `.env.production`) become per-environment **Fallthrough** values. Secrets and connection strings stay in environment variables. ## Steps **1. Define the flag** ```ts TypeScript theme={null} // shipd.config.ts import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, description: "Replaces FEATURE_NEW_CHECKOUT", }, }); ``` ```go Go theme={null} // Entry inside config.ShipdConfig (import github.com/alasti-company/shipd-go/config). "new-checkout": {Type: "boolean", Default: false, Description: "Replaces FEATURE_NEW_CHECKOUT"}, ``` **2. Push it and match each environment** ```bash theme={null} shipd push --project web-app --env production ``` For each environment where the variable is currently `true`, open the flag in the dashboard, select the environment, set **Fallthrough** to `true`, and click **Save environment**. Push sets **Fallthrough** in the environment you push to from `default`, and resets it on every push when they differ. If the environment you push to serves `true`, change `default` to `true` in `shipd.config.ts` (or run `shipd pull`) before your next push, or the push turns the flag off there. Other environments keep their dashboard value. See [Environments](/concepts/environments). **3. Use the variable as the SDK default** Until shipd serves the flag, the client falls back to `defaults`. Seed them from the variable so behavior doesn't change if the edge is unreachable during the switch: ```ts TypeScript theme={null} // src/lib/shipd.ts import { createClient } from "shipdit"; import type { FlagDefinitions } from "../generated/flags"; export const shipd = createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, defaults: { "new-checkout": process.env.FEATURE_NEW_CHECKOUT === "true", }, }); await shipd.ready(); ``` ```go Go theme={null} // Initialize once at process startup. Imports: context, log, os, time, and shipd. client, err := shipd.New(shipd.Options{ SDKKey: os.Getenv("SHIPD_SDK_KEY"), Defaults: map[string]any{ "new-checkout": os.Getenv("FEATURE_NEW_CHECKOUT") == "true", }, }) if err != nil { log.Fatal(err) } defer func() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if err := client.Shutdown(ctx); err != nil { log.Printf("shipd events: %v", err) } }() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) if err := client.Ready(ctx); err != nil { log.Printf("using defaults: %v", err) } cancel() ``` **4. Replace the checks** ```ts TypeScript theme={null} // src/checkout.ts // Before if (process.env.FEATURE_NEW_CHECKOUT === "true") { /* … */ } // After if (shipd.isEnabled("new-checkout", { userId })) { /* … */ } ``` ```go Go theme={null} // Before if os.Getenv("FEATURE_NEW_CHECKOUT") == "true" { /* ... */ } // After if client.IsEnabled("new-checkout", shipd.EvaluationContext{UserID: userID}) { /* ... */ } ``` **5. Remove the variable** Once every deploy reads the flag, replace the default with a literal (`"new-checkout": false`) and delete `FEATURE_NEW_CHECKOUT` from your environments. Now you can change the value without a redeploy, and [target users](/flags/targeting) or [roll out by percentage](/flags/percentage-rollouts). For Go definition snippets, add the entries to `config.ShipdConfig` in `shipd.config.go` before pushing. See [Define flags in code](/config-as-code/define-flags#go-definitions). ## Related * [Create a boolean flag](/flags/boolean) * [Node.js SDK](/sdks/node) # Migrate from LaunchDarkly Source: https://docs.useshipd.com/resources/migrate-from-launchdarkly Map LaunchDarkly flags, variations, contexts, and segments to shipd, and move flags over one at a time. ## Overview Move from LaunchDarkly to shipd one flag at a time by manually recreating flag definitions in TypeScript or Go. Recreate targeting in the dashboard or define it in code for a selected environment. ## Concept mapping | LaunchDarkly | shipd | | - | - | | Project / environment | Project / environment | | Flag | Flag, defined in `shipd.config.ts` | | Boolean flag | Boolean flag (`type: "boolean"`) | | String flag with a fixed set of variations | Variant flag (`type: "variant"`) | | Number flag | Number flag (`type: "number"`) | | JSON flag | JSON flag (`type: "json"`) | | Variations | `variants` (variant flags) or the values rules serve | | Context (user) | [Evaluation context](/reference/sdk#types): `userId` plus `attributes` | | Individual targets | A rule: `userId` **is one of** a list | | Targeting rules | Rules on the flag page or in a `targeting` block. First match wins | | Percentage rollout | **Percentage** condition ([rollouts](/flags/percentage-rollouts)) ([A/B splits](/flags/experiments)) | | Segments | Audiences | | Default rule (fallthrough) | **Fallthrough** | | Targeting off / off variation | No separate off variation. A disabled flag serves its **Fallthrough** value; to turn a flag off, set **Fallthrough** to the off value ([details](/flags/kill-switch)) | | SDK key | Server SDK key (`shipd_sdk_server_…`) | | Mobile key / client-side ID | Client SDK key (`shipd_sdk_client_…`) | | Relay Proxy | Not needed. SDKs download a snapshot from the edge and evaluate locally | | Code-level fallback value | Client `defaults` | Contexts with several kinds (user, organization, device) become attributes on one evaluation context. To bucket a rollout by organization instead of user, set the percentage condition's **Of attribute** to an attribute such as `organizationId`. Prerequisite flags have no equivalent. Express the dependency in code or in each flag's rules. ## Migrate a flag **1. Recreate the definition** Keep the same key so call sites are easy to find. ```ts TypeScript theme={null} // shipd.config.ts import { defineFlags } from "shipdit/config"; export default defineFlags({ "new-checkout": { type: "boolean", default: false, description: "Migrated from LaunchDarkly", }, "search-variant": { type: "variant", variants: ["control", "semantic", "hybrid"] as const, default: "control", }, }); ``` ```go Go theme={null} // Entries inside config.ShipdConfig (import github.com/alasti-company/shipd-go/config). "new-checkout": {Type: "boolean", Default: false, Description: "Migrated from LaunchDarkly"}, "search-variant": {Type: "variant", Default: "control", Variants: []string{"control", "semantic", "hybrid"}}, ``` **2. Push** ```bash theme={null} shipd push --project web-app --env production ``` **3. Recreate targeting** Recreate segments under **Audiences** in the [dashboard](https://app.useshipd.com). In each environment, add rules in LaunchDarkly order, reference the new audiences, set **Fallthrough**, and click **Save environment**. To manage the selected environment in code, push a [`targeting` block](/reference/config#targeting-in-code) that references the existing audience keys. This publishes targeting immediately when policy allows, including in production. If an approval policy applies, complete the approval and publication flow. **4. Send the same attributes** Pass the attributes your LaunchDarkly rules used (for example `email`, `plan`, `country`) in the evaluation context. See [Identify users](/flags/identify-users). **5. Dual-run behind a wrapper** Wait for both SDKs to load their initial flag data before comparing results. Route evaluations through one function, compare both systems, then switch. ```ts TypeScript theme={null} // src/lib/flags.ts import { shipd } from "./shipd"; import { ldClient } from "./launchdarkly"; export async function newCheckoutEnabled(user: { id: string; plan: string }) { const fromShipd = shipd.isEnabled("new-checkout", { userId: user.id, attributes: { plan: user.plan }, }); const fromLd = await ldClient.variation( "new-checkout", { kind: "user", key: user.id, plan: user.plan }, false, ); if (fromShipd !== fromLd) { console.warn("flag mismatch", { key: "new-checkout", userId: user.id, fromShipd, fromLd }); } return fromLd; // switch to fromShipd once mismatches stop } ``` ```go Go theme={null} // flags.go package flags import ( shipd "github.com/alasti-company/shipd-go" "log" ) // Pass a function that calls your existing LaunchDarkly client. func newCheckoutEnabled(client *shipd.Client, userID, plan string, fromLaunchDarkly func() (bool, error)) (bool, error) { fromShipd := client.IsEnabled("new-checkout", shipd.EvaluationContext{ UserID: userID, Attributes: map[string]any{"plan": plan}, }) fromLD, err := fromLaunchDarkly() if err != nil { return false, err } if fromShipd != fromLD { log.Printf("flag mismatch: key=new-checkout user=%s shipd=%v ld=%v", userID, fromShipd, fromLD) } return fromLD, nil // Switch to fromShipd once differences are acceptable. } ``` **6. Cut over** Return the shipd value, remove the LaunchDarkly call, and archive the flag in LaunchDarkly. Percentage rollouts hash differently in each tool, so a user in LaunchDarkly's 20% isn't necessarily in shipd's 20%. Expect mismatches for rolled-out flags, and cut them over when the difference is acceptable. For Go definition snippets, add the entries to `config.ShipdConfig` in `shipd.config.go` before pushing. See [Define flags in code](/config-as-code/define-flags#go-definitions). ## Related * [Compare shipd and LaunchDarkly](https://www.useshipd.com/vs/launchdarkly#try-one-flag) * [Quickstart](/quickstart) * [Define flags in code](/config-as-code/define-flags) * [Local evaluation](/concepts/local-evaluation) # Migrate from Statsig Source: https://docs.useshipd.com/resources/migrate-from-statsig Map Statsig gates, experiments, and dynamic configs to shipd flags, and move them over one at a time. ## Overview This page maps Statsig concepts to shipd and shows a manual migration path. shipd has no automated importer: you recreate definitions in TypeScript or Go, recreate targeting in the dashboard, and switch code over one gate or config at a time. shipd assigns variants but doesn't compute experiment results. Keep sending exposures and metrics to your analytics tool. ## Concept mapping | Statsig | shipd | | - | - | | Feature gate | Boolean flag (`type: "boolean"`) → [`isEnabled`](/reference/sdk#isenabled) | | Gate rules | Rules on the flag page. First match wins | | Gate pass percentage | **Percentage** condition ([rollouts](/flags/percentage-rollouts)) | | Experiment groups | Variant flag (`type: "variant"`) with a percentage split ([A/B tests](/flags/experiments)) | | Layers | No equivalent. Use one variant flag per experiment | | Dynamic config | JSON flag (`type: "json"`) → [`getJson`](/reference/sdk#getjson) | | Parameter that is a number | Number flag (`type: "number"`) → [`getNumber`](/reference/sdk#getnumber) | | Segments | Audiences | | `StatsigUser` | [Evaluation context](/reference/sdk#types) | | `userID` | `userId` | | `email`, `country`, `custom` fields | `attributes` | | `customIDs` | `attributes`, with the percentage condition's **Of attribute** set to bucket on them | | Server secret key | Server SDK key (`shipd_sdk_server_…`) | | Client SDK key | Client SDK key (`shipd_sdk_client_…`) | | Pulse / experiment results | Not provided. Analyze in your own analytics | ## Map the user object ```ts TypeScript theme={null} // Statsig const user = { userID: "usr_8f2k19", email: "dana@fieldkit.dev", country: "US", custom: { plan: "pro" }, customIDs: { companyID: "org_fieldkit" }, }; // shipd const context = { userId: "usr_8f2k19", attributes: { email: "dana@fieldkit.dev", country: "US", plan: "pro", companyID: "org_fieldkit", }, }; ``` ```go Go theme={null} // Map Statsig's userID to UserID; other user fields become Attributes. user := shipd.EvaluationContext{ UserID: "usr_8f2k19", Attributes: map[string]any{ "email": "dana@fieldkit.dev", "country": "US", "plan": "pro", "companyID": "org_fieldkit", }, } ``` Browser clients (`shipdit/client`) fill `country`, `region`, `city`, and `timezone` automatically. See [Target users by attribute](/flags/targeting). ## Migrate **1. Recreate definitions** ```ts TypeScript theme={null} // shipd.config.ts import { defineFlags } from "shipdit/config"; export default defineFlags({ // gate: new_checkout "new-checkout": { type: "boolean", default: false }, // experiment: search_ranking "search-variant": { type: "variant", variants: ["control", "semantic", "hybrid"] as const, default: "control", }, // dynamic config: checkout_config "checkout-payload": { type: "json", default: { mode: "strict", showPromo: true }, }, }); ``` ```go Go theme={null} // Entries inside config.ShipdConfig (import github.com/alasti-company/shipd-go/config). "new-checkout": {Type: "boolean", Default: false}, "search-variant": {Type: "variant", Default: "control", Variants: []string{"control", "semantic", "hybrid"}}, "checkout-payload": {Type: "json", Default: map[string]any{"mode": "strict", "showPromo": true}}, ``` ```bash theme={null} shipd push --project web-app --env production ``` **2. Recreate targeting** For each environment, open the flag in the [dashboard](https://app.useshipd.com), add rules in the same order as in Statsig, set **Fallthrough**, and click **Save environment**. Recreate segments under **Audiences** first. **3. Replace calls** ```ts TypeScript theme={null} // src/checkout.ts // Before const on = statsig.checkGate(user, "new_checkout"); const ranking = statsig.getExperiment(user, "search_ranking").get("variant", "control"); const config = statsig.getConfig(user, "checkout_config").value; // After const on = shipd.isEnabled("new-checkout", context); const ranking = shipd.getVariant("search-variant", context); const config = shipd.getJson("checkout-payload", context); ``` ```go Go theme={null} // Replace your existing Statsig evaluations with these local checks. on := client.IsEnabled("new-checkout", user) ranking := client.GetVariant("search-variant", user) config := client.GetJSON("checkout-payload", user) ``` Wrap each check in one function and log mismatches between the two systems before you switch, as in the [LaunchDarkly guide](/resources/migrate-from-launchdarkly#migrate-a-flag). **4. Keep logging exposures** Log the variant to your analytics wherever you read it. See [Run an A/B test](/flags/experiments#read-the-variant-and-record-exposure). Bucketing differs between tools, so users in a running Statsig experiment get new assignments in shipd. Start a new experiment period rather than migrating one mid-flight. For Go definition snippets, add the entries to `config.ShipdConfig` in `shipd.config.go` before pushing. See [Define flags in code](/config-as-code/define-flags#go-definitions). ## Related * [Quickstart](/quickstart) * [Define flags in code](/config-as-code/define-flags) # Troubleshooting Source: https://docs.useshipd.com/resources/troubleshooting Fixes for flags that don't update, always return the default, push conflicts, 401s, type errors, and more. ## Overview Each section below is a question developers ask about shipd, with the likely causes, how to check each one, and the fix. Links point to the page that owns the full behavior. Two checks help with most problems: ```ts TypeScript theme={null} // src/lib/shipd.ts export const shipd = createClient({ // … onError: (error) => console.error("[shipd]", error), }); // null means no snapshot has loaded yet. console.log("snapshot version", shipd.getVersion()); ``` ```go Go theme={null} log.Printf("shipd request error: %v", client.LastError()) result := client.Evaluate("new-checkout", shipd.EvaluationContext{}) if result.SnapshotVersion != nil { log.Printf("snapshot version: %d", *result.SnapshotVersion) } else { log.Print("no snapshot loaded") } ``` ```bash Terminal theme={null} shipd whoami # Organization, project, and environment your CLI key targets ``` ## Why isn't my flag updating? | Cause | Check | Fix | | - | - | - | | You are waiting for the next poll | You did not pass `stream: true` | Wait up to `refreshIntervalMs` (30 seconds by default), or pass `stream: true` for realtime updates. | | Realtime is off on Node.js 20 | `onError` logs `shipdit: WebSocket is not available in this runtime` | Pass a `WebSocket` constructor. See [WebSocket is not available in this runtime](#websocket-is-not-available-in-this-runtime). | | The SDK key belongs to another environment | Find the key on the project's **SDK keys** page and compare its environment with the one you edited | Use an SDK key created for the environment you are changing. See [SDK keys](/concepts/keys). | | You changed a different environment | `shipd whoami` shows the environment `shipd push` targets; the dashboard shows the active environment | Push with `--env `, or switch environments in the dashboard and save again. | | The dashboard change was not saved | Reload the flag page; unsaved edits are gone | Make the change again and click **Save environment**. | | The change is waiting for approval | The flag has a pending request in **Approvals** | Get the request reviewed. See [Review production changes](/operations/approvals). | | The flag is disabled | **Enabled in ``** is off | A disabled flag skips all rules and serves the **Fallthrough** value. To turn a feature off, set **Fallthrough** to `false`. See [Kill switch](/flags/kill-switch). | | An earlier rule matches first | Test the user in the flag page simulator | Rules run top to bottom and the first match wins. Reorder the rules or narrow the earlier one. See [Target users](/flags/targeting). | For Go, confirm `DisablePolling` is false and check `LastError()`. Use a bounded context with `Refresh(ctx)` to check a request immediately. Go does not use the WebSocket options in the TypeScript checks above. See [Go reference](/reference/go-sdk). ## Why does my flag always return the default? | Cause | Check | Fix | | - | - | - | | You evaluate before the first snapshot loads | `shipd.getVersion()` returns `null` | `await shipd.ready()` at startup, or use `useReady()` in React. | | The key is misspelled or does not exist | The SDK emits an `unregistered_flag` event; `shipd flags list` does not show the key | Fix the key, or run `shipd push` to create the flag. Generated types catch typos at compile time. | | The SDK key is for another project or environment | Compare the key's project and environment on the **SDK keys** page | Use a key for the project and environment that contains the flag. | | The edge rejects the key | `onError` reports a `401` | See [Why does the edge return 401?](#why-does-the-edge-return-401) | | The rule needs a bucket attribute | The percentage condition uses `userId` (the default) or another attribute that is missing from your evaluation context | Pass the configured bucket attribute. In browsers, `identify()` also sets `userId`. | | The flag was archived | The [audit log](/operations/audit-log) shows the archive, from the dashboard or `shipd push --prune` | Archived flags are removed from the snapshot, so the SDK serves your `defaults`. Remove the check from your code. | The SDK never throws from an evaluation method. When it cannot resolve a value, it serves your `defaults`, or `false`, `"control"`, `0`, or `{}` if you did not pass one. See [SDK](/reference/sdk). ## Why did shipd push return 409 / exit 3? **Cause.** `shipd push` exits with code `3` when the control plane returns `409 conflict`. Usually someone changed the flag after your last `shipd pull`. It also happens when a pending approval request already exists for the change, or when the push contains an operation that a policy-protected environment does not support. **Check.** Run `shipd diff` to see how the server differs from your `shipd.config.ts`. **Fix.** Run `shipd pull`, merge your change, and push again. See [Resolve a push conflict](/config-as-code/conflicts) and [Errors](/reference/errors). ## shipd push exited with code 5 **Cause.** An approval policy accepted part of the push but queued it for review. Exit code `5` means `pending_approval`: the queued changes are not live yet. **Check.** Run the push with `--json` and read `approvalRequests`, or open **Approvals** in the dashboard. **Fix.** Ask an eligible reviewer to approve the request. `--yes`, `--ci`, and `--force` do not bypass approval. Pushing again while the request is pending returns exit code `3`. See [Review production changes](/operations/approvals). ## Why does the edge return 401? **Cause.** The edge returns the same generic `401` for any credential it does not accept: * The SDK key was revoked. * The key is a management API key (`shipd_mgmt_…`) or service account token (`shipd_sa_…`). Only SDK keys work on the edge. * The key was truncated or has extra whitespace. **Check.** Confirm the key starts with `shipd_sdk_server_` or `shipd_sdk_client_`, and that it shows **Active** on the project's **SDK keys** page. **Fix.** Create a new SDK key and deploy it. After a `401`, the SDK keeps its last good snapshot and reports the error to `onError`. See [SDK keys, management API keys, and service account tokens](/concepts/keys) and [Edge API](/reference/edge-api). ## TypeScript says my flag key is not assignable **Cause.** The flag key is not in your generated `FlagDefinitions`, or it is the wrong flag type for the method (for example, `isEnabled` on a variant flag). **Check.** Open `src/generated/flags.ts` (or your configured `typesOut`) and search for the key. Check that `FlagDefinitions` is imported from that generated file and passed to `createClient()` or `createShipdReact()`. **Fix.** Regenerate types: ```bash Terminal theme={null} shipd types gen ``` `shipd push` and `shipd pull` also regenerate them. Use the method that matches the flag type: `isEnabled` for boolean, `getVariant` for variant, `getNumber` for number, and `getJson` for JSON flags. See [Generated types](/config-as-code/types). ## Percentage rollout serves everyone the same value **Cause.** A percentage condition buckets by `userId` (or a chosen attribute). Without it, the condition never matches, so every request falls through to the same value. **Check.** Log the evaluation context you pass. TypeScript server clients have no `userId` unless you pass one per call or in `createClient({ context })`. Go requires `EvaluationContext` per call and has no client-wide context option. Server `identify()` / `Identify` does not set evaluation context. **Fix.** Pass a stable `userId`: ```ts TypeScript theme={null} shipd.isEnabled("new-checkout", { userId: "usr_8f2k19" }); ``` ```go Go theme={null} client.IsEnabled("new-checkout", shipd.EvaluationContext{UserID: "usr_8f2k19"}) ``` See [Roll out a flag to a percentage of users](/flags/percentage-rollouts) and [Identify users](/flags/identify-users). ## WebSocket is not available in this runtime **Cause.** You passed `stream: true`, but the runtime has no global `WebSocket`. Node.js 20 does not; Node.js 22 and later, and browsers, do. **Check.** `onError` receives `shipdit: WebSocket is not available in this runtime`. Polling still works. **Fix.** Upgrade to Node.js 22, pass a constructor from the `ws` package, or omit `stream` to poll only: ```ts src/lib/shipd.ts theme={null} import WebSocket from "ws"; export const shipd = createClient({ // … stream: true, WebSocket, }); ``` See [Node.js and server runtimes](/sdks/node). ## Flags flash in the browser on load **Cause.** The page renders with your `defaults`, then re-renders when the initial `POST /sdk/v1/evaluate` response arrives. **Check.** The flash happens while initial evaluated values are loading, after `identify()` or `reset()`, or when a key is not listed in `defaults`. **Fix.** Pick one: | Option | How | | - | - | | Preload keys and wait for `ready()` | List the flags you need in `defaults` so the first request includes them. In React, render a placeholder until `useReady()` returns `true`. Without React, `await shipd.ready()` before rendering. | | Evaluate on the server and pass values down | Evaluate the flags on your server with a server SDK key and pass only the resolved values to the browser (for example, as SSR props or from an authenticated API endpoint). Never pass a full server snapshot to a browser client; browser clients reject `bootstrap` and snapshot `cache` adapters. | See [Client vs. server evaluation](/concepts/client-vs-server), [Browser](/sdks/browser), [React](/sdks/react), and [Next.js](/sdks/nextjs). ## What happens if shipd is down? Flag checks keep working. Evaluation is local, so SDKs serve the last good snapshot while the edge is unreachable, and continue polling if the WebSocket gateway is down, provided polling is enabled. If the control plane is down, `shipd push` and the dashboard fail, but evaluation continues from the last published snapshot. See [What happens if shipd is down?](/concepts/local-evaluation#what-happens-if-shipd-is-down) # Browser Source: https://docs.useshipd.com/sdks/browser Evaluate flags in the browser with shipdit/client, a client SDK key, identify, and subscribe. ## Overview In this guide you evaluate flags in a browser app with `shipdit/client`. It has the same synchronous getters as the server client. Targeting runs at the edge; only requested values reach the browser. Rules, audiences, and alternative values stay server-side. The client keeps values in memory and persists only a stable anonymous id. Using React? Read [React](/sdks/react) after this page. ## Install ```bash theme={null} pnpm add shipdit ``` ## Use a client SDK key In the [dashboard](https://app.useshipd.com), go to **SDK keys**, click **Create SDK key**, and set **Key type** to `client`. Client keys (`shipd_sdk_client_…`) are safe to embed in browser bundles. > [!WARNING] > > Never ship a server SDK key (`shipd_sdk_server_…`) to a browser. See [Keys](/concepts/keys). ## Create the client ```ts src/lib/shipd.ts theme={null} import { createClient } from "shipdit/client"; import type { FlagDefinitions } from "../generated/flags"; export const shipd = createClient({ sdkKey: import.meta.env.VITE_SHIPD_SDK_KEY, stream: true, defaults: { "new-checkout": false, "search-variant": "control", }, }); ``` The browser client adds these behaviors to the [`createClient`](/reference/sdk#createclient) options: | Behavior | Default | Turn off or change | | - | - | - | | Generate a stable `anonymousId` under `shipdit:anonymousId` | On | `anonymousId`, `anonymousStorageKey` | | Add `country`, `region`, `city`, and `timezone` to the evaluation context | On | `automaticTraits: false` | Location traits come from edge geolocation and the browser's time zone. Traits you pass yourself win. See [Target users](/flags/targeting). ## Identify on login, reset on logout ```ts src/auth.ts theme={null} import { shipd } from "./lib/shipd"; export function onLogin(user: { id: string; name: string; plan: string }) { shipd.identify({ userId: user.id, name: user.name, traits: { plan: user.plan }, }); } export function onLogout() { shipd.reset(); // clears the identity and rotates the anonymousId } ``` Later checks reuse that identity, so you can call `shipd.isEnabled("new-checkout")` with no arguments. See [Identify users](/flags/identify-users). ## Re-render on changes Flag values change when evaluated values arrive or when `identify()` or `reset()` runs. Identity changes immediately clear previous values and request fresh ones. Getters return defaults until those values arrive. `subscribe()` calls your listener on each change and returns an unsubscribe function. ```ts src/main.ts theme={null} import { shipd } from "./lib/shipd"; function render() { const checkout = document.querySelector("#checkout-link")!; checkout.setAttribute( "href", shipd.isEnabled("new-checkout") ? "/checkout/new" : "/checkout", ); } render(); const unsubscribe = shipd.subscribe(render); ``` ## Avoid a flash of default content The first render uses `defaults` while values load. List the flags you need in `defaults` so the first request includes them, then await `ready()` before rendering flag-dependent UI. A key first used later, or a new per-call context, initially returns its default and loads in the background. Subscribe to receive the resolved value. ```ts theme={null} await shipd.ready(); render(); ``` `ready()` covers initial loading and resolves after the first attempt or `readyTimeoutMs` (5 seconds by default). After `identify()` or `reset()`, use `subscribe()` for the refreshed values. Polling and streaming refresh values without downloading rules. If a refresh fails, values for the same context remain available; a different identity starts with defaults. Browser clients support up to 100 distinct flag keys and retain up to 32 evaluation contexts in memory. They reject server SDK keys, full snapshot `bootstrap`, and snapshot `cache` adapters. `persist` is deprecated and has no effect. The SDK removes its old snapshot cache on upgrade. > [!WARNING] > > A client key is public and evaluation context is supplied by the caller. Anyone with the key can request known `clientAvailable: true` flag values with different traits. Keep private targeting, secrets, and authorization decisions on your server. For private flags, expose allowlisted evaluated values through an authenticated application endpoint. See [Client vs. server evaluation](/concepts/client-vs-server). ## Next * [Client vs. server evaluation](/concepts/client-vs-server) * [React](/sdks/react) * [Identify users](/flags/identify-users) * [Local evaluation](/concepts/local-evaluation) * [SDK reference](/reference/sdk) ## Client availability and evaluation Flags are server-only by default, including existing flags after migration. In a flag’s **Definition**, enable **Available to client SDKs** and click **Save definition** to permit public client keys to request its value. This setting applies across environments and publishes a snapshot update. The management API also accepts `clientAvailable: true` in `flag.create` and `flag.update`. You can also set `clientAvailable: true` or `false` in a TypeScript `defineFlags` definition or version-1 JSON config and run `shipd diff` and `shipd push`. Omitting the field preserves the existing remote setting; new flags still default to private. `shipd pull` includes the current setting in TypeScript and JSON source. See [client availability in config](/reference/config#client-availability). Client availability is part of the published snapshot, with the same asynchronous propagation as targeting changes. A successful definition save confirms the database change and queues publication; it does not confirm that every edge location has the new snapshot. If publication fails, the outbox retries and the previous snapshot remains active, including any previously public values. Disabling availability therefore stops new delivery only after the new snapshot propagates. It cannot retract values already downloaded or clear a disconnected client's last good values. Check snapshot publication and verify a fresh evaluation returns `not_found` before treating removal as propagated. For urgent access removal, revoke the SDK key; allow for key-revocation propagation too. Availability is not an immediate secret-revocation mechanism. Browser clients use `POST /sdk/v1/evaluate` with requested `keys`, `userId`, and `attributes`. The response contains evaluated values and evaluation reasons, never rules, audience predicates, rollout configuration, rule ids, or unused variants. Server SDK keys continue fetching the full snapshot for local evaluation. Client keys always receive a 403 from `GET /sdk/v1/snapshot`, including conditional requests. A hidden or missing flag returns `not_found` without a value. The SDK uses configured `defaults`, then its type default (false, `"control"`, 0, or an empty JSON object). A newly requested context uses defaults until its values arrive. Failed refreshes retain last good values for the same context; `identify()` and `reset()` clear previous values before refreshing. Polling and stream notifications refresh the evaluated values. Audience dependencies resolve exclusively at the edge, including private audience predicates used by a client-visible flag. No audience definitions or membership lists are delivered. Flag-to-flag prerequisites are not supported by the current condition schema; publishing a client flag does not make another flag visible. Enabling client availability makes the resulting value public, including any JSON contents you choose to serve. Evaluation responses use `Cache-Control: no-store` with no ETag or shared response cache. The browser stores values only in memory, scoped to its client and canonical identity/attributes/audience context. It never reads old full snapshots as a fallback. Client keys are public bearer credentials: callers can replay requests and claim any identity, attributes, or audience ids. Remote evaluation hides configuration; it does not authenticate those claims. Do not use values for authorization. There is no signed identity mechanism in this protocol; enforce trusted decisions through your authenticated application backend. ## Migrating existing browser applications This is a breaking security migration. Before enabling the restricted edge contract, inventory applications using client keys and notify their owners. Upgrade to the browser SDK version that uses `/sdk/v1/evaluate`, provide initial keys through `defaults`, and explicitly enable client availability for the flags each application needs. Existing and new flags default to private; there is no automatic public backfill. Verify the published snapshots contain the intended settings before cutover. Deploy the database migration and snapshot publisher before the restricted edge route, and coordinate SDK upgrades and availability review with application owners. Snapshots without the availability field remain private. During cutover, older SDKs expecting full snapshots receive 403 and use their existing fallback/cache behavior; they cannot be transparently supported by returning rules. Schedule an announced breaking cutover for applications that cannot upgrade together. Do not roll back the edge restriction to restore compatibility. The new browser SDK removes its legacy namespaced snapshot cache (or the custom `storageKey` you provide) without reading it. It rejects snapshot `bootstrap` and custom `cache` adapters. Already deployed older SDKs may still hold previously downloaded configuration: rebuilding an application cannot erase copies, invalidate public keys, or retract that data. Revoke or rotate exposed keys separately and remove sensitive identifiers from historical configuration where appropriate. Server SDK versions and local evaluation behavior are unchanged. # Convex Source: https://docs.useshipd.com/sdks/convex Mount the Convex component, receive snapshot updates, and evaluate flags in backend functions. ## Overview The `@shipdit/convex` component keeps the last valid shipd snapshot in Convex. Your queries read that local copy, so flag evaluation stays reactive and does not add a network request to each function call. The integration is available on every shipd plan. Mount **one named component instance per shipd environment**. For example, mount `shipdDevelopment` and `shipdProduction` separately. Each instance has its own SDK key, signing secret, snapshot, and health status. ## Install ```bash theme={null} npm install @shipdit/convex ``` Add the component to `convex/convex.config.ts`. The `httpPrefix` gives each instance a distinct webhook route. ```ts convex/convex.config.ts theme={null} import { defineApp } from "convex/server"; import { v } from "convex/values"; import shipd from "@shipdit/convex/convex.config.js"; const app = defineApp({ env: { SHIPD_PRODUCTION_SDK_KEY: v.string(), SHIPD_PRODUCTION_WEBHOOK_SECRET: v.string(), }, }); app.use(shipd, { name: "shipdProduction", httpPrefix: "/shipd/production", env: { SHIPD_SDK_KEY: app.env.SHIPD_PRODUCTION_SDK_KEY, SHIPD_WEBHOOK_SECRET: app.env.SHIPD_PRODUCTION_WEBHOOK_SECRET, }, }); export default app; ``` Run `npx convex dev` after changing component mounts so Convex regenerates `components`. ## Configure environment values Set these values for every mounted instance: ```bash theme={null} npx convex env set SHIPD_PRODUCTION_SDK_KEY shipd_sdk_server_... npx convex env set SHIPD_PRODUCTION_WEBHOOK_SECRET replace-after-dashboard-setup ``` | Value | Purpose | | - | - | | `SHIPD_SDK_KEY` | Server SDK key. Fetches the snapshot for exactly one shipd environment. | | `SHIPD_WEBHOOK_SECRET` | Verifies signed invalidations from shipd. | The component fetches snapshots from `https://edge.useshipd.com`. Do not expose the SDK key or webhook secret to browser code. ## Create the webhook destination 1. Open the project in the shipd dashboard and go to **Settings → Integrations**. 2. Under **Convex**, choose the matching environment. 3. Enter `https://.convex.site/shipd/production/webhook`. 4. Click **Create destination**. 5. Copy the signing secret immediately and replace `SHIPD_PRODUCTION_WEBHOOK_SECRET` in Convex. 6. Redeploy, then click **Test delivery**. The callback hostname must end in `.convex.site` and use HTTPS. shipd signs the exact request body and sends only publication metadata. The component fetches the canonical snapshot from the edge; the webhook never contains flags or credentials. ## Wrap host queries Create one wrapper for each mounted instance. Defaults are required and stay type-safe. ```ts convex/lib/shipd.ts theme={null} import { Shipd } from "@shipdit/convex"; import { components } from "../_generated/api"; type Flags = { "new-checkout": { type: "boolean"; default: false }; "search-variant": { type: "variant"; default: "control"; variants: readonly ["control", "semantic"]; }; }; export const shipd = new Shipd(components.shipdProduction, { "new-checkout": false, "search-variant": "control", }); ``` Component functions cannot see your host application's `ctx.auth`. Authorize in the host function before calling the wrapper: ```ts convex/checkout.ts theme={null} import { query } from "./_generated/server"; import { shipd } from "./lib/shipd"; export const navigation = query({ args: {}, handler: async (ctx) => { const identity = await ctx.auth.getUserIdentity(); if (!identity) throw new Error("Unauthenticated"); return { newCheckout: await shipd.isEnabled(ctx, "new-checkout", { userId: identity.subject, }), search: await shipd.getVariant(ctx, "search-variant", { userId: identity.subject, }), }; }, }); ``` The wrapper also provides `getNumber`, `getJson`, and `evaluate`. Use `evaluate` when you need the reason, matched rule, snapshot version, or stale state. ## Inspect sync health Call `getStatus` from an authorized host query: ```ts theme={null} export const shipdStatus = query({ args: {}, handler: async (ctx) => { const identity = await ctx.auth.getUserIdentity(); if (!identity) throw new Error("Unauthenticated"); return shipd.getStatus(ctx); }, }); ``` `hasSnapshot` tells you whether an initial sync succeeded. `version`, `etag`, and `fetchedAt` identify the cached snapshot. `lastAttemptAt`, `lastError`, and `lastErrorAt` describe sync health. `stale: true` means a valid cached snapshot exists but the latest refresh failed. Webhooks provide fast invalidation. A one-minute ETag poll is the reliability fallback. You can also call `syncNow` from an authorized host action. ## Understand defaults and stale snapshots * Before the first valid snapshot, the wrapper returns your typed default. * A missing flag or value-type mismatch also returns its typed default. * After a successful sync, the component keeps the last valid snapshot indefinitely. * A refresh failure marks that snapshot stale but does not replace it with defaults. * Older out-of-order snapshots are ignored. This makes temporary shipd, webhook, or network failures fail stable instead of changing flag behavior. ## Rotate credentials Rotate the webhook secret without creating a second destination: 1. In the project's **Settings → Integrations**, choose the environment, then click **Rotate secret**. 2. Copy the new secret immediately. 3. Update the matching `SHIPD_WEBHOOK_SECRET` value in Convex and redeploy. 4. Click **Test delivery**. There is no overlap window: requests signed with the old secret fail after rotation. Coordinate the dashboard rotation and Convex deployment during a short maintenance window. The one-minute poll continues refreshing snapshots if webhook delivery fails. Rotate the SDK key separately by creating a replacement server SDK key for the same environment in **SDK keys**, updating `SHIPD_SDK_KEY`, confirming a successful sync, and then revoking the old key. ## Next * [Node.js and server runtimes](/sdks/node) * [Environments](/concepts/environments) * [Keys](/concepts/keys) * [Complete Convex example](/examples/convex) # Go Source: https://docs.useshipd.com/sdks/go Evaluate shipd flags locally in a Go service with one concurrent client and context per request. ## Overview Add shipd to a Go 1.23+ service with one client per environment. Flag checks use an in-memory snapshot and return without waiting for the network. The SDK refreshes snapshots and flushes diagnostic events in the background. Define flags in [TypeScript or Go](/config-as-code/define-flags) and sync them with the CLI. Use a [server SDK key](/concepts/keys) for the environment. If your service already uses OpenFeature, register the [shipd OpenFeature provider](/integrations/openfeature#go). ## Install ```bash theme={null} go get github.com/alasti-company/shipd-go ``` ## Create the client ```go main.go theme={null} package main import ( "context" "log" "os" "time" shipd "github.com/alasti-company/shipd-go" ) func main() { client, err := shipd.New(shipd.Options{ SDKKey: os.Getenv("SHIPD_SDK_KEY"), Defaults: map[string]any{ "new-checkout": false, "search-variant": "control", "max-retries": 3, }, }) if err != nil { log.Fatal(err) } defer func() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() // Shutdown delivers pending events, then closes the client. if err := client.Shutdown(ctx); err != nil { log.Printf("shipd events: %v", err) } }() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) if err := client.Ready(ctx); err != nil { log.Printf("shipd startup: %v; continuing with defaults", err) } cancel() user := shipd.EvaluationContext{ UserID: "usr_8f2k19", Attributes: map[string]any{"plan": "pro"}, } log.Printf("new checkout: %v", client.IsEnabled("new-checkout", user)) log.Printf("search: %s", client.GetVariant("search-variant", user)) log.Printf("retries: %v", client.GetNumber("max-retries", user)) } ``` The client is safe to share across goroutines. Pass an evaluation context per request. Supply `country` or other location traits yourself when needed. `Identify` sends traits to shipd for audience insights and does not set a process-wide identity. ## Updates and failure handling The client fetches a snapshot at startup and polls every 30 seconds using ETags. Network failures, malformed snapshots, and unsupported schema versions keep the last valid snapshot. Before any snapshot loads, configured defaults apply. Use a bounded context with `Ready`, `Refresh`, and `Shutdown`. `LastError` exposes request failures. To stop, stop accepting new requests and drain in-flight handlers within a deadline before calling `Shutdown(ctx)`. Shutdown attempts to flush pending events, then closes the client even if delivery fails. `Close` stops immediately without delivering them. Set `Stream: true` to refresh when a WebSocket update arrives, with polling as a fallback. Supply a `SnapshotCache` adapter through `Cache` to persist snapshots for offline starts. See the [client options](/reference/go-sdk#new). ## Next * [Go SDK reference](/reference/go-sdk) * [Target users](/flags/targeting) * [Roll out a flag to a percentage of users](/flags/percentage-rollouts) ## Definitions and generated accessors Author definitions with `config.ShipdConfig` from `github.com/alasti-company/shipd-go/config` in `shipd.config.go`. The shared CLI reads this Go source directly and generates Go accessors by default after push and pull, unless `typesLanguage` overrides it. Run `shipd types gen` to regenerate locally. See [Define flags in code](/config-as-code/define-flags#go-definitions) and [Generate Go accessors](/config-as-code/types#go-output). # Next.js Source: https://docs.useshipd.com/sdks/nextjs Evaluate flags in Server Components and route handlers with a server key, and in client components with React hooks. ## Overview In this guide you use shipd in a Next.js App Router app. Server Components and route handlers use `shipdit` with a server SDK key. Client components use `shipdit/client` and the React hooks with a client SDK key. There is no Next.js-specific package. You combine the [Node.js](/sdks/node) and [React](/sdks/react) setups. ## Which key goes where Create one key of each type in **SDK keys** for the environment. See [Keys](/concepts/keys). | Code | Entry point | Key | Environment variable | | - | - | - | - | | Server Components, route handlers, server actions | `shipdit` | `shipd_sdk_server_…` | `SHIPD_SDK_KEY` | | Client components (`"use client"`) | `shipdit/client` | `shipd_sdk_client_…` | `NEXT_PUBLIC_SHIPD_SDK_KEY` | ```bash .env.local theme={null} SHIPD_SDK_KEY=shipd_sdk_server_… NEXT_PUBLIC_SHIPD_SDK_KEY=shipd_sdk_client_… ``` > [!WARNING] > > Next.js inlines every `NEXT_PUBLIC_` variable into the browser bundle. Never give the server key > a `NEXT_PUBLIC_` name. ## Evaluate on the server Create the server client in a module that only server code imports. Adding `import "server-only"` (from the [`server-only`](https://www.npmjs.com/package/server-only) package) is optional. It makes the build fail if a client component imports this file. ```ts src/lib/shipd.server.ts theme={null} import "server-only"; import { createClient } from "shipdit"; import type { FlagDefinitions } from "@/generated/flags"; export const shipd = createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, defaults: { "new-checkout": false, "search-variant": "control", "max-retries": 3, "checkout-payload": { mode: "strict", showPromo: true }, }, }); ``` This client doesn't set `stream: true`, so it polls. To add realtime updates on a long-running Node.js server, see [Node.js](/sdks/node#create-the-client-module). Await `ready()` before you evaluate, then pass per-request context: ```tsx src/app/checkout/page.tsx theme={null} import { shipd } from "@/lib/shipd.server"; import { getSession } from "@/lib/auth"; import { CheckoutButton } from "./CheckoutButton"; export default async function CheckoutPage() { await shipd.ready(); const session = await getSession(); const newCheckout = shipd.isEnabled("new-checkout", { userId: session.user.id, attributes: { plan: session.user.plan }, }); return ; } ``` `ready()` resolves once per client, so later requests don't wait. Route handlers work the same way: ```ts src/app/api/search/route.ts theme={null} import { shipd } from "@/lib/shipd.server"; export async function GET(request: Request) { await shipd.ready(); const userId = request.headers.get("x-user-id") ?? undefined; const engine = shipd.getVariant("search-variant", { userId }); return Response.json({ engine }); } ``` Pass context on each server call. On the server client, `identify()` only records an identify event and never changes evaluation context. Use server evaluation whenever targeting depends on verified session identity, role, or billing plan, and pass only the resolved values to client components (or return them from an authenticated route handler with `Cache-Control: no-store`). Keep backend authorization checks on every server action and route handler. See [Client vs. server evaluation](/concepts/client-vs-server). ## Evaluate in client components Bind the hooks in a client module: ```ts src/lib/shipd-react.ts theme={null} "use client"; import { createShipdReact } from "shipdit/client/react"; import type { FlagDefinitions } from "@/generated/flags"; export const { ShipdProvider, useFlag, useVariant, useReady, useShipdClient } = createShipdReact(); ``` Create the browser client and provider in `providers.tsx`: ```tsx src/app/providers.tsx theme={null} "use client"; import { createClient } from "shipdit/client"; import type { FlagDefinitions } from "@/generated/flags"; import { ShipdProvider } from "@/lib/shipd-react"; const client = createClient({ sdkKey: process.env.NEXT_PUBLIC_SHIPD_SDK_KEY!, stream: true, defaults: { "new-checkout": false, "search-variant": "control", }, }); export function Providers({ children }: { children: React.ReactNode }) { return {children}; } ``` ```tsx src/app/layout.tsx theme={null} import { Providers } from "./providers"; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` Identify the signed-in user from a client component inside `Providers`, as shown in [React](/sdks/react#identify-from-your-auth-layer). ## Avoid hydration mismatches Client components are also rendered on the server. The server render and the first browser render can see different snapshots and identities, so a flag can evaluate differently in each. Use one of these patterns: **Evaluate on the server and pass the value down.** The value is fixed in the HTML, so both renders agree. Use this for content that must be correct on first paint. ```tsx src/app/checkout/CheckoutButton.tsx theme={null} "use client"; export function CheckoutButton({ newCheckout }: { newCheckout: boolean }) { return Checkout; } ``` **Gate on `useReady()`.** `useReady()` is `false` during the server render and the first browser render, so both output the same placeholder. The component renders the real value after the client is ready. ```tsx src/components/SearchBox.tsx theme={null} "use client"; import { useReady, useVariant } from "@/lib/shipd-react"; export function SearchBox() { const ready = useReady(); const engine = useVariant("search-variant"); if (!ready) return ; return engine === "semantic" ? : ; } ``` ## Next * [React](/sdks/react) * [Complete Next.js example](/examples/nextjs) * [Identify users](/flags/identify-users) * [SDK reference](/reference/sdk) # Node.js and server runtimes Source: https://docs.useshipd.com/sdks/node Create one shipdit client per process, wait for ready() at startup, and evaluate flags per request. ## Overview In this guide you add `shipdit` to a Node.js service: one client per process, a `ready()` call at startup, and per-request evaluation context. Flag checks run in memory against the environment's snapshot, so they add no network call to a request. This page uses `new-checkout` and `search-variant` from [Define flags in code](/config-as-code/define-flags), plus the `max-retries` number flag and `checkout-payload` JSON flag from [Create number and JSON flags](/flags/number-and-json). Add all four to `shipd.config.ts` and run `shipd push` so the generated `FlagDefinitions` includes them. ## Install ```bash theme={null} pnpm add shipdit ``` `shipdit` requires Node.js 20 or later. ## Create a server SDK key 1. In the [dashboard](https://app.useshipd.com), open your project and select the environment. 2. Go to **SDK keys** and click **Create SDK key**. 3. Enter a name, set **Key type** to `server`, and create it. 4. Copy the key (`shipd_sdk_server_…`). It is shown once. ```bash .env theme={null} SHIPD_SDK_KEY=shipd_sdk_server_… ``` Each SDK key belongs to one environment. See [Keys](/concepts/keys) for all credential types. ## Create the client module Create the client once and import it everywhere. Pass a default for every flag. Defaults are served until the first snapshot arrives and whenever the edge can't be reached. ```ts src/lib/shipd.ts theme={null} import { createClient } from "shipdit"; import type { FlagDefinitions } from "../generated/flags"; export const shipd = createClient({ sdkKey: process.env.SHIPD_SDK_KEY!, stream: true, defaults: { "new-checkout": false, "search-variant": "control", "max-retries": 3, "checkout-payload": { mode: "strict", showPromo: true }, }, }); ``` `stream: true` enables realtime updates over WebSocket. Without it, the client polls every 30 seconds. > [!NOTE] > > The SDK uses `globalThis.WebSocket`, which exists in Node.js 22 and later. On Node.js 20, pass a > constructor from the [`ws`](https://www.npmjs.com/package/ws) package, or omit `stream` > to poll only. > > ```ts theme={null} > import WebSocket from "ws"; > > createClient({ /* … */ WebSocket }); > ``` `createClient` throws if `sdkKey` is empty. The client connects to `https://edge.useshipd.com`, and `stream: true` adds the `https://ws.useshipd.com` gateway. See [`createClient`](/reference/sdk#createclient) for every option. ## Wait for ready at startup Call `ready()` once before you accept traffic. It resolves when the first snapshot loads, or after `readyTimeoutMs` (5 seconds by default). It never rejects for network errors. ```ts src/server.ts theme={null} import { serve } from "@hono/node-server"; import { app } from "./app"; import { shipd } from "./lib/shipd"; await shipd.ready(); export const server = serve({ fetch: app.fetch, port: 3000 }); ``` ## Evaluate per request A server client handles many users at once, so pass the evaluation context on each call. On a server client, `identify()` only records the user's traits for audience insights. It never changes the context that later evaluations use. ```ts src/app.ts theme={null} import { Hono } from "hono"; import { shipd } from "./lib/shipd"; export const app = new Hono(); app.get("/checkout", (c) => { const user = c.get("user"); // from your auth middleware const context = { userId: user.id, attributes: { plan: user.plan, country: user.country }, }; if (!shipd.isEnabled("new-checkout", context)) { return c.json({ flow: "legacy" }); } return c.json({ flow: "new", search: shipd.getVariant("search-variant", context), // "control" | "semantic" | "hybrid" retries: shipd.getNumber("max-retries", context), ui: shipd.getJson("checkout-payload", context), }); }); ``` The same code works in Express: ```ts src/routes/checkout.ts theme={null} router.get("/checkout", (req, res) => { const on = shipd.isEnabled("new-checkout", { userId: req.user.id }); res.json({ flow: on ? "new" : "legacy" }); }); ``` Without a `userId`, percentage rollouts can't assign a bucket. The server SDK doesn't infer location, so pass `country` or other traits yourself. See [Target users](/flags/targeting). ## Shut down cleanly `close()` stops polling, closes the WebSocket, and flushes pending events. Await its promise before exiting; it resolves after delivery finishes, fails, or reaches the timeout (5 seconds by default). ```ts src/server.ts theme={null} process.on("SIGTERM", async () => { // Keep recording while active requests drain; bound long-lived requests. await new Promise((resolve) => { const deadline = setTimeout(() => { server.closeAllConnections(); resolve(); }, 5_000); server.close(() => { clearTimeout(deadline); resolve(); }); }); await shipd.close(); }); ``` ## What happens on failure Evaluation methods never throw. | Situation | What the client serves | | - | - | | Before the first snapshot loads | `defaults` | | Edge unreachable or timing out | Last good snapshot, else `defaults` | | Flag key missing from the snapshot | `defaults[key]` | | SDK key revoked (HTTP 401) | Last good snapshot; `onError` is called | Pass `onError` to log background failures. For the full model, see [Local evaluation](/concepts/local-evaluation). For error messages, see [Errors](/reference/errors). ## Next * [Identify users](/flags/identify-users) * [Next.js](/sdks/nextjs) * [Test flags locally and in unit tests](/sdks/testing) * [SDK reference](/reference/sdk) # React Source: https://docs.useshipd.com/sdks/react Bind typed hooks once, wrap your app in ShipdProvider, and read flags in components. ## Overview In this guide you add typed hooks to a React app: bind them once with `createShipdReact`, provide a browser client, identify the signed-in user, and read flags in components. Hooks re-render when new evaluated values arrive or the identity changes. This page builds on [Browser](/sdks/browser). For the App Router, also read [Next.js](/sdks/nextjs). ## Bind hooks once Call `createShipdReact` in one client-only module and import hooks from there. Hooks from a different `createShipdReact` call can't read this provider. ```ts src/lib/shipd-react.ts theme={null} import { createShipdReact } from "shipdit/client/react"; import type { FlagDefinitions } from "../generated/flags"; export const { ShipdProvider, useFlag, useVariant, useNumber, useJson, useReady, useShipdClient, } = createShipdReact(); ``` Keep this out of `src/generated/flags.ts`. Generated files contain types only, so server code can import `FlagDefinitions` without pulling in React. ## Create the client and provider ```tsx src/main.tsx theme={null} import { createRoot } from "react-dom/client"; import { createClient } from "shipdit/client"; import type { FlagDefinitions } from "./generated/flags"; import { ShipdProvider } from "./lib/shipd-react"; import { App } from "./App"; const client = createClient({ sdkKey: import.meta.env.VITE_SHIPD_SDK_KEY, // shipd_sdk_client_… stream: true, defaults: { "new-checkout": false, "search-variant": "control", "max-retries": 3, "checkout-payload": { mode: "strict", showPromo: true }, }, }); createRoot(document.getElementById("root")!).render( , ); ``` Create the client once, outside components. Creating it during render starts a new client on every render. ## Identify from your auth layer ```tsx src/components/IdentifyUser.tsx theme={null} import { useEffect } from "react"; import { useShipdClient } from "../lib/shipd-react"; import { useSession } from "../auth"; export function IdentifyUser() { const client = useShipdClient(); const session = useSession(); useEffect(() => { if (session?.user) { client.identify({ userId: session.user.id, traits: { plan: session.user.plan }, }); } else { client.reset(); } }, [client, session?.user]); return null; } ``` Render `` inside `ShipdProvider`. Every hook re-renders with the new identity. See [Identify users](/flags/identify-users). ## Read flags ```tsx src/components/CheckoutNav.tsx theme={null} import { useFlag, useReady, useVariant } from "../lib/shipd-react"; export function CheckoutNav() { const ready = useReady(); const newCheckout = useFlag("new-checkout"); const search = useVariant("search-variant"); // "control" | "semantic" | "hybrid" if (!ready) return ; return ( ); } ``` Keys are type-checked against the flag type. `useFlag("search-variant")` and `useVariant("new-checkout")` are compile errors. | Hook | Returns | Client method | | - | - | - | | `useFlag(key, context?)` | `boolean` | [`isEnabled`](/reference/sdk#isenabled) | | `useVariant(key, context?)` | Variant union | [`getVariant`](/reference/sdk#getvariant) | | `useNumber(key, context?)` | `number` | [`getNumber`](/reference/sdk#getnumber) | | `useJson(key, context?)` | JSON value | [`getJson`](/reference/sdk#getjson) | | `useReady()` | `true` once `ready()` settles | [`ready`](/reference/sdk#ready) | | `useShipdClient()` | The provided client | — | All hooks throw if they're called outside `ShipdProvider`. ## Handle the loading state Before the first evaluation response arrives, hooks return `defaults`. List the flags in `defaults` to load them in the initial request. `useReady()` is `false` until initial loading finishes or `readyTimeoutMs` elapses. Use it to show a skeleton instead of briefly rendering the default path. If a default is an acceptable first render (for example, `false` hides an unreleased feature), you can skip `useReady()`. The component re-renders when evaluated values arrive. ## Next * [Next.js](/sdks/nextjs) * [Test flags locally and in unit tests](/sdks/testing) * [Complete React example](/examples/react) * [SDK reference](/reference/sdk) # Test flags locally and in unit tests Source: https://docs.useshipd.com/sdks/testing Force flag values in unit tests with a bootstrap snapshot, run without network access, and develop against a separate environment. ## Overview This page shows how to control flag values in unit tests, how the SDK behaves when you develop without network access, and how to keep local work out of production with a `development` environment. None of these patterns need a test-only package. They use regular [TypeScript client options](/reference/sdk#createclient) or [Go options](/reference/go-sdk#new). ## Force values in unit tests In TypeScript, pass a `bootstrap` snapshot and a stub `fetch` that always answers `304 Not Modified`; the client serves that snapshot immediately. The Go helper below serves test values as defaults and uses a stub HTTP client so no request reaches the network, which is enough for application branching tests. To test Go targeting rules, pass a snapshot as `Bootstrap`, as shown [below](#test-targeting-rules). ```ts TypeScript theme={null} // test/shipd.ts import { createClient, SNAPSHOT_SCHEMA_VERSION, type FlagSnapshot } from "shipdit"; import type { FlagDefinitions } from "../src/generated/flags"; type Values = Partial>; /** Build a snapshot where every listed flag serves the given value. */ function snapshotFor(values: Values): FlagSnapshot { const flags: FlagSnapshot["flags"] = {}; for (const [key, value] of Object.entries(values)) { const type = typeof value === "boolean" ? "boolean" : typeof value === "number" ? "number" : typeof value === "string" ? "variant" : "json"; flags[key] = { key, type, enabled: true, version: 1, default: value, rules: [], fallthrough: { kind: type, value }, ...(type === "variant" ? { variants: [value as string] } : {}), } as FlagSnapshot["flags"][string]; } return { schemaVersion: SNAPSHOT_SCHEMA_VERSION, projectId: "proj_test", environmentId: "env_test", environmentKey: "test", version: 1, generatedAt: new Date(0).toISOString(), flags, }; } export function createTestClient(values: Values = {}) { return createClient({ sdkKey: "shipd_sdk_server_test", bootstrap: snapshotFor(values), refreshIntervalMs: 0, // fetch once, then stop events: false, // don't send diagnostic events fetch: async () => new Response(null, { status: 304 }), defaults: { "new-checkout": false, "search-variant": "control", "max-retries": 3, "checkout-payload": { mode: "strict", showPromo: true }, }, }); } ``` ```go Go theme={null} // testclient_test.go package checkout import ( "errors" "net/http" "testing" shipd "github.com/alasti-company/shipd-go" ) type offlineHTTPClient struct{} func (offlineHTTPClient) Do(*http.Request) (*http.Response, error) { return nil, errors.New("offline test") } func createTestClient(t *testing.T, enabled bool) *shipd.Client { t.Helper() client, err := shipd.New(shipd.Options{ SDKKey: "shipd_sdk_server_test", Defaults: map[string]any{"new-checkout": enabled}, DisablePolling: true, DisableEvents: true, HTTPClient: offlineHTTPClient{}, }) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = client.Close() }) return client } ``` Flags you don't list aren't in the snapshot, so they return their `defaults`. ```ts TypeScript theme={null} // src/checkout.ts import type { ShipdClient } from "shipdit"; import type { FlagDefinitions } from "./generated/flags"; export function pickCheckout(shipd: ShipdClient, userId: string) { return shipd.isEnabled("new-checkout", { userId }) ? "new" : "legacy"; } ``` ```go Go theme={null} // checkout.go package checkout import shipd "github.com/alasti-company/shipd-go" func pickCheckout(client *shipd.Client, userID string) string { if client.IsEnabled("new-checkout", shipd.EvaluationContext{UserID: userID}) { return "new" } return "legacy" } ``` ```ts TypeScript theme={null} // src/checkout.test.ts import { afterEach, expect, it } from "vitest"; import { createTestClient } from "../test/shipd"; import { pickCheckout } from "./checkout"; let shipd: ReturnType; afterEach(() => shipd.close()); it("uses the new checkout when the flag is on", () => { shipd = createTestClient({ "new-checkout": true }); expect(pickCheckout(shipd, "usr_8f2k19")).toBe("new"); }); it("falls back to the legacy checkout", () => { shipd = createTestClient({ "new-checkout": false }); expect(pickCheckout(shipd, "usr_8f2k19")).toBe("legacy"); }); ``` ```go Go theme={null} // checkout_test.go package checkout import "testing" func TestPickCheckout(t *testing.T) { for _, test := range []struct { enabled bool want string }{ {true, "new"}, {false, "legacy"}, } { client := createTestClient(t, test.enabled) if got := pickCheckout(client, "usr_8f2k19"); got != test.want { t.Errorf("enabled=%v: got %q, want %q", test.enabled, got, test.want) } } } ``` Passing the client into the code under test (instead of importing a module-level singleton) keeps each test independent. If your code imports the singleton from `src/lib/shipd.ts`, mock that module with your test runner (`vi.mock` or `jest.mock`) and return a test client. ### Test targeting rules To test a targeting rule itself, add `rules` to a flag in the snapshot and pass context to the evaluation. In TypeScript, pass it as `bootstrap`; the snapshot types are in `FlagSnapshot`, exported from `shipdit`. In Go, pass the snapshot JSON as `Bootstrap`: ```go targeting_test.go theme={null} package checkout import ( shipd "github.com/alasti-company/shipd-go" "testing" ) func TestTargeting(t *testing.T) { const snapshot = `{"schemaVersion":1,"projectId":"p","environmentId":"e","environmentKey":"test", "version":1,"generatedAt":"2026-10-10T00:00:00Z","flags":{"new-checkout":{"key":"new-checkout", "type":"boolean","enabled":true,"default":false,"fallthrough":{"kind":"boolean","value":false}, "rules":[{"id":"pro","conditions":[{"kind":"attribute","attribute":"plan","operator":"eq","value":"pro"}], "serve":{"kind":"boolean","value":true}}]}}}` client, err := shipd.New(shipd.Options{ SDKKey: "shipd_sdk_server_test", Bootstrap: []byte(snapshot), DisablePolling: true, DisableEvents: true, HTTPClient: offlineHTTPClient{}, }) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = client.Close() }) if !client.IsEnabled("new-checkout", shipd.EvaluationContext{Attributes: map[string]any{"plan": "pro"}}) { t.Fatal("pro targeting rule did not match") } } ``` With an offline client, `Ready` returns the fetch error immediately instead of waiting for its deadline, or `nil` when `Bootstrap` is set. ### React components Render with a test client in `ShipdProvider`. Because `bootstrap` is set, `useReady()` is `true` after the first effect. ```tsx src/components/CheckoutNav.test.tsx theme={null} import { render, screen } from "@testing-library/react"; import { afterEach, expect, it } from "vitest"; import { ShipdProvider } from "../lib/shipd-react"; import { createTestClient } from "../../test/shipd"; import { CheckoutNav } from "./CheckoutNav"; let client: ReturnType; afterEach(() => client.close()); it("links to the new checkout", async () => { client = createTestClient({ "new-checkout": true }); render( , ); const link = await screen.findByRole("link", { name: "Checkout" }); expect(link.getAttribute("href")).toBe("/checkout/new"); }); ``` ## Serve only defaults Sometimes you want a client that never contacts shipd, for example when `.env` has no SDK key. `createClient` throws if `sdkKey` is empty, so there's no key-less mode. Instead, create a client with a placeholder key and a `fetch` that always fails. Every check returns its default. ```ts TypeScript theme={null} // src/lib/shipd.ts import { createClient } from "shipdit"; import type { FlagDefinitions } from "../generated/flags"; const defaults = { "new-checkout": false, "search-variant": "control", "max-retries": 3, "checkout-payload": { mode: "strict", showPromo: true }, } as const; const sdkKey = process.env.SHIPD_SDK_KEY?.trim(); export const shipd = sdkKey ? createClient({ sdkKey, defaults, }) : createClient({ sdkKey: "local", defaults, refreshIntervalMs: 0, readyTimeoutMs: 0, events: false, onError: () => {}, // the stubbed fetch always fails fetch: async () => new Response(null, { status: 503 }), }); ``` ```go Go theme={null} // main.go package main import ( "errors" shipd "github.com/alasti-company/shipd-go" "log" "net/http" ) type offlineHTTPClient struct{} func (offlineHTTPClient) Do(*http.Request) (*http.Response, error) { return nil, errors.New("offline") } func main() { client, err := shipd.New(shipd.Options{ SDKKey: "local", Defaults: map[string]any{ "new-checkout": false, "search-variant": "control", "max-retries": 3, "checkout-payload": map[string]any{"mode": "strict", "showPromo": true}, }, DisablePolling: true, DisableEvents: true, HTTPClient: offlineHTTPClient{}, }) if err != nil { log.Fatal(err) } defer client.Close() log.Printf("checkout: %v", client.IsEnabled("new-checkout", shipd.EvaluationContext{})) } ``` The shipd dashboard uses a similar fallback so it boots from an empty `.env` with safe UI defaults when no client SDK key is configured. ## Develop without network access You don't need special configuration to work offline: * TypeScript `ready()` resolves as soon as the first fetch fails, or after `readyTimeoutMs` (5 seconds by default) if the request hangs. It never rejects. * Every check returns its default until a snapshot (server) or evaluated values (browser) load. * Browser clients keep evaluated values only in memory and start from `defaults` when offline. Server clients can read from a custom `cache` adapter or `bootstrap` snapshot. * Polling continues, so the client picks up updates when the network returns. Go `Ready(ctx)` returns a request or context error when startup fails; handle it and continue with defaults if appropriate. Go keeps snapshots in memory and does not persist them to disk. See [Local evaluation](/concepts/local-evaluation) for the full failure model. ## Use a development environment Keep local work away from production flags with a separate environment and SDK key. **1. Create the environment** In the dashboard, open your project's **Environments** page and click **Create environment**. Name it `Development` with the slug `development`. **2. Create a key for it** Select the `development` environment, go to **SDK keys**, and click **Create SDK key**. Keys are created for the active environment. **3. Point your local env at it** ```bash .env.local theme={null} SHIPD_SDK_KEY=shipd_sdk_server_… # development key ``` **4. Push your flag definitions** A management API key is bound to one environment. Run `shipd login`, approve the `development` environment in the browser, then push: ```bash theme={null} shipd login shipd push ``` You can now add rules, run rollouts, and change the **Fallthrough** in `development` without affecting production. See [Environments](/concepts/environments). ## Next * [Local evaluation](/concepts/local-evaluation) * [Sync flags with the CLI](/config-as-code/sync) * [SDK reference](/reference/sdk)