Your SDK takes the API key in its constructor, the base URL through a setter, and the timeout on
every call. A caller who forgets the timeout on one call gets the default in production. The
constructor also reads BILLING_APIKEY from the environment, so a test that sets the variable
changes what the next test’s client sends.
What you get
You will end up with one constructor call that carries the credential, the base URL, the HTTP client, and each optional behavior, plus a test of what it resolved. This is for you if you decide what an SDK’s constructor accepts.
Short answer
Give the client one options object and resolve it in the constructor: the credential, the base
URL, the HTTP client, and each optional behavior by name. A client generated by sdkgen takes
apikey, base, system.fetch, and a feature map whose entries stay off until active is
true. Read environment variables in a separate helper that returns plain options. Then construct
the client with no network and assert on client.options().
You will need
Node 22 or later, Python 3 for the Python target, and an OpenAPI 3 document whose
servers entry and security scheme say
where the API is and how it authenticates. Verified 2026-11-19 against Node 22.23.5, Python
3.13.18, @voxgig/create-sdkgen 0.31.9, @voxgig/sdkgen 4.44.3, orval 8.48.0,
openapi-typescript 7.13.0, and openapi-fetch 0.17.0. The document here, api.json, is a
Billing API: three operations on invoices, one server URL, and bearer authentication. The clients
were generated once by generate.sh and are committed under generated/, so after npm ci every
command runs offline against an in-memory stand-in. Entity-shaped clients are covered in
shape an SDK around entities instead of endpoint wrappers.
Approaches compared
| Approach | When it fits | What it costs you | When to pick something else |
|---|---|---|---|
| AWS SDK for JavaScript v3 credential providers | Credentials come from roles, shared files, or single sign-on, through a provider function passed as credentials | A default chain that searches the environment and shared files when you pass nothing, so the machine decides | One static key, where a chain adds sources nobody asked for |
| Octokit authentication strategies | One API with several credential types, each handled by its own authStrategy | An auth option whose shape depends on the strategy beside it, so the two are read as a pair | A single token, which the default strategy already takes as a string |
openapi-typescript and openapi-fetch | A TypeScript app that wants options and paths checked by the compiler, and defaults one call can replace | Types only, so the document’s server URL and security scheme are dropped and createClient must be handed both | Several languages, or retries you do not want to write as middleware |
| orval fetch factory | One TypeScript app that wants typed functions, a typed factory, and no runtime library | The factory receives a fetch and nothing else, so the credential and any retry policy are code you write | Several languages, or consumers who expect a configured client object |
| sdkgen constructor options | One option map shared by the generated TypeScript and Python clients, with each generated behavior off until named | Options typed any and checked when the constructor runs, and no per-call override on entity calls | Callers need compile-time checking of option names, or another retry policy on one call |
| Stripe constructor options | You hand-write the SDK, and the API has one secret key and a short list of transport settings | Defaults that act without being named: one network retry, and telemetry switched on | The API takes more than one kind of credential |
Voxgig maintains sdkgen. It is one of six options here, not the recommendation.
The six differ in what the constructor does when it is given nothing. Stripe’s defaults retry once
and send telemetry, and the AWS chain goes looking for credentials on the machine.1 sdkgen,
orval, and openapi-fetch add no retry or telemetry that a caller did not name, which makes the
call longer and puts the behavior in one readable place. The two TypeScript generators also leave
the credential to you, where sdkgen reads the scheme from the document.
Generate the client and count what its constructor accepts
sdkgen writes the constructor, so the design work is choosing what is generated into it.
generate.sh scaffolds a project from api.json with two targets, adds two features, and
generates.
npx --yes @voxgig/create-sdkgen@0.31.9 billing --def api.json --target ts --target py
(cd billing-sdk/.sdk && npx voxgig-sdkgen feature add retry,timeout)
(cd billing-sdk/.sdk && npm run generate)
The package bundles 20 feature models.2 feature add copies the two named ones into the
project beside test, which the scaffold had already added, and a feature that was never added is
absent from the generated client. demo.mjs builds
every client through one function.
export function makeClient(api, feature) {
return new BillingSDK({
apikey: 'sk-test-1',
base: 'https://eu.api.example.com/v1',
system: { fetch: api.fetch },
...(feature ? { feature } : {}),
})
}
Four inputs arrive in one object: the credential, a base URL that replaces the document’s
servers entry, the HTTP client as system.fetch, and a feature map. api.fetch is the
stand-in from standin.mjs, a fetch function that answers as the Billing API would and records
what it received.
node demo.mjs
constructed: 0 requests sent
base https://eu.api.example.com/v1
auth authorization: Bearer <apikey>
apikey set, 9 characters
fetch supplied by the caller
features retry on, test off, timeout off
prepared: GET https://eu.api.example.com/v1/invoices/inv_1, 0 requests sent
the constructor accepts 16 option keys
allow, apikey, auth, base, clean, entity, extend, feature, headers, prefix, secret, server, suffix, system, test, utility
its generated README documents 6
apikey, base, prefix, suffix, feature, extend
three calls, no option repeated
GET /v1/invoices key sent
POST /v1/invoices key sent
GET /v1/invoices/inv_2 key sent
the API answers 503 twice, then 200
no feature block rejected, request_status 503 after 1 request
retry active 1 invoice listed after 3 requests
The first seven lines cost no request. client.options() returns a deep copy of what the
constructor resolved, and client.prepare() builds a request without sending it. The Bearer
prefix was never passed: the generator read it from the document’s security scheme. options()
returns the credential too, so the demo prints only its length.
The three calls pass a match or a record and nothing else. The control object an entity call
takes carries throw, err, explain, and signal. A call can be cancelled through signal, but
no option the constructor resolved changes for one call.
The last block shows what off means. retry and timeout were generated in, and a client built
with no feature block made one request and rejected with the 503. Naming retry with
active: true made three.
The middle block is the trade-off in numbers. The constructor validates against 16 keys, and the
README that sdkgen wrote beside the SDK documents six. system, which carries the HTTP client, is
described in the
feature catalogue and not
in that table. A short documented list is easier to learn, and a caller finds the rest by reading
Schema.js.
Keep environment reads out of the constructor
The generated constructor reads no environment variable, and its README passes
process.env.BILLING_APIKEY in by hand. Keep it that way with one helper that turns an
environment object into plain options.
export function optionsFromEnv(env) {
const options = {}
for (const [name, option] of NAMES) {
const value = Object.hasOwn(env, name) ? env[name] : undefined
if (typeof value === 'string' && value !== '') options[option] = value
}
// The generated constructor accepts a missing key and sends no credential,
// so the first sign of trouble would be a 401. Fail here, with the name.
if (!options.apikey) throw new Error('BILLING_APIKEY is not set')
return options
}
optionsFromEnv reads the object it is handed. The entry point of a program calls it with
process.env, and a test calls it with an object of its own.
process.env belongs to the process, not to a
test, so a test that writes to it has changed the input of the test that runs next.3
node pitfall.mjs
a constructor that reads process.env
defaults pass, staging pass
staging pass, defaults FAIL, base was https://staging.api.example.com/v1
plain values, with optionsFromEnv(env) given its own object
defaults pass, staging pass
staging pass, defaults pass
Each line is the same two tests in a different order. The staging test sets BILLING_BASE and
never restores it, so a constructor that reads the environment carries the value into the next
test. Node’s test runner
runs each file in its own process
by default, so the leak stays inside one file and appears when tests are reordered or run alone.
Resolve the same options in the Python target
The Python client came from the same model and takes the same keys in a dict.
client = BillingSDK({
"apikey": "sk-test-1",
"base": "https://eu.api.example.com/v1",
"system": {"fetch": recording_fetch},
"feature": {"retry": {"active": True, "retries": 2, "minDelay": 1}},
})
python3 demo.py
constructed: 0 requests sent
base https://eu.api.example.com/v1
auth authorization: Bearer <apikey>
apikey set, 9 characters
fetch supplied by the caller
features retry on, test off, timeout off
prepared: GET https://eu.api.example.com/v1/invoices/inv_1, 0 requests sent
The seven lines match the first seven from demo.mjs, and a test compares them. Two things
differ: the options come back from options_map(), and the Python fetch returns a response and
an error as a pair.
Give the orval factory one configured fetch
orval generates functions, so it has no constructor to design. Its nearest equivalent is
httpClientInjection, which wraps the operations in a factory that receives a fetch once.
export default {
billing: {
input: './api.json',
output: {
target: './generated/orval/billing.ts',
client: 'fetch',
override: {
fetch: { httpClientInjection: 'factory' },
},
},
},
}
orval wrote one file, and the factory is this line of it:
export const getBilling = (fetchFn: typeof globalThis.fetch = fetch) => {
The bearer scheme in the document produced no credential code. The URL helpers return paths such
as /invoices unless output.baseUrl fixes a base
at generation. So the fetch you pass carries the rest, and configuredFetch in orval-demo.mjs
is seven lines that prepend the base URL and set the header. Every generated function also takes a
standard RequestInit as its last argument, so a per-call override is an ordinary fetch option.
node orval-demo.mjs
getBilling(fetch) returned: listInvoices, getListInvoicesUrl, createInvoice, getCreateInvoiceUrl, getInvoice, getGetInvoiceUrl
GET https://eu.api.example.com/v1/invoices key sent status 200
POST https://eu.api.example.com/v1/invoices key sent status 201
Set the defaults once with openapi-fetch
openapi-typescript generates
types with no runtime. From api.json it wrote one file,
which carries neither the server URL nor the security scheme.
export interface paths {
"/invoices": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get: operations["listInvoices"];
The client is openapi-fetch. The options of its createClient become the defaults of every
call: baseUrl, fetch, and any fetch option, headers among them.
export function makeBilling(api) {
return createClient({
baseUrl: 'https://eu.api.example.com/v1',
headers: { authorization: 'Bearer sk-test-1' },
fetch: api.fetch,
})
}
node openapi-fetch-demo.mjs
createClient(options) returned: request, GET, PUT, POST, DELETE, OPTIONS, HEAD, PATCH, TRACE, use, eject
GET https://eu.api.example.com/v1/invoices key sent status 200
POST https://eu.api.example.com/v1/invoices key sent status 201
GET https://eu.api.example.com/v1/invoices another key status 401
The third call passed its own authorization header, which replaced the default for that call
alone. In TypeScript the call is createClient<paths>(...), and typecheck.mjs hands tsc a
correct caller and one with two slips.
node typecheck.mjs
tsc typed.ts: no errors
tsc typo.ts: exit 2
typo.ts(7,3): error TS2561: Object literal may only specify known properties, but 'baseURL' does not exist in type 'ClientOptions'. Did you mean to write 'baseUrl'?
typo.ts(10,36): error TS2554: Expected 2 arguments, but got 1.
The first error is a misspelled option, caught before the program runs. The second is the path
/invoice, which is not in the document, and its message counts arguments instead of naming the
path.
Check it worked
node --test constructor.test.mjs
1..17
# tests 17
# suites 0
# pass 17
# fail 0
# cancelled 0
# skipped 0
# todo 0
# pass 17 covers each preceding claim. One test replaces the platform’s fetch with a function
that throws, then builds a client, reads its options, and prepares a request. Another sets
BILLING_APIKEY and BILLING_BASE in the real environment and expects a client built with no
options to resolve an empty key and the document’s URL.
When it goes wrong
The second half of pitfall.mjs hands the generated constructor four sets of options.
node pitfall.mjs
what the generated constructor checks
{ apiKey: 'sk-test-1' }
throws: Unexpected keys at field <root>: apiKey
{ apikey: 42 }
throws: Expected field apikey to be string, but found integer: 42.
{ feature: { cache: { active: true } } }
throws: fc is not a constructor
{ system: { fetch } }, and no apikey
accepted
first call rejected, request_status 401, authorization header: none
Construction throws Unexpected keys at field <root>: apiKey. The option is spelled apikey, and
the constructor refuses any name the generated schema does not list. Fix the spelling. The refusal
is worth having, because an ignored key would send every request without a credential.
Construction throws fc is not a constructor. The options activate a feature, here cache, that
was never added to the project, and the message does not name it. Run
npx voxgig-sdkgen feature add cache in .sdk and generate again.
The first call answers 401. The constructor accepts a missing apikey and sends no
authorization header. optionsFromEnv throws BILLING_APIKEY is not set before the client
exists: the earlier failure, and the one that names its cause.
When not to do this
Do not put a per-call decision in the constructor. A timeout that differs by endpoint is not
configuration of the client. sdkgen takes one call’s deadline as an AbortSignal.timeout() in the
control object, which carries no retry count or credential. orval is the better choice when calls
differ in more than a deadline, because every function it generates takes a RequestInit.
Do not choose sdkgen for its constructor when your consumers write TypeScript only and want the
compiler to check option names. Its constructor takes any and refuses a misspelled key when it
runs. openapi-fetch is the better choice there, because tsc rejects baseURL before the
program starts.
Do not read the environment in the constructor to save callers a line. AWS’s
fromEnv()
is the same decision as optionsFromEnv: a provider that the caller passes in.
Do not hand client.options() to a logger. It returns the credential as given.
Related how-tos
Last verified
Verified 2026-11-19 against Node 22.23.5, Python 3.13.18, @voxgig/create-sdkgen 0.31.9,
@voxgig/sdkgen 4.44.3, orval 8.48.0, openapi-typescript 7.13.0, openapi-fetch 0.17.0, and
TypeScript 5.9.3. Every output block is what the command preceding it printed. sdkgen, orval, and
openapi-typescript ran once, with the network, through generate.sh; their output is committed
under generated/, and the commands here run against it. The AWS, Octokit, and Stripe
constructors are described from their documentation and were not run.
Footnotes
-
The AWS developer guide warns, in its second paragraph, against relying on more than one source of credentials. You can, it says, change the permissions under which your code runs without realizing the change has happened. Its next paragraph introduces the default chain, which checks one source after another until one of them answers. ↩︎ Back to text
-
The feature catalogue gives a lower total in the prose of its second paragraph than the table under it, which lists twenty. The package agrees with the table: version 4.44.3 carries twenty model files. ↩︎ Back to text
-
The Twelve-Factor App made the environment the place for config: an app stores config in environment variables, which it calls granular controls, each fully orthogonal to the others. The page was written by Adam Wiggins and last updated in 2017. It settles where config is stored and leaves open which line of a program reads it. ↩︎ Back to text