How-to › Ship an SDK

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.

Audience
API producer
Level
intermediate
Topic
Compose runtime features in an SDK
Languages
TypeScript and Go
Verified

Read first: Wrap an SDK transport in a middleware chain

A support ticket quotes one failed order, and the API’s logs hold thousands of requests with no id that ties any of them to it. Your SDK sends those requests from seven methods in each of two languages. Adding a header inside every method is fourteen edits, and the next regeneration writes over all of them.

What you get

You will end up with one hook, declared in an sdkgen feature and generated into the TypeScript and Go targets, that stamps a correlation header on every operation. This is for you if you own the SDK and the project that generates it.

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 covers that pattern.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
Kiota middleware handlerA Kiota client, where one handler should see every request the adapter sendsA URL and a RequestInit to work from, so the operation has to be read back out of the pathThe header depends on which operation is running
OkHttp application interceptorA Java or Kotlin client on OkHttp, generated or hand-writtenSees only the HTTP request, with no operation name, and covers that one languageYou ship the same header in several languages
sdkgen PreRequest hookAn sdkgen SDK whose hook should know the entity and operation, in each target you write it forOne source file per target, a regeneration, and direct() calls that skip itThe work belongs on each HTTP attempt, at the transport
Speakeasy beforeRequest hookA Speakeasy SDK, where the hook gets the operation ID and a built RequestA paid plan, since hooks are Business and Enterprise only, and one hook file per languageYou 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.

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:

  // 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:

// 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 describes.

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:

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
      },
    },
  },
})
node demo.mjs
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 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:

go run -C go .
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.

node --test hook.test.mjs
1..17
# tests 17
# suites 0
# pass 17
# fail 0
# cancelled 0
# skipped 0
# todo 0
go test -C go -v . | grep -E '^(=== RUN|PASS$|FAIL$)'
=== 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 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:

  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)
  }
node kiota-demo.mjs
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 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 signs every x-ms- header, its client request id included.3 The stand-in here signs every x- header:

node pitfall.mjs
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 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.

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.

Footnotes

  1. Azure Storage draws the same line with more room. Its List Containers reference 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. ↩︎ Back to text

  2. Kiota’s overview lists TypeScript among its supported languages. The table in its README 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. ↩︎ Back to text

  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 notes, a header with an empty value was left out; since then it is signed too. ↩︎ 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.