# How to unwrap response envelopes and keep headers and request IDs

> Return the entity or a page from each SDK method, not the data and meta envelope, and keep the status, headers, rate-limit values, and request ID one call away.

Source: https://voxgig.com/howto/unwrap-response-envelopes-without-losing-headers

- Audience: api-producer
- Level: beginner
- Languages: typescript, java
- Verified: 2026-11-30
- Published: 2026-11-30

## Short answer

Return the payload the caller asked for, the entity or a page, and keep the response it came from one call away. In TypeScript, record the status, request ID, and headers in a WeakMap keyed by the returned value, and add a withResponse() method to the returned promise. Put pagination on a page type, never on the entity. Assert in a test that both paths reach the request ID.

---
## You will need

Node 22.18 or later, which runs the `.ts` files with its built-in type stripping, and a JDK 11 or
later for the Java part. An API that wraps its responses in an envelope, here a local stand-in on
127.0.0.1. Method names follow
[the same verbs across resources](/howto/consistent-method-names-across-resources-and-languages).

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [AWS SDK v3 $metadata](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-smithy-types/Interface/ResponseMetadata/) | The output is a command result, not an entity a caller stores | Every output type carries `$metadata`, and a header it does not map to one of six fields needs a middleware | Callers store the returned value as an entity |
| [OpenAPI Generator withHttpInfo](https://openapi-generator.tech/docs/generators/java/) | Java and other typed clients generated from a document | A second method per operation, and the default method returns whatever schema the document names, envelope included | You want the entity by default and can wrap the generated client |
| [Stainless `withResponse`, as `groq-sdk` ships it](https://github.com/groq/groq-typescript#accessing-raw-response-data-eg-headers) | You write the pattern by hand: callers rarely need headers, and each method keeps one return type | The default path keeps no request ID, so a caller must choose the raw path before the call | Support needs the request ID from every call, logged or not |
| [Stripe `lastResponse`](https://docs.stripe.com/api/request_ids) | Every returned object should carry its response, invisible to `JSON.stringify` | A property name taken from every entity, and lists still come back as a list object with `data` | An entity may own a field with that name, or lists should be plain arrays |

Stripe hangs the response on the object, so the default path keeps everything and the name
`lastResponse` is reserved on every type. Stainless keeps the return type clean and puts the
headers behind `withResponse()`, which a caller has to choose in advance.
[Stainless has stopped taking signups and creating projects and SDKs](https://www.stainless.com/blog/stainless-is-joining-anthropic/)
and is winding down its hosted products, so its row describes the pattern in `groq-sdk`, whose
README says Stainless generated it. OpenAPI Generator pays for the same split with a second method per operation.

## Return the payload and keep the response beside it

Record each response in a `WeakMap` keyed by the value the method returns. The entity type stays
exactly what the API documents, so no field the API adds later can collide with the metadata.

```ts title="client.ts"
const metaByValue = new WeakMap<object, ResponseMeta>()

/** The response that produced a value this client returned, or undefined. */
export function responseMeta(value: object): ResponseMeta | undefined {
  return metaByValue.get(value)
}

/** A Promise of the payload, plus withResponse() for the payload and the response. */
export type ApiCall<T> = Promise<T> & {
  withResponse(): Promise<{ data: T; meta: ResponseMeta }>
}

function apiCall<T>(result: Promise<{ data: T; meta: ResponseMeta }>): ApiCall<T> {
  const data = result.then((r) => r.data) as ApiCall<T>
  // Mark both rejections handled now; a caller who awaits either still gets the error.
  result.catch(() => {})
  data.catch(() => {})
  data.withResponse = () => result
  return data
}
```

`ApiCall` is a real `Promise`, so `Promise.all` and `assert.rejects` accept it. The two `catch`
handlers stop Node from ending the process when a failed call is awaited late. The caller's own
`await` still throws.

Unwrap in one place, and give a list a page type of its own, so `next_cursor` never reaches an item.

```ts title="client.ts"
  return {
    widgets: {
      get: (id: string) => apiCall(call(`/widgets/${segment(id)}`, (e: Envelope<Widget>) => e.data)),
      list: (cursor?: string) =>
        apiCall(
          call(
            `/widgets${cursor === undefined ? '' : `?cursor=${encodeURIComponent(cursor)}`}`,
            (e: Envelope<Widget[]>): Page<Widget> => ({ items: e.data, nextCursor: e.meta.next_cursor ?? null }),
          ),
        ),
    },
  }
```

Run the demo against the stand-in:

```bash
node demo.ts
```

```text output
default  {"id":"w_1","name":"sprocket"}
         responseMeta(widget).requestId = req_1
raw      {"id":"w_1","name":"sprocket"}
         status 200, requestId req_2, rateLimitRemaining 98
list     w_1 w_2, nextCursor c_2, requestId req_3
         keys of an item: id, name
error    widgets API answered 404 (request id req_4)
```

## Check it worked

The tests assert that the request ID is reachable from the default path through `responseMeta` and
from the raw path through `withResponse()`. They also cover a page, a 404, a plain-text 502 from a
proxy, a copied entity, and a call awaited late. One test runs `tsc` over a file whose `@ts-expect-error` lines fail
the moment `widget.data`, `widget.meta`, or `widget.next_cursor` would compile.

```bash
node --test envelope.test.ts
```

```text output
1..8
# tests 8
# suites 0
# pass 8
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 5832.652155
```

## See where three published SDKs put it

The same stand-in serves Stripe, Groq, and DynamoDB shapes, and each client gets its address,
key, and HTTP agent in code.

```bash
node vendors.ts
```

```text output
stripe 23.2.0
  retrieve       keys id, object, email; non-enumerable lastResponse
                 lastResponse.requestId req_1, statusCode 200
  list           keys object, data, has_more, url; non-enumerable lastResponse
                 lastResponse.requestId req_2
groq-sdk 1.6.0
  default        keys id, object, created, owned_by; non-enumerable none
  withResponse() data.id example-model; response.status 200, x-request-id req_4
  asResponse()   status 200, x-request-id req_5, body unread true
@aws-sdk/client-dynamodb 3.1180.0
  GetItem        keys Item, $metadata; non-enumerable none
                 $metadata {"httpStatusCode":200,"requestId":"req_6","attempts":1,"totalRetryDelay":0}
                 x-example-trace from the middleware: trace_7
```

stripe-node defines `lastResponse` as a non-enumerable property, so a logged customer does not
show it.[^1] Its list comes back as Stripe's own list object, so callers of a list do write `.data`.
The `groq-sdk` default object carries no request ID at all. AWS keeps the request ID in
`$metadata`, and the stand-in's `x-example-trace` header reached the caller through a
[deserialize-step middleware](https://github.com/aws/aws-sdk-js-v3#middleware-stack) added with
`priority: 'high'`.

## Wrap the generated Java client

OpenAPI Generator returns whatever schema the document names. Generated from an `openapi.json`
whose 200 response is `WidgetEnvelope`, its `getWidget` returns the envelope, and
`getWidgetWithHttpInfo` adds the status and headers.

```java title="generated/java/com/example/widgets/api/WidgetsApi.java"
  public WidgetEnvelope getWidget(@javax.annotation.Nonnull String id, Map<String, String> headers) throws ApiException {
    ApiResponse<WidgetEnvelope> localVarResponse = getWidgetWithHttpInfo(id, headers);
    return localVarResponse.getData();
  }
```

A facade of two methods unwraps it without touching the generated code:

```java title="java/UnwrappedWidgets.java"
  public Widget get(String id) throws ApiException {
    return api.getWidget(id).getData();
  }

  public ApiResponse<Widget> getWithHttpInfo(String id) throws ApiException {
    ApiResponse<com.example.widgets.model.WidgetEnvelope> raw = api.getWidgetWithHttpInfo(id);
    return new ApiResponse<>(raw.getStatusCode(), raw.getHeaders(), raw.getData().getData());
  }
```

```bash
node java-demo.ts
```

```text output
generated getWidget                 returns WidgetEnvelope, name via getData().getName(): sprocket
                                    request id via getMeta().getRequestId(): req_1
generated getWidgetWithHttpInfo     status 200, x-request-id req_2, x-ratelimit-remaining 98
UnwrappedWidgets.get                returns Widget, name via getName(): sprocket
UnwrappedWidgets.getWithHttpInfo    returns ApiResponse<Widget>, status 200, x-request-id req_4
```

This facade keeps the request ID on the `WithHttpInfo` path only, which is the cost of this row: a
caller who needs the ID has to pick that method before the call.

## When it goes wrong

Callers write `.data` everywhere, or an item carries `next_cursor`. The method returned the
envelope, or flattened `meta` into each entity. `pitfall.ts` shows both against the same stand-in:

```bash
node pitfall.ts
```

```text output
envelope   caller writes envelope.data.name: sprocket
           top-level keys: data, meta; x-ratelimit-remaining kept: false
flattened  keys of one widget: id, name, request_id, next_cursor
unwrapped  keys of one widget: id, name; page keys: items, nextCursor
```

Unwrap in the client, and move pagination to a page type.

The request ID is `undefined` on a value you built yourself. `responseMeta` only knows the objects
the client returned, and a spread such as `{ ...widget }` makes a separate object. Keep the original, or
take `withResponse()` when you plan to copy.

A request goes to the wrong path once the base URL holds `/v1`. `new URL('/widgets', base)` drops
the base path, so `client.ts` appends the path to the base URL instead.

## When not to do this

Do not unwrap an envelope that carries data the caller needs on every call. A batch endpoint that
returns per-item errors in `meta` belongs in a result type that names them, not in a side table.

Do not hide the response behind a `WeakMap` if callers serialize and rebuild values before they
read the request ID. A queue worker that receives a copy gets nothing back from `responseMeta`. Put
the ID in your own log line at call time instead.

Do not add a raw method per operation by hand in a generated SDK. OpenAPI Generator already emits
one, the `WithHttpInfo` method, and a facade over the generated client is less to maintain than
edits a regeneration overwrites.

## Related how-tos

- [Expose typed SDK errors callers match without parsing text](/howto/typed-sdk-errors-callers-can-match)

- [Shape an SDK around entities instead of endpoint wrappers](/howto/entity-clients-instead-of-endpoint-wrappers)

- [Expose an escape hatch for endpoints an SDK does not model](/howto/escape-hatch-for-unmodelled-endpoints)

- [Design an SDK constructor that takes configuration once](/howto/sdk-client-constructor-and-configuration)

- [Validate API responses at the SDK boundary with Zod](/howto/validate-api-responses-at-the-sdk-boundary)

## Last verified

Verified 2026-11-30 against Node 22.23.5, OpenJDK 21.0.13, TypeScript 6.0.3, stripe 23.2.0,
`groq-sdk` 1.6.0, `@aws-sdk/client-dynamodb` 3.1180.0, OpenAPI Generator 7.28.0, and Jackson 2.21.8.
Every output block is what the command preceding it printed. The three published SDKs ran against
a local stand-in that copies each API's envelope and request-ID header, not against Stripe, Groq,
or AWS. The Stainless generator itself was not run; its row is read from `groq-sdk`.

[^1]: The property is set with `Object.defineProperty`, `enumerable: false`, and `writable: false` in
[the request sender](https://github.com/stripe/stripe-node/blob/v23.2.0/src/RequestSender.ts), so
`JSON.stringify` and `console.log` pass over it. The same file copies four headers onto the raw
response as plain properties, `requestId`, `stripeAccount`, `apiVersion`, and `idempotencyKey`,
which is how `lastResponse.requestId` exists without a header lookup.