Repo of the Day
ravionhq/superjson
Published: Feb 23, 2023
Open repository ↗Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.
Summary
Superjson is a TypeScript library that extends JSON.stringify and JSON.parse to handle JavaScript values that standard JSON drops or mangles, including Date, BigInt, Map, Set, RegExp, Error, URL, and undefined. It encodes those values into a JSON-compatible shape with a small metadata sidecar, so the original types can be restored on parse. It is published under the MIT license and is designed as a drop-in replacement for the standard JSON functions.
What it is useful for
- Sending rich JavaScript values across boundaries that only transport JSON, such as server-to-client payloads,
localStorage, message queues, or worker messages. - Next.js
getServerSideProps,getStaticProps, andgetInitialPropsdata hooks, which the README calls out as rejecting values likeDate. - APIs that should remain JSON-compatible for plain clients but still round-trip types when both sides use Superjson. The README demonstrates this with
serialize, which returns{ json, meta }separately so non-Superjson clients can ignore the metadata. - Working with domain types that are not in the default set. The README documents a recipe using
SuperJSON.registerCustom, withDecimal.jsandPrisma.Decimalas the worked example.
How engineers can use it
Install with yarn add superjson, then use stringify and parse in place of the built-ins. The README's basic example is:
import superjson from 'superjson';
const jsonString = superjson.stringify({ date: new Date(0) });
const object = superjson.parse(jsonString);
For lower-level access, serialize and deserialize return or accept { json, meta }. The README notes deserialize supports an { inPlace: true } option that mutates the input object for better performance on large payloads.
For Next.js, the README documents two integration paths. The first is an experimental SWC plugin for Next.js 13+: install next-superjson-plugin and register it under experimental.swcPlugins in next.config.js. The second is a stable Babel transform: install babel-plugin-superjson-next and add "superjson-next" to .babelrc under the next/babel preset.
Documented limitations: only built-in types are supported by default; other classes must be registered with SuperJSON.registerCustom before any SuperJSON calls. The SWC integration is explicitly labeled experimental in the README. For anything beyond the commands above, refer to the README directly, since installation steps for non-Next.js or non-yarn setups are not covered in the supplied material.