Sanitizes error messages by redacting sensitive patterns like API keys, tokens, and authorization headers. Reuse when logging or returning error messages containing sensitive credentials.
// Source: https://github.com/backbay-labs/clawdstrike | License: Apache-2.0 | Copyright You must retain, in the Source form of any Derivative Works
// Provided via justclaw.it.com; keep this notice with the code.
const SENSITIVE_PATTERNS = [
/x-apikey[:\s]+\S+/gi,
/key[:\s]+\S+/gi,
/authorization[:\s]+\S+/gi,
/Bearer\s+\S+/gi,
/apikey[=:]\S+/gi,
];
export function sanitizeErrorMessage(err: unknown): string {
const raw = err instanceof Error ? err.message : String(err);
let sanitized = raw;
for (const pattern of SENSITIVE_PATTERNS) {
sanitized = sanitized.replace(pattern, "[REDACTED]");
}
// Strip URLs that might contain keys in query params
sanitized = sanitized.replace(
/https?:\/\/[^\s]+key=[^\s&]+/gi,
"[URL_REDACTED]",
);
return sanitized;
}
See the full source, get the GitHub permalink, and search for more like it.
Get a free API key