# How to add a custom feature that survives SDK regeneration

> Declare a behavior as an sdkgen feature with source per language, keep it opt-in with an injectable clock, and prove a second generate changes nothing.

Source: https://voxgig.com/howto/add-a-custom-feature-to-a-generated-sdk

- Audience: library-maintainer
- Level: advanced
- Languages: typescript, go, python
- Verified: 2026-11-20
- Published: 2026-11-20

## Short answer

In an sdkgen project, declare the feature in `.sdk/model/feature/<name>.aontu` with its options and the pipeline stage it hooks, write its source once per target under `.sdk/tm/<target>/`, run `voxgig-sdkgen feature add <name>`, and generate. Keep `active: false` so callers opt in, take the clock as an option, and test that an activated client sends the header.

---
## You will need

Node 22 or later and an sdkgen project you can regenerate; this page scaffolds one from a
five-operation Bookshelf document with TypeScript, Go, and Python targets. Go and Python are
needed only to run those targets. The sample in `code/` runs offline against committed output,
and `generate.sh` records how that output was made.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Go RoundTripper](https://pkg.go.dev/net/http#RoundTripper) | One Go client, and you own the `http.Client` it uses | Written again for every language, and it sees requests, not operations | Several languages must behave the same |
| [Kiota middleware handler](https://learn.microsoft.com/en-us/openapi/kiota/middleware) | A Kiota client, and per-request behavior at the HTTP layer | One handler class per language, outside anything Kiota generates or tests | You want the behavior declared beside the API model |
| [orval mutator](https://orval.dev/docs/guides/custom-client/) | A TypeScript-only client where every call can share one fetch function | Settings live in the mutator's module, so anything per client rides in each call's options | You need per-client options or another language |
| [sdkgen custom features](https://github.com/voxgig/sdkgen/blob/main/docs/how-to/add-a-feature.md) | Several sdkgen targets must behave identically and keep it through regeneration | One implementation per target language, plus a model file and hook wiring to learn | One language, where a middleware is shorter |
| [Speakeasy SDK hooks](https://www.speakeasy.com/docs/sdks/customize/code/sdk-hooks) | A Speakeasy SDK on a plan that includes hooks | Business and Enterprise plans only, and a hook per language directory | Your plan excludes hooks, or you generate elsewhere |

Voxgig maintains sdkgen. It is the subject of this page and one of five options in the table,
not the recommendation.

A Kiota handler or an orval mutator is shorter than an sdkgen feature, because each is one file
in one language. The sdkgen feature costs a file per target and buys the same option name,
default, and test corpus in every language. A Go RoundTripper is the cheapest of all and reaches
only Go.

## Declare the feature in the model

A feature is a model file plus source for each target. This one, `stamp`, hooks `PreRequest`,
the stage just before the transport sends the request. The other pipeline stages are `PrePoint`,
`PreSpec`, `PreResponse`, `PreResult` and `PreDone`, in the order the
[hooks reference](https://github.com/voxgig/sdkgen/blob/main/docs/reference/hooks.md) lists them,
and `PreUnexpected` fires instead when an operation fails.

```aontu title=".sdk/model/feature/stamp.aontu"
main: kit: feature: stamp: {
  name: key()
  title: "Client time header on every request"
  version: '0.1.0'
  active: true
  transport: 'none'

  config: {
    options: {
      active: false
      header: 'X-Client-Time'
    }
  }

  hook: {
    PreRequest: { active: true }
  }
}

main: kit: feature: stamp: config: optspec: {
  now: '`$FUNCTION`'
}
```

The outer `active: true` puts the feature in the build. The inner `config.options.active: false`
is what a client gets when its constructor says nothing, so the feature ships switched off.
`optspec` declares `now` as a function, the clock a test replaces.

The worked reference is the
[elementdemo SDK](https://github.com/voxgig-sdk/voxgig-elementdemo-sdk), whose `.sdk` holds a
custom `elementcard` feature. It hooks `PreResult`, renders an element-shaped record as an ASCII
tile, and ships the same switched-off default.

## Write the source once per target

Each target has a feature directory in its template tree, and the generator finds a file named
after the feature there. The TypeScript source sits at `.sdk/tm/ts/src/feature/stamp/`, Go at
`.sdk/tm/go/feature/stamp_feature.go`, and Python at `.sdk/tm/py/pkg/feature/stamp_feature.py`.
The TypeScript hook:

```ts title=".sdk/tm/ts/src/feature/stamp/StampFeature.ts"
  PreRequest(this: any, ctx: any) {
    if (!this.active || null == ctx.spec) {
      return
    }
    const spec = ctx.spec
    const header = this._options.header || 'X-Client-Time'
    if (null == spec.headers) {
      spec.headers = {}
    }
    const lower = header.toLowerCase()
    if (Object.keys(spec.headers).some((k) => k.toLowerCase() === lower)) {
      return
    }
    const now = 'function' === typeof this._options.now ? this._options.now : Date.now
    const value = new Date(now()).toISOString()
    spec.headers[header] = value
    this._client._stamp.count++
    this._client._stamp.last = value
  }
```

The Go and Python files do the same in their own idiom, reading `now` through the Go target's
`foptNow` helper and a callable in Python. Three files for one header is the price of the
approach, and the reason a one-language SDK should take a middleware instead.

Register the feature and generate, from `.sdk/`:

```bash
npx voxgig-sdkgen feature add stamp
npm run generate
```

`feature add` logs `stamp: defined in this project, so its files stay as they are`, because no
package provides the name. The generated `Config.ts` then carries `stamp` with
`"active": false`, and each target's feature directory holds the copied source.

## Call it with a pinned clock

`demo.mjs` loads the committed TypeScript build and calls a stand-in server on `127.0.0.1`,
once with the feature switched on and once with a client constructed with no feature options.

```bash
node demo.mjs
```

```text output
stamp active, clock pinned
  GET  /books  x-client-time: 2026-01-02T03:04:05.006Z
  POST /books  x-client-time: 2026-01-02T03:04:05.006Z
  client._stamp: {"count":2,"last":"2026-01-02T03:04:05.006Z"}
default construction
  GET  /books  x-client-time: (none)
  client._stamp: null
```

Both operations carry the pinned instant, written in the UTC form of
[RFC 3339](https://www.rfc-editor.org/rfc/rfc3339.html).[^1] The default client sends nothing and
records nothing, since the feature's `init` never ran for it.

## Add the same header in Kiota and orval

Neither generator has a feature model, so the behavior lives in hand-written code beside the
generated tree. Kiota sends every request through a middleware chain from its HTTP package.
`StampHandler` in `stamp-middleware.mjs` implements its `execute(url, requestInit, requestOptions)`
and goes first in `MiddlewareFactory.getDefaultMiddlewares()`, as the
[middleware page](https://learn.microsoft.com/en-us/openapi/kiota/middleware) shows.[^2] orval
replaces the fetch call with the function named by `override.mutator` in `orval.config.mjs`.

```ts title="stamp-fetch.ts"
export const stampFetch = async <T>(url: string, init: RequestInit = {}): Promise<T> => {
  const headers = new Headers(init.headers)
  if (!headers.has(settings.header)) {
    headers.set(settings.header, new Date(settings.now()).toISOString())
  }
  const res = await fetch(settings.base + url, { ...init, headers })
  const text = await res.text()
  return { data: text ? JSON.parse(text) : undefined, status: res.status, headers: res.headers } as T
}
```

```bash
node others.mjs
```

```text output
Kiota 1.38.0, StampHandler first in the middleware chain
  GET  /books  x-client-time: 2026-01-02T03:04:05.006Z
  POST /books  x-client-time: 2026-01-02T03:04:05.006Z
orval 8.48.0, stampFetch as the mutator
  GET  /books  x-client-time: 2026-01-02T03:04:05.006Z
  POST /books  x-client-time: 2026-01-02T03:04:05.006Z
```

Both files sit outside the output, so regeneration leaves them alone. The Kiota handler is
per client, through the adapter it builds. orval imports the mutator by name, so settings kept
in its module are shared by every call. Each generated function also takes an `options` argument
that reaches the mutator, so a header set there wins, and an off switch is yours to write. Each is TypeScript only; a Go or Python
Kiota client needs its own handler class.

## Check it worked

Regenerate twice and compare. `generate.sh` ran `npm run generate` twice and fingerprinted every
output file after each run, and ran the header probe in `probe/` against the Go and Python builds
once.

```bash
node regen-check.mjs
```

```text output
run 1: 283 files, run 2: 283 files, changed: 0
  ts  ./ts/src/feature/stamp/StampFeature.ts  run 1: true  run 2: true
  go  ./go/feature/stamp_feature.go  run 1: true  run 2: true
  py  ./py/bookshelf_sdk/feature/stamp_feature.py  run 1: true  run 2: true
orval, generated twice: changed: 0
recorded by generate.sh from the Go and Python SDKs:
go  stamp on:  GET /books 2026-01-02T03:04:05.006Z | POST /books 2026-01-02T03:04:05.006Z
go  stamp off: GET /books
py  stamp on:  GET /books 2026-01-02T03:04:05.006Z | POST /books 2026-01-02T03:04:05.006Z
py  stamp off: GET /books None
```

Then run the tests. The first constructs a client with the feature active and expects
`2026-01-02T03:04:05.006Z` on both requests, so a feature dropped from the model fails CI.

```bash
node --test stamp.test.mjs
```

```text output
# tests 7
# suites 0
# pass 7
# fail 0
```

## When it goes wrong

The feature never fires and every test passes. The constructor gave the feature options but
left out `active: true`, so the default from the model applied. Test for the header, not for a
successful call.

The test cannot pin the header's value. The feature read the wall clock, so no exact value can
be asserted, and a test that checks only the shape lets a broken clock through.
`pitfall.mjs` shows both.

```bash
node pitfall.mjs
```

```text output
options given, active left out
  call succeeded: true, header sent: false
active, no clock injected
  header sent: true, ISO 8601 shape: true
  equal to the pinned value: false
```

The third failure is a feature switched on by default. Every caller of the published SDK then
sends the header, including those whose API rejects unknown headers. Keep `active: false` in
the model and let the constructor decide.

## When not to do this

Do not write an sdkgen feature for an SDK with one language target. A Go RoundTripper or a
Kiota handler is one file you own. The model file, the per-target source and the hook wiring buy
nothing until a second language needs the same behavior.

Do not reach for sdkgen if your clients come from Kiota or orval and the behavior is transport
work. Kiota's default TypeScript middleware chain already runs retry, redirect, and user agent
handlers, so a header is one more handler. orval's mutator is the better choice when the client is TypeScript-only
and one configuration per process is enough.

Do not ship the feature on by default, and do not let it read the clock directly. A behavior
every caller gets without asking is a breaking change for the callers who did not want it.

## Related how-tos

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

- [Preview a regeneration as a diff before writing files](/howto/preview-a-regeneration-as-a-diff)

- [Fail a build when a generator customization becomes a fork](/howto/audit-generator-customisations-for-drift)

- [Package a customization several SDK projects can install](/howto/package-a-shared-generator-customisation)

- [Add a hook at the PreRequest stage of every SDK operation](/howto/add-a-prerequest-hook-to-every-operation)

## Last verified

Verified 2026-11-20 against Node 22.23.5, `@voxgig/create-sdkgen` 0.31.9, `@voxgig/sdkgen`
4.44.3, Kiota 1.38.0 with `@microsoft/kiota-bundle` 1.0.0-preview.114, and orval 8.48.0. Every
output block is what the command preceding it printed. Scaffolding and generation ran once,
recorded in `generate.sh`; the Go and Python lines were printed by that run on Go 1.24.7 and
Python 3.13.18. Speakeasy was not run; its hooks come from its documentation.

[^1]: The trailing `Z` is defined in [RFC 3339](https://www.rfc-editor.org/rfc/rfc3339.html),
section 2, as a UTC offset of 00:00, often spoken "Zulu" from the ICAO phonetic alphabet. Section
4.3 then gives `-00:00` a meaning of its own: the time in UTC is known and the local offset is
not. Three spellings of a zero offset carry two meanings, and `toISOString` always picks `Z`.

[^2]: Kiota's [middleware page](https://learn.microsoft.com/en-us/openapi/kiota/middleware)
tabulates thirteen handlers across seven languages. One row, Response Decompression, reads N/A in
every column, because those languages use the decompression their native HTTP clients already
offer.