superjson

repository·main·Indexed 26 days ago

https://github.com/flightcontrolhq/superjson

A library that safely serializes JavaScript expressions to a superset of JSON, supporting types such as Date, BigInt, Map, Set, RegExp, and Symbol. It provides stringify and parse for simple workflows, as well as serialize and deserialize for low-level access to JSON and metadata. superjson includes support for custom types via registerCustom, custom classes via registerClass, and custom symbols via registerSymbol, and offers integration plugins for Next.js via SWC and Babel.

Tokens
1.8K
Snippets
10
Records
19
Agent score
89%

What's inside superjson

  1. Configure Next.js Babel transform (stable)

    main

    For stable Next.js support using Babel, follow these steps:

    1. Install the Babel plugin:
    yarn add babel-plugin-superjson-next
    1. Add it to your .babelrc file:
    {
      "presets": ["next/babel"],
      "plugins": [
        "superjson-next"
      ]
    }
  2. Configure Next.js SWC Plugin (experimental)

    main

    For Next.js v13 or above, you can use the experimental SWC plugin for faster compilation.

    1. Install the plugin:
    yarn add next-superjson-plugin
    1. Add it to your next.config.js:
    module.exports = {
      experimental: {
        swcPlugins: [
          [
            'next-superjson-plugin',
            {
              excluded: [],
            },
          ],
        ],
      },
    };
  3. Extend Superjson with custom types

    main

    You can extend Superjson to support non-default data types using SuperJSON.registerCustom. This should be executed before any other SuperJSON calls (e.g., in _app.ts for Next.js).

    import { Decimal } from 'decimal.js';
    
    SuperJSON.registerCustom<Decimal, string>(
      {
        isApplicable: (v): v is Decimal => Decimal.isDecimal(v),
        serialize: v => v.toJSON(),
        deserialize: v => new Decimal(v),
      },
      'decimal.js'
    );
  4. Advanced usage with serialize and deserialize

    main

    For lower-level access to the split json and meta data, use serialize and deserialize. This is useful for APIs that need to remain JSON-compatible for standard clients while providing metadata for Superjson-enabled clients.

    const object = {
      normal: 'string',
      timestamp: new Date(),
      test: /superjson/,
    };
    
    const { json, meta } = superjson.serialize(object);
    
    /*
    json = {
      normal: 'string',
      timestamp: "2020-06-20T04:56:50.293Z",
      test: "/superjson/",
    };
    
    meta = {
      values: {
        timestamp: ['Date'],
        test: ['regexp'],
      }
    };
    */
    
    // To restore the object:
    deserialize({ json, meta }, { inPlace: true });
  5. Basic usage with stringify and parse

    main

    The simplest way to use Superjson is via stringify and parse. These functions behave similarly to JSON.stringify and JSON.parse but support complex types like Date automatically.

    import superjson from 'superjson';
    
    const jsonString = superjson.stringify({ date: new Date(0) });
    // jsonString === '{"json":{"date":"1970-01-01T00:00:00.000Z"},"meta":{"values":{date:"Date"}}}'
    
    const object = superjson.parse<{ date: Date }>(jsonString);
    // object === { date: new Date(0) }
  6. Supported Data Types

    main

    Superjson supports several types that standard JSON does not.

    | type | supported by standard JSON? | supported by Superjson? |
    | ----------- | --------------------------- | ------------------------- |
    | `string` | ✅ | ✅ |
    | `number` | ✅ | ✅ |
    | `boolean` | ✅ | ✅ |
    | `null` | ✅ | ✅ |
    | `Array` | ✅ | ✅ |
    | `Object` | ✅ | ✅ |
    | `undefined` | ❌ | ✅ |
    | `bigint` | ❌ | ✅ |
    | `Date` | ❌ | ✅ |
    | `RegExp` | ❌ | ✅ |
    | `Set` | ❌ | ✅ |
    | `Map` | ❌ | ✅ |
    | `Error` | ❌ | ✅ |
    | `URL` | ❌ | ✅ |