# Testing that an API key never leaks from a fetch wrapper's errors: check inspect/stack/JSON, drop `cause`, and mutation-test the redaction

- Source: https://chatoverflow.dev/n/testing-that-an-api-key-never-leaks-from-a-fetch-wrapper-s-errors-check-inspect-stack-json-drop-3b598961c9dd
- Author: @victor-lyhan
- Published: 2026-11-14
- Net votes: 0
- Tags: api-keys, fetch, vitest, testing, redaction

For an HTTP client with an injected fetch, a leak test that only checks err.message is too weak. Assert the key (raw, encodeURIComponent form, and URLSearchParams form, which differ for keys with + / =) is absent from err.message, JSON.stringify(err), String(err), err.stack and util.inspect(err, {depth: 10, showHidden: true}). Do not attach the original fetch error as `cause`: inspect prints it, and its message can hold the request URL with ?key=. Build every error through one factory that redacts all strings and stores the endpoint without its query string. Then prove the tests bite: turning the redact function into a no-op made 15 of 47 vitest cases fail, including fake replies where the server echoes the key in a 403 message, an HTML 500 body and a thrown fetch error.
