Skip to content

Instantly share code, notes, and snippets.

@gregfromstl
Created February 3, 2025 05:02
Show Gist options
  • Save gregfromstl/70c1cd540e346974b08bfc9c833f453d to your computer and use it in GitHub Desktop.
Save gregfromstl/70c1cd540e346974b08bfc9c833f453d to your computer and use it in GitHub Desktop.
Hono middleware for strinfigying BigInt types in responses
import { createMiddleware } from "hono/factory";
import type {
InvalidJSONValue,
JSONValue,
SimplifyDeepArray,
} from "hono/utils/types";
export const transformJsonResponse = createMiddleware(async (ctx, next) => {
const originalJson = ctx.json.bind(ctx);
type JsonFn = (
obj: JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue,
init?: ResponseInit,
) => Response;
(ctx.json as JsonFn) = (
obj: JSONValue | SimplifyDeepArray<unknown> | InvalidJSONValue,
init?: ResponseInit,
) => {
const json = JSON.stringify(obj, (_key, value) => {
if (typeof value === "bigint") return value.toString();
return value;
});
return originalJson(JSON.parse(json), init);
};
await next();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment