# How to inject a per-request credential into a generated SDK

> Set a credential that differs per tenant or per call from a hook kept outside the generated tree, look it up once per logical call, and prove that a retry reuses it.

Source: https://voxgig.com/howto/per-request-credential-hook-in-a-generated-sdk

- Audience: api-consumer
- Level: advanced
- Languages: typescript
- Verified: 2026-11-19
- Published: 2026-11-19

## Short answer

Resolve the credential in a hook that runs once per logical call, and keep the hook outside the generated tree. With sdkgen, write a custom feature that implements `PreRequest`, add it with `voxgig-sdkgen feature add`, and pass the tenant through the entity options. The hook sets `Authorization` on the request spec, so a retried attempt reuses the value. A wrapper around the client's `fetch` runs inside the retry loop and looks the credential up on every attempt.

---
## You will need

Node 22 or later, an OpenAPI 3 document that declares a bearer scheme, and a source of per-tenant
credentials. Verified 2026-11-19 against Node 22.23.5, `@voxgig/create-sdkgen` 0.31.9,
`@voxgig/sdkgen` 4.44.3, Swagger Codegen 3.0.85, `openapi-typescript` 7.13.0, and `openapi-fetch`
0.17.0. The document here, `api.json`, is a Desk API: three operations on tickets, where the
bearer token decides whose tickets a request sees. A bearer token travels in the `Authorization`
header, as [RFC 6750](https://www.rfc-editor.org/rfc/rfc6750.html#section-2.1) defines.[^1] The
clients were generated once by `generate.sh` and are committed under `generated/`, so after
`npm ci` every command runs offline against a stand-in on the loopback interface.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [OpenAPI Generator `typescript-fetch` middleware](https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache) | A `typescript-fetch` client, where a `pre` function sees each request before it is sent | A middleware array handed to `Configuration` at run time, by every service that builds a client | You also ship clients in other languages and want one definition of the hook |
| [`openapi-typescript` and `openapi-fetch` middleware](https://openapi-ts.dev/openapi-fetch/middleware-auth) | A TypeScript caller that wants an `onRequest` it can register once or hand to a single call | The documented example keeps the token in module state, which its own page warns against on a server | You need the same hook in a language other than TypeScript |
| [sdkgen custom feature at `PreRequest`](https://github.com/voxgig/sdkgen/blob/main/docs/how-to/add-a-feature.md) | An sdkgen project, where the hook should be generated into the client and run once per call | A model file and a source file per target language, written and tested by you, and `direct()` calls skip it | One language and one service, where a middleware is a dozen lines |
| [Speakeasy SDK hooks](https://www.speakeasy.com/docs/sdks/customize/code/sdk-hooks) | You own a Speakeasy SDK and can add a `beforeRequest` hook under `src/hooks` | Hooks are limited to Business and Enterprise plans and live in the SDK repository, out of a consumer's reach | You consume the SDK, where its `security` option takes an async callback instead |
| [Swagger Codegen `fetch` argument](https://swagger.io/docs/open-source-tools/swagger-codegen/codegen-v3/generators/) | A `typescript-fetch` client from Swagger Codegen, whose API classes take the `fetch` they call as an argument | No hook, and no code for an `http` `bearer` scheme, so the wrapper and its place among retries are yours | You would rather change what is generated, which its documentation does with templates and `-t` |

Voxgig maintains sdkgen. It is one of five options here, not the recommendation.

The five put the credential logic in different places. sdkgen's feature lives under `.sdk/` and
is generated into the client, at the price of a file per language. Speakeasy's hook lives in the
SDK repository, so its consumers use the
[security callback](https://www.speakeasy.com/docs/sdks/customize/authentication/security-callbacks)
instead. The other three take a function at run time, when the client is built or, for `openapi-fetch`,
on one call. That needs no generation step and is repeated by every service that builds a client.

## Write the lookup as a feature at PreRequest

An sdkgen feature is a model file and one source file per target, laid out as the
[add-a-feature guide](https://github.com/voxgig/sdkgen/blob/main/docs/how-to/add-a-feature.md)
describes. The shipped `secrets` feature resolves one credential per client through a provider
chain, so a credential that changes with the tenant needs a feature of its own. The model names the
one hook the feature implements and marks it awaited, because the lookup is asynchronous.

```aontu title="credential-feature/.sdk/model/feature/credential.aontu"
main: kit: feature: credential: {

  name: key()
  title: "Per-call credential"
  description: "Resolve the credential for each operation call and set it on the request, once per call"
  version: '0.0.1'
  active: true
  transport: 'none'

  config: {
    # Opt-in: enable per SDK via options.feature.credential.active = true
    options: {
      active: false
      header: 'authorization'
      prefix: 'Bearer'
    }
  }

  # One hook, awaited: the lookup may be a call to a vault or a token service.
  hook: {
    PreRequest: { active: true, await: true }
  }
}
```

The source implements that stage. The
[feature catalogue](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md) says a
hook runs per operation and not per HTTP attempt, and by `PreRequest` the spec is built, headers
included.

```ts title="credential-feature/.sdk/tm/ts/src/feature/credential/CredentialFeature.ts"
async PreRequest(this: any, ctx: any) {
  const spec = ctx.spec
  const resolve = this._options.resolve
  if (null == spec || 'function' !== typeof resolve) {
    return
  }

  // The entity options are the per-call channel: client.Ticket({ tenant }).
  const call = {
    tenant: (ctx.entopts || {}).tenant,
    entity: ctx.op && ctx.op.entity,
    op: ctx.op && ctx.op.name,
  }

  const credential = await resolve(call)

  // Fail closed. A call that goes out under some other tenant's credential
  // is worse than a call that never leaves.
  if ('string' !== typeof credential || '' === credential) {
    throw ctx.error('credential_missing',
      'no credential for tenant ' + JSON.stringify(call.tenant) +
      ' (' + call.entity + '.' + call.op + ')')
  }

  // Everything that leaves the pipeline is cleaned. Registering the value
  // puts a mask in its place in an error or a log record.
  ctx.utility.cleanAdd(ctx, credential)

  // init() receives the caller's options alone, so the defaults the model
  // file declares are repeated here, as the shipped features repeat theirs.
  const header = String(this._options.header || 'authorization').toLowerCase()
  const prefix = null == this._options.prefix ? 'Bearer' : this._options.prefix
  spec.headers = spec.headers || {}
  spec.headers[header] = prefix ? prefix + ' ' + credential : credential
```

Three choices in that method matter. The tenant arrives in the entity options, so it is an
argument of the call and not state on the client. A lookup that returns nothing stops the call.
The resolved value is registered with the SDK's
[secret redaction](https://github.com/voxgig/sdkgen/blob/main/docs/explanation/secret-redaction.md),
so an error raised later carries a mask.

## Add the feature by path and regenerate

`feature add` takes a bare name for a shipped feature, or a path whose last element names the
feature and whose rest locates its `.sdk` folder.

```bash title="generate.sh"
npx --yes @voxgig/create-sdkgen@0.31.9 desk --def api.json --target ts
(cd desk-sdk/.sdk && npx voxgig-sdkgen feature add retry)
(cd desk-sdk/.sdk && npx voxgig-sdkgen feature add ../../credential-feature/credential)
(cd desk-sdk/.sdk && npm run generate)
```

The add copied the model and the source into the project's `.sdk/` folder, and generation wired
the class in beside the shipped features. `credential-feature/` stays the source of truth,
outside the scaffold and outside the generated `ts/` tree.

```js title="generated/ts/Config.js"
const FEATURE_CLASS = {
    credential: CredentialFeature_1.CredentialFeature,
    retry: RetryFeature_1.RetryFeature,
    test: TestFeature_1.TestFeature,
};
```

## Switch it on and name the tenant on each call

The feature is off until the constructor activates it. `resolve` is the caller's function, and
`vault` stands in for wherever the tokens live.

```js title="sdk.mjs"
export function makeClient({ base, vault }) {
  return new DeskSDK({
    base,
    feature: {
      credential: { active: true, resolve: ({ tenant }) => vault.get(tenant) },
      retry: RETRY,
    },
  })
}
```

`demo.mjs` drives one client for two tenants with `client.Ticket({ tenant: 'acme' }).list()`.
Each line is a request as the stand-in server recorded it, and the tenant shown is the one the
server derived from the token.

```bash
node demo.mjs
```

```text output
two tenants through one client
  acme    GET  /v1/tickets  key of acme    200
  globex  GET  /v1/tickets  key of globex  200
  globex  POST /v1/tickets  key of globex  201
  acme sees t1, t2; globex sees t3
  credential lookups: 3, one per call
one call that the API answers 503, then 200
  acme    GET  /v1/tickets  key of acme    503
  acme    GET  /v1/tickets  key of acme    200
  credential lookups for that call: 1
a call that names no tenant
  rejected, credential_missing, 0 requests sent
```

The middle block is the forced retry. The `retry` feature wraps the transport, so it sent the
request twice, and both attempts carried the value the hook set once.

## Pass Swagger Codegen a fetch that carries the credential

Swagger Codegen's `typescript-fetch` client has no hook. For the `http` `bearer` scheme in
`api.json` it generated only a comment, `// authentication bearerAuth required`.[^2] Two seams
need no edit to `api.ts`: the `fetch` an API object is constructed with, and the `options`
argument of every method.

```ts title="generated/swagger-codegen/api.ts"
export class BaseAPI {
    protected configuration: Configuration;

    constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected fetch: FetchAPI = isomorphicFetch) {
```

```js title="swagger-demo.mjs"
export function credentialFetch(resolve) {
  return async (url, init = {}) => {
    const headers = { ...init.headers, authorization: `Bearer ${await resolve()}` }
    return fetch(url, { ...init, headers })
  }
}

// One API object per tenant: the object is three fields, so this is cheap.
export function apiFor(tenant, { base, vault }) {
  return new DefaultApi(undefined, base, credentialFetch(() => vault.get(tenant)))
}
```

```bash
node swagger-demo.mjs
```

```text output
a fetch that carries the credential, one API object per tenant
  acme    GET  /v1/tickets  key of acme    200
  globex  GET  /v1/tickets  key of globex  200
the header passed in the options argument of one call
  acme    GET  /v1/tickets  key of acme    200
Configuration({ accessToken }), which api.ts never reads for this scheme
  acme    GET  /v1/tickets  no valid key   401, authorization header: none
one call answered 503 and then 200, through a retrying fetch
  credential outside the retry  2 attempts, 1 lookup
  credential inside the retry   2 attempts, 2 lookups
```

The third block is a trap: `Configuration` declares an `accessToken` field, and setting it sent
no header. The last block is the cost of a seam that is only a function. The client has no retry
either, so a retrying `fetch` is a second wrapper, and the order of the two decides whether a
retry repeats the lookup.

## Hand `openapi-fetch` a middleware for one call

`openapi-typescript` generated types alone, so the hook belongs to its client, `openapi-fetch`. A
middleware object's `onRequest` receives the `Request` before it is sent. `client.use()` registers
one for every call, and the `middleware` option hands one to a single call.

```js title="openapi-fetch-demo.mjs"
export function credentialFor(tenant, vault) {
  return {
    async onRequest({ request }) {
      const credential = await vault.get(tenant)
      if (typeof credential !== 'string' || credential === '') {
        throw new Error(`no credential for tenant ${JSON.stringify(tenant)}`)
      }
      request.headers.set('authorization', `Bearer ${credential}`)
      return request
    },
  }
}
```

```bash
node openapi-fetch-demo.mjs
```

```text output
one client, a middleware handed to each call
  acme    GET  /v1/tickets  key of acme    200
  globex  GET  /v1/tickets  key of globex  200
  acme sees t1, t2; globex sees t3
a call with no middleware
  nobody  GET  /v1/tickets  no valid key   401, error: {"error":"unauthorized"}
```

The package has no retry of its own, so `onRequest` runs once per call. Its documentation's
example keeps one token in module state and says to avoid that in server applications, which is
where a multi-tenant caller runs.

## Check it worked

```bash
node --test credential.test.mjs
```

```text output
1..16
# tests 16
# suites 0
# pass 16
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

`# pass 16` includes twelve calls for two tenants at once, each of which must see its own
tickets. Another test resolves a revoked key under a header name no redaction list knows, and
expects the error to carry `[redacted]` where the wire carried the key.

## When it goes wrong

```bash
node pitfall.mjs
```

```text output
one call for acme, answered 503 and then 200
  credential feature at PreRequest   2 attempts, 1 lookup, 2 tickets
  wrapper around the client's fetch  2 attempts, 2 lookups, 2 tickets
client.direct() with the credential feature active
  status 401, authorization header: none
```

Every retry repeats the lookup. The credential code wraps the `fetch` handed to the client as
`system.fetch`, which sits inside the retry feature and runs once per attempt. Move the lookup to
`PreRequest`, where it runs once per call.

A `direct()` call answers 401. `direct()` builds and sends a request without the pipeline, so no
hook runs, and with no `apikey` set it deletes an `authorization` header passed in `headers`.
Resolve the tenant's key first and make the call from a client constructed with it as `apikey`.

The header arrives without `Bearer`. The model file declares `prefix: 'Bearer'`, but `init`
receives only what the caller passed, so the source has to repeat each default.

Every generate run warns that the feature's copy is stale. The model carried a `base` key copied
from a shipped feature. Leave that key out of a feature you add by path.

## When not to do this

Do not use a `PreRequest` hook to renew a token that can expire between attempts. The hook runs
once per call, so every retry carries the token resolved before the first attempt, even an expired one. Renewal belongs at the
transport seam, and selection of a tenant's credential belongs here.

Do not write an sdkgen feature for one service in one language. `openapi-fetch` is the better
choice there: its per-call middleware is a dozen lines and needs no generation step.

Do not move to sdkgen for this hook when Swagger Codegen already generates your clients. Its
seam is a plain `fetch`, which is the better choice when one wrapper must also serve clients that
no generator made.

Do not fall back to a default credential when a call names no tenant. A request sent under the
wrong tenant's key succeeds, and it reads or writes another customer's data.

## Related how-tos

- [Run the client credentials flow inside a generated SDK](/howto/client-credentials-inside-a-generated-sdk)

- [Refresh an access token once under concurrent requests](/howto/refresh-a-token-once-under-concurrent-requests)

- [Choose the pipeline stage where an SDK behavior should run](/howto/map-a-behaviour-to-a-pipeline-stage)

- [Wrap an SDK transport in a middleware chain](/howto/wrap-an-sdk-transport-with-middleware)

- [Keep test and live API keys from crossing environments](/howto/keep-test-and-live-keys-apart)

## Last verified

Verified 2026-11-19 against Node 22.23.5, `@voxgig/create-sdkgen` 0.31.9, `@voxgig/sdkgen` 4.44.3,
Swagger Codegen 3.0.85, `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, Swagger Codegen, 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 API is the stand-in in
`server.mjs`. OpenAPI Generator and Speakeasy were not run: OpenAPI Generator's row comes from
its `typescript-fetch` runtime template, and Speakeasy's from its documentation.

[^1]: [RFC 6750](https://www.rfc-editor.org/rfc/rfc6750.html#section-2.3), published in October
2012, defines three ways to send a bearer token. Of the third, the query string, it says the
method is included to document current use and that its use is not recommended. The header is the
only one of the three that a resource server must support.

[^2]: The [template](https://github.com/swagger-api/swagger-codegen-generators/blob/master/src/main/resources/handlebars/typescript-fetch/api.mustache)
behind that comment has a branch for API keys, one for basic authentication, and one for OAuth,
each of which writes the credential into the request. A scheme that is none of the three gets the
comment line that precedes them, and the generated `Configuration` keeps its `accessToken` field
for the OAuth branch to read.