# How to add a hook at the PreRequest stage of every SDK operation

> Declare one PreRequest hook in an sdkgen feature, generate it into the TypeScript and Go targets, and prove a correlation header arrives on every operation.

Source: https://voxgig.com/howto/add-a-prerequest-hook-to-every-operation

- Audience: api-producer
- Level: intermediate
- Languages: typescript, go
- Verified: 2026-11-19
- Published: 2026-11-19

## Short answer

In sdkgen, declare a feature whose model marks the PreRequest hook active, and write that hook once per target so it sets a header on the spec. Run voxgig-sdkgen feature add, then npm run generate. Every entity operation in those targets then sends the header once a caller switches the feature on. A direct() call skips the pipeline, so pass the header to it yourself, and run any request signer after the hook.

---
## You will need

Node 22 or later, Go 1.21 or later, and an sdkgen project with the `ts` and `go` targets. Verified
2026-11-19 against Node 22.23.5, Go 1.24.7, `@voxgig/create-sdkgen` 0.31.9 and `@voxgig/sdkgen`
4.44.3. The sample generated both targets once from `api.json`, a seven-operation Stockroom
document, and committed them, so every command runs offline against a local stand-in server.

A hook is one of two seams in an sdkgen client. The other is the transport, and
[wrap an SDK transport in a middleware chain](/howto/wrap-an-sdk-transport-with-middleware)
covers that pattern.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Kiota middleware handler](https://learn.microsoft.com/en-us/openapi/kiota/middleware) | A Kiota client, where one handler should see every request the adapter sends | A URL and a `RequestInit` to work from, so the operation has to be read back out of the path | The header depends on which operation is running |
| [OkHttp application interceptor](https://lysine.dev/okhttp/features/interceptors/) | A Java or Kotlin client on OkHttp, generated or hand-written | Sees only the HTTP request, with no operation name, and covers that one language | You ship the same header in several languages |
| [sdkgen `PreRequest` hook](https://github.com/voxgig/sdkgen/blob/main/docs/reference/hooks.md) | An sdkgen SDK whose hook should know the entity and operation, in each target you write it for | One source file per target, a regeneration, and `direct()` calls that skip it | The work belongs on each HTTP attempt, at the transport |
| [Speakeasy `beforeRequest` hook](https://www.speakeasy.com/docs/sdks/customize/code/sdk-hooks) | A Speakeasy SDK, where the hook gets the operation ID and a built `Request` | A paid plan, since hooks are Business and Enterprise only, and one hook file per language | You are not on a Business or Enterprise plan |

Voxgig maintains sdkgen. It is this page's worked path, and its row says when to pick something
else.

The four differ in what the function is handed. An OkHttp interceptor and a Kiota handler get an
HTTP request, so they see every request and cannot name the operation. Speakeasy's hook gets a
`Request` and a context that names the operation, on a paid plan. sdkgen's hook gets the spec
before the URL is built, with the entity and operation attached, and costs a source file per
target.

## Declare the hook in a feature model

An sdkgen hook belongs to a feature, and a feature starts as a model file. Its `hook` block names
the stages the pipeline dispatches the feature at. The generated README lists six: `PrePoint`,
`PreSpec`, `PreRequest`, `PreResponse`, `PreResult`, and `PreDone`. `PreRequest` fires once per
operation, after the spec is built and before anything is sent.

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

  name: key()
  title: "Correlation header"
  description: "Stamp the caller's correlation id on the request of every operation"
  version: '0.0.1'
  active: true
  base: 'BASE'
  transport: 'none'

  config: {
    # Opt-in: enable per client via options.feature.correlate.active = true
    options: {
      active: false
      header: 'X-Correlation-Id'
    }
  }

  # The one stage the pipeline dispatches this feature at.
  hook: {
    PreRequest: active: true
  }
}
```

`transport: 'none'` is the value the hooks reference gives a feature that uses hooks alone.
`active: false` under `options` makes it opt-in: every generated client carries the code, and a
client that never asks for it never builds the feature. An `optspec` entry lower in the file
declares `current`, the function a caller supplies.

## Write the hook once per target

The method name is the stage name. In TypeScript:

```ts title="correlate-feature/.sdk/tm/ts/src/feature/correlate/CorrelateFeature.ts"
  // Fires once per operation: the spec exists, and nothing has been sent.
  PreRequest(this: any, ctx: any) {
    const id = this._options.current(ctx.entity.name + '.' + ctx.op.name)

    if ('string' !== typeof id || !VALID_ID.test(id)) {
      this._client._correlate.skipped++
      return
    }

    ctx.spec.headers[this._options.header || 'X-Correlation-Id'] = id
    this._client._correlate.stamped++
  }
```

`ctx.spec.headers` is the map the request is built from. `ctx.entity.name` and `ctx.op.name` say
which operation is running, and the hook hands that to the caller's `current` function. An id that
is not 1 to 128 visible ASCII characters is left off, because a correlation id usually arrives on
an inbound request and is forwarded to somebody else's API.[^1]

The Go target dispatches by reflection on the method name, so the name is all that ties the
method to the stage:

```go title="correlate-feature/.sdk/tm/go/feature/correlate_feature.go"
// Fires once per operation: the spec exists, and nothing has been sent.
func (f *CorrelateFeature) PreRequest(ctx *core.Context) {
	if !f.Active || f.current == nil || ctx.Spec == nil {
		return
	}

	id := f.current(ctx.Op.Entity + "." + ctx.Op.Name)
	if !validCorrelationID.MatchString(id) {
		f.Skipped.Add(1)
		return
	}

	ctx.Spec.Headers[f.header] = id
	f.Stamped.Add(1)
}
```

## Add the feature and generate both targets

`feature add` takes a path whose last element is the feature name, as sdkgen's
[add-a-feature guide](https://github.com/voxgig/sdkgen/blob/main/docs/how-to/add-a-feature.md)
describes.

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

The second command copies the model file and each target's source into `.sdk/`. The third writes
`ts/src/feature/correlate/CorrelateFeature.ts` and `go/feature/correlate_feature.go`, and
registers the feature in both clients. In 4.44.3 every `generate` then warns that the copied
feature is stale, even after the refresh command it names, though the generated files match the
source.

Switch the feature on when a client is built, with the function that returns the id in force:

```js title="demo.mjs"
const client = new StockroomSDK({
  base: api.url,
  apikey: 'sk-test-1',
  feature: {
    correlate: {
      active: true,
      // The hook calls this once per operation, with the operation it is about to send.
      current: (op) => {
        ops.push(op)
        return job
      },
    },
  },
})
```

```bash
node demo.mjs
```

```text output
the hook was told  the server received
item.list          GET   /v1/items        x-correlation-id: job-7
item.load          GET   /v1/items/itm_1  x-correlation-id: job-7
item.update        PATCH /v1/items/itm_1  x-correlation-id: job-7
item.create        POST  /v1/items        x-correlation-id: job-8
order.create       POST  /v1/orders       x-correlation-id: job-8
order.list         GET   /v1/orders       x-correlation-id: job-8
order.load         GET   /v1/orders/ord_1 x-correlation-id: job-8

7 operations, 7 requests, 7 with the header
```

The left column is what the hook passed to `current`. The rest is what the stand-in recorded. The
demo changes `job` after the third call and the header follows, because the hook reads the id per
operation. In a server, return the store of an
[`AsyncLocalStorage`](https://nodejs.org/api/async_context.html) from `current`, and two requests
handled at once each stamp their own id.

The Go client takes the same option as a `func(op string) string`, and `go/main.go` makes the
same seven calls:

```bash
go run -C go .
```

```text output
the hook was told  the server received
item.list          GET   /v1/items        x-correlation-id: job-7
item.load          GET   /v1/items/itm_1  x-correlation-id: job-7
item.update        PATCH /v1/items/itm_1  x-correlation-id: job-7
item.create        POST  /v1/items        x-correlation-id: job-8
order.create       POST  /v1/orders       x-correlation-id: job-8
order.list         GET   /v1/orders       x-correlation-id: job-8
order.load         GET   /v1/orders/ord_1 x-correlation-id: job-8

7 operations, 7 requests, 7 with the header
```

The generated Go operations take no `context.Context`, so the id reaches the hook through the
closure. A Go server with one id per inbound request builds a client per request, which costs
1.7 MB in about 16,600 allocations in the sample's `BenchmarkNewClient`.

## Check it worked

Assert on what the server received. Seventeen Node tests cover the TypeScript client and the
Kiota handler, and eight Go tests cover the Go client, against stand-ins that record every header.

```bash
node --test hook.test.mjs
```

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

```bash
go test -C go -v . | grep -E '^(=== RUN|PASS$|FAIL$)'
```

```text output
=== RUN   TestEveryOperationCarriesTheHeader
=== RUN   TestTheHookIsToldTheOperation
=== RUN   TestTheHookCanLeaveOneOperationAlone
=== RUN   TestAnIDThatIsNotVisibleASCIIIsNotSent
=== RUN   TestDirectSkipsTheHook
=== RUN   TestTheFeatureIsOffUntilSwitchedOn
=== RUN   TestAMissingCurrentFailsAtConstruction
=== RUN   TestOneClientServesManyGoroutines
PASS
```

The first test in each file is the claim: seven operations, seven requests, each with
`x-correlation-id: job-7`.

## Add the same header in Kiota and Speakeasy

Kiota generates no hook, because its generated code makes no HTTP calls. The client takes a
request adapter, and behavior lives in that adapter's middleware chain. Kiota's
[middleware page](https://learn.microsoft.com/en-us/openapi/kiota/middleware) shows a handler in
.NET, TypeScript, and Python.[^2] The TypeScript one is a class with an `execute` method, added to
the array from `MiddlewareFactory.getDefaultMiddlewares()`.

Kiota 1.38.0 turned `api.json` into a client whose entry point is
`createStockroomClient(requestAdapter)`, and this handler stamps its requests:

```js title="kiota-handler.mjs"
  async execute(url, requestInit, requestOptions) {
    this.urls.push(`${requestInit.method} ${new URL(url).pathname}`)
    const id = this.current()
    if (typeof id === 'string' && VALID_ID.test(id)) {
      requestInit.headers = { ...requestInit.headers, 'x-correlation-id': id }
    }
    return this.next.execute(url, requestInit, requestOptions)
  }
```

```bash
node kiota-demo.mjs
```

```text output
the handler was told    the server received
GET /v1/items           x-correlation-id: job-7
GET /v1/items/itm_1     x-correlation-id: job-7
PATCH /v1/items/itm_1   x-correlation-id: job-7
POST /v1/items          x-correlation-id: job-7
POST /v1/orders         x-correlation-id: job-7
GET /v1/orders          x-correlation-id: job-7
GET /v1/orders/ord_1    x-correlation-id: job-7

7 calls, 7 requests, 7 with the header
handler position: 1 of 9, ahead of RetryHandler
```

The handler is told a method and a URL where the sdkgen hook was told `item.list`. In exchange it
sits inside the HTTP client, so no call goes around it, and its position is yours to choose. Ahead
of the retry handler it runs once per call, and behind it once per attempt.

Speakeasy generates the hook mechanism into the SDK. Its
[SDK hooks page](https://www.speakeasy.com/docs/sdks/customize/code/sdk-hooks) gives
`src/hooks/registration.ts` as the TypeScript registration file and
`internal/hooks/registration.go` as the Go one. Each is generated once and never overwritten.
There, `initHooks` calls `hooks.registerBeforeRequestHook` with an object whose
`beforeRequest(hookCtx, request)` returns the `Request` to send.

`hookCtx.operationID` names the operation, and the built `Request` carries the final URL, which
sdkgen's `PreRequest` never sees. The same page limits hooks to Business and Enterprise plans.

## When it goes wrong

A signing API answers 401 once the hook is on. The signer ran first, so the header was added to a
request whose signature was already computed. For Blob, Queue, and File requests, Azure Storage's
[Shared Key scheme](https://learn.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key)
signs every `x-ms-` header, its client request id included.[^3] The stand-in here signs every
`x-` header:

```bash
node pitfall.mjs
```

```text output
where the signer runs, and what the signing server answered
  PreRequest hook placed before correlate  401 signature mismatch
  PreRequest hook added after correlate    200
  system.fetch, the transport seam         200

one record, fetched three ways
  Item().load()              GET /v1/items/itm_1  x-correlation-id: job-7
  direct()                   GET /v1/items/itm_1  x-correlation-id: (none)
  direct() with headers      GET /v1/items/itm_1  x-correlation-id: job-7
```

Hooks at one stage run in the order their features were added: generated features sorted by
name, after `test`, unless `feature` is an array, then `extend` instances in list order. A signer named `auth` sorts
ahead of `correlate`, and an `async` hook finishes after the hooks behind it have run. Sign in
`system.fetch` instead. It is called after every hook has finished, with the final URL.

A `direct()` call arrives without the header, as the second block shows. `direct()` builds and
sends its request without running the stages, in both targets. Pass `headers` to it.

A hook passed through `extend` in a `hooks` map never runs. The generated README shows a feature
as an object with that map, but the 4.44.3 runtime calls a method named after the stage. Put `PreRequest` on
the object itself.

## When not to do this

Do not declare a feature for a header that only one caller needs. That caller can pass an object
with a `PreRequest` method in the client's `extend` option, with no regeneration.

Do not put per-attempt work in an sdkgen `PreRequest` hook. It runs once per operation, so timing
an attempt or signing a retry belongs at the transport. A Kiota handler does either job, depending
on where it sits in the chain.

Do not rely on the hook when the header must be on every request without exception. `direct()`
goes around the pipeline, while a Kiota handler inside the HTTP client has no such gap. Kiota also
suits a Go server that carries an id per request. Its Go methods take a `context.Context`, and
[its HTTP library](https://github.com/microsoft/kiota-http-go/blob/main/nethttp_request_adapter.go)
builds each request with it, so one shared client stamps a different id per call.

Do not use sdkgen's hook when your function needs the finished request. Speakeasy's
`beforeRequest` is handed the built `Request` and a context that carries the document's operation
ID.

Do not forward an id you have not checked. It came from outside, and it lands in another
company's logs.

## Related how-tos

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

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

- [Tag SDK calls with session and request ids](/howto/tag-sdk-calls-with-session-and-request-ids)

- [Propagate a request id through an SDK into server logs](/howto/propagate-a-request-id-into-server-logs)

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

## Last verified

Verified 2026-11-19 against Node 22.23.5, Go 1.24.7, `@voxgig/create-sdkgen` 0.31.9,
`@voxgig/sdkgen` 4.44.3, TypeScript 5.9.3, Kiota 1.38.0, and `@microsoft/kiota-http-fetchlibrary`
1.0.0-preview.111. Every output block is what the command preceding it printed. The scaffold, the
generation, and the Kiota run are not repeated by the page's checks: `generate.sh` ran them once,
and their output is committed under `generated/`.

`generate.sh` runs the Kiota CLI with `KIOTA_CLI_TELEMETRY_OPTOUT=true`, because the CLI collects
telemetry unless that variable is set. A Kiota Go client was generated and run once, outside the
sample, to confirm that a handler reads each call's context. Speakeasy and OkHttp were not run;
Speakeasy's hooks come from its documentation.

[^1]: Azure Storage draws the same line with more room. Its
[List Containers reference](https://learn.microsoft.com/en-us/rest/api/storageservices/list-containers2)
gives `x-ms-client-request-id` a one-kibibyte limit, describes the value it echoes back as at most
1024 visible ASCII characters, and highly recommends sending the header. The hook here allows an eighth of that.

[^2]: Kiota's [overview](https://learn.microsoft.com/en-us/openapi/kiota/overview) lists
TypeScript among its supported languages. The table in its
[README](https://github.com/microsoft/kiota) marks TypeScript as in preview, the generator prints
a preview warning on each TypeScript run, and `kiota info` names runtime packages at
1.0.0-preview.111. The supported client and the preview are the same code.

[^3]: The rule is one sentence in a list of steps: retrieve all headers for the resource that
begin with `x-ms-`, including the `x-ms-date` header. A Table service request skips the step,
because its signature string has no canonicalized headers at all. Before service version
2016-05-31, the
[same page](https://learn.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key)
notes, a header with an empty value was left out; since then it is signed too.