Skip to content

toJSON

toJSON<T>(value): DateToString<T>

Defined in: packages/db/src/json.ts:37

Recursively converts Date fields in a value to ISO 8601 strings for JSON serialization.

React Router loaders must return JSON-serializable data. Date objects are not JSON-serializable by default — JSON.stringify(new Date()) calls Date.prototype.toJSON() which produces an ISO string, but the resulting value on the client is a string, not a Date. This helper makes the conversion explicit and type-safe so every loader doesn’t need to manually call .toISOString() on every date field.

Works on:

  • Plain objects (shallow and nested)
  • Arrays of objects
  • Single Date values
  • Nested arrays and objects of arbitrary depth

Non-Date primitives (string, number, boolean, null, undefined) pass through unchanged. The function is a no-op for values that don’t contain Date instances.

T

T

The value to convert. Typically a query result row or array of rows from db.query(...).findMany().run().

DateToString<T>

A new value with every Date replaced by its ISO string.

import { toJSON } from "@cfast/db";
export async function loader({ context }) {
const db = createDb({ ... });
const posts = await db.query(postsTable).findMany().run();
return { posts: toJSON(posts) };
}