How-to › Ship an SDK

How to turn SDK features on per environment without a code change#

Ship one sdkgen build and pick its features per environment from a committed file that the constructor reads, the client logs, and a test pins in wrap order.

Audience
Platform team
Level
advanced
Topic
Compose runtime features in an SDK
Languages
TypeScript and Go
Verified

Read first: Choose the pipeline stage where an SDK behavior should run

Production wants your SDK to retry and cache. CI wants netsim failures and a debug trace, and a developer laptop wants neither. The client is built in three branches of an if, so the branch CI exercises is not the one customers run. When a CI test fails, the cause is a response cached by the test before it.

What you get

You will end up with one build, a committed file naming each environment’s features in wrap order, and a wrapper that refuses a bad profile and logs what activated. This is for you if one sdkgen client runs in several environments.

Short answer

Keep one sdkgen build and a committed file that lists, per environment, the features the constructor turns on. A small wrapper takes the profile name and refuses a feature the build lacks or a stateful feature in CI. It passes the list to the SDK’s feature option as an array and logs what the client instantiated. The array order is the wrap order, so one test pins both the set and the nesting.

You will need

Node 22 or later, Go 1.24 or later for the oapi-codegen part, and an SDK generated by sdkgen with the features you want to switch, added at generation time. Verified 2026-11-21 against Node 22.23.5, @voxgig/create-sdkgen 0.31.9, @voxgig/sdkgen 4.44.3, oapi-codegen v2.8.2 and Go 1.24.7. Read choose the pipeline stage where an SDK behavior should run first if hooks and transport wrappers are unfamiliar.

The release has no runtime feature tags. Its design note on feature tags is a proposal to match features to the targets that can take them at generation time, and it says nothing in it reaches generated code.1 No constructor option of 4.44.3 or 4.45.0 names a tag, a profile, or an environment. This page builds the named set from what the release does offer.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
Environment variables read by your own wrapperA few switches, and a platform that already sets variables per deployOne variable per feature, so the combination a host ran is recorded nowhere you can diffYou need the set and its order reviewed before it ships
LaunchDarkly flag evaluated at constructionYou already run LaunchDarkly and want an operator to change an environment’s setA LaunchDarkly connection on the construction path, a fallback value when it is unreachable, and changes outside version controlCI must be reproducible from a checkout alone
oapi-codegen with a RoundTripper chainA Go client where you own every middlewareEach feature is a transport you write and test, because the generated client carries noneYou want the same behaviors generated in several languages
sdkgen feature array from a committed profileAn sdkgen client in several environments, with features added at generation timeA wrapper you own, and an internal _features list that a test has to pinThe set must be fixed per release, not per environment
Speakeasy hooks registered at build timeA Speakeasy SDK whose behaviors must be identical for every customerHooks are for Business and Enterprise users only, and run in every environment unless they test a conditionEach environment needs a different set of behaviors

The profile file keeps an environment reproducible from a checkout, and costs you the guarantee that customers run the code path you tested. Speakeasy’s compiled hooks keep that guarantee and give up the per-environment set. Environment variables and a LaunchDarkly flag move the decision out of review, which is faster to change and harder to reconstruct after an incident.2

Voxgig maintains sdkgen, the worked path here. The last column says when each row, sdkgen’s included, is the wrong pick.

Name each environment’s features in one file

Features are added once, at generation time, and every one is off until the constructor turns it on. The profile file lists the features each environment turns on, with their options, in the order the constructor should initialize them:

{
  "production": [
    { "name": "cache", "ttl": 30000, "max": 500 },
    { "name": "retry", "retries": 2, "minDelay": 50, "maxDelay": 2000 }
  ],
  "ci": [
    { "name": "netsim", "failTimes": 1, "failStatus": 503 },
    { "name": "debug", "max": 50 }
  ],
  "laptop": []
}

The features reference says each transport feature wraps whatever is installed, so the one initialized last is outermost. Given an array, the SDK initializes in array order. Given a map, it puts test first and sorts the rest.

Build the client from the profile

makeClient checks the profile, adds active: true to every entry, and reads the instantiated features back from the client:

export function makeClient(name, { base, profiles = loadProfiles(), log = () => {} } = {}) {
  if (!Object.hasOwn(profiles, name)) throw new Error(`no profile named "${name}"`)
  const entries = profiles[name]
  checkProfile(name, entries)

  // The array form fixes the init order, so the file decides the wrap order as well as the set.
  const client = new BookshelfSDK({ base, feature: entries.map((e) => ({ ...e, active: true })) })

  // Read back what the SDK instantiated, rather than trusting the file.
  const activated = client._features.map((f) => f.name)
  const wanted = entries.map((e) => e.name)
  if (activated.join() !== wanted.join()) {
    throw new Error(`profile "${name}" asked for [${wanted}] and the client activated [${activated}]`)
  }
  log({ profile: name, activated, chain: chainOf(activated) })
  return client
}

checkProfile refuses a name the build does not carry, a repeated name, an active key, an option the feature does not read, and cache, cost, or ratelimit in the CI profile. profileFrom maps APP_ENV to a profile, treats an unset value as laptop, and refuses an unknown one. The demo builds the one SDK under each profile and makes two list calls against a local stand-in:

node demo.mjs
production activated [cache, retry]  chain retry > cache > fetch
  list 1: ok, 1 book   list 2: ok, 1 book   requests that reached the API: 1
  _cache hit 1, miss 1, bypass 0
ci         activated [netsim, debug]  chain netsim > fetch
  list 1: request_status 503   list 2: ok, 1 book   requests that reached the API: 1
  _netsim calls 2
  _debug book.list 503, book.list 200
laptop     activated []  chain fetch
  list 1: ok, 1 book   list 2: ok, 1 book   requests that reached the API: 2

The first line of each block is the log the wrapper writes at construction. debug hooks the pipeline rather than the transport, so it is activated but absent from the chain.

Prove the wrap order with one failed attempt

The chain is computed, so a test checks it against behavior. The stand-in answers its first request with 503. A cache inside the retry sees both attempts, and a cache outside it sees one call:

  // File order cache, retry: retry is outermost, so the cache sees the 503 attempt and the 200.
  assert.deepEqual(await run(['cache', 'retry']), {
    chain: ['retry', 'cache', 'fetch'], cache: { hit: 0, miss: 1, bypass: 1 }, requests: 2,
  })
  // Reversed: the cache is outermost and sees one call, whatever retry did beneath it.
  assert.deepEqual(await run(['retry', 'cache']), {
    chain: ['cache', 'retry', 'fetch'], cache: { hit: 0, miss: 1, bypass: 0 }, requests: 2,
  })

bypass counts a cacheable request whose response was not stored. Only the inner cache saw the 503, so swapping two lines of features.json flips that counter.

Check it worked

Run the suite:

node --test profiles.test.mjs | tail -8
# tests 13
# suites 0
# pass 13
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 423.629498

Two tests matter most. One constructs each committed profile and asserts the activated list and the logged chain. Another runs probe.mjs on the committed build and compares it with records/sdkgen-4.44.3.txt, which record.sh also wrote for 4.45.0, with the same lines.

Do the same in Speakeasy and oapi-codegen

Speakeasy registers hooks in initHooks, in src/hooks/registration.ts for TypeScript, and its hooks page says the file is generated once and then yours.3 The generated hooks class calls it from its constructor with the hook registry alone, so the hooks are compiled in and fixed per release. What varies per construction is the SDK options: the generated SDKOptions in Mistral’s Speakeasy client carries retryConfig, timeoutMs and debugLogger, and Speakeasy documents retryConfig: { strategy: "none" } for turning retries off globally. A Speakeasy profile maps to those options, and a hook that must stay quiet in CI reads the configuration through its hook context. Speakeasy’s CLI starts with speakeasy auth login, so none of this was run.

oapi-codegen generates no features to switch. Its client takes any HttpRequestDoer through WithHTTPClient, so oapi/profiles.go reads the same file and wraps an http.RoundTripper per entry, the last one outermost:

	rt := base
	chain := []string{"transport"}
	names := []string{}
	for _, e := range entries {
		fname := e["name"].(string)
		rt = wrappers[fname](rt, e, rec)
		chain = append([]string{fname}, chain...)
		names = append(names, fname)
	}
cd oapi && go run . ../features.json
production activated [cache, retry]  chain retry > cache > transport
  list 1: ok, 1 book   list 2: ok, 1 book   requests that reached the API: 1
ci         activated [netsim, debug]  chain debug > netsim > transport
  list 1: status 503   list 2: ok, 1 book   requests that reached the API: 1
  debug GET /v1/books 503, GET /v1/books 200
laptop     activated []  chain transport
  list 1: ok, 1 book   list 2: ok, 1 book   requests that reached the API: 2

oapi/profiles_test.go checks the wrap order the same way as the TypeScript test. In Go, debug is a transport too, so it sits in the chain and records each attempt.

When it goes wrong

The CI suite debugs a stale response. Someone added cache to the CI profile, and the cache does not drop an entry when the client writes. Keep cache out of CI, which checkProfile enforces:

node pitfall.mjs
straight into the constructor
  list, create "Emma", list: the client sees 1 then 1, the API holds 2
  _cache hit 1, miss 1
through makeClient
  profile "ci" names "cache", which keeps state between calls

Construction fails with TypeError: fc is not a constructor. A profile names a feature the build does not carry, often a typo, and the SDK’s error does not say which. checkProfile names it and lists what the build has.

A feature in the file never runs. An entry with active: false, or with no active key passed straight to the SDK, is skipped without a message. The wrapper adds active itself and refuses the key in the file.

A setting in the file has no effect. The SDK accepts an option its feature does not read, such as retires for retries, without a message. checkProfile refuses it and lists the options the feature reads.

When not to do this

Do not switch features per environment when the risk lives in the switch. The code path a customer hits runs only in production, so a defect that needs cache and retry together never reaches CI. Add a staging profile identical to production, and run a suite against it.

Do not use the profile file for a set that must ship fixed in every release. Speakeasy’s hooks, compiled in at build time, fit that better than an sdkgen profile does.

Do not build a feature system for a Go client that needs one or two behaviors. With oapi-codegen, an http.Client with a timeout and one RoundTripper is shorter than any profile file.

Do not let APP_ENV default to production. An unset variable should get the profile with the least in it.

Last verified

Verified 2026-11-21 against Node 22.23.5, @voxgig/create-sdkgen 0.31.9, @voxgig/sdkgen 4.44.3, @voxgig/apidef 8.32.4, oapi-codegen v2.8.2, github.com/oapi-codegen/runtime v1.8.0 and Go 1.24.7, with the Go part also run on Go 1.25.0. Every output block is what the command preceding it printed. The SDK and the Go client were generated once by generate.sh and committed; record.sh repeated the probe after installing @voxgig/sdkgen 4.45.0. Speakeasy and LaunchDarkly were not run, and what this page says of them comes from their documentation.

Footnotes

  1. The design note is marked as a proposal dated 2026-08-17. It opens by quoting the whole of a line from the project’s notes: features should have tags so that only compatible features are applied to a target. A feature declares what it needs and a target what it provides. Its non-goals say the tags describe what the generator can do for a target, not what the resulting SDK can do at runtime, and that nothing reaches generated code. ↩︎ Back to text

  2. The Twelve-Factor App page on config argues against the arrangement on this page. It says that grouping config into named environments such as development, test and production does not scale cleanly, and gives joes-staging as an example of the names that follow. It also leaves out of config how code modules are connected, which it says does not vary between deploys and is best done in the code. ↩︎ Back to text

  3. Mistral’s TypeScript client, generated by Speakeasy, carries the same promise in the header of its own registration file: generated once on the first generation, and then free to be modified. A comment inside initHooks adds that hooks are registered per SDK instance and are valid for the lifetime of the instance. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.