1 /**
2 * Builds a JSON `Response`, for throwing from loaders and components so that
3 * react-router routes it to the nearest `errorElement`.
4 *
5 * Replaces react-router's `json()` helper, which was removed in v7. It keeps the
6 * same call shape, including the numeric-status shorthand, so call sites read the
7 * same as before.
8 *
9 * Deliberately not `Response.json()`: that static method is newer than the
10 * admin's browser target (Safari 16), and esbuild lowers syntax but does not
11 * polyfill runtime APIs, so it would fail at runtime on supported browsers.
12 */
13 export const jsonResponse = (
14 body: unknown,
15 init?: number | ResponseInit
16 ): Response => {
17 const responseInit: ResponseInit =
18 typeof init === "number" ? { status: init } : init ?? {}
19
20 return new Response(JSON.stringify(body), {
21 ...responseInit,
22 headers: {
23 "Content-Type": "application/json; charset=utf-8",
24 ...responseInit.headers,
25 },
26 })
27 }