• Stars
    star
    3,746
  • Rank 11,772 (Top 0.3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 10 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.

superjson

Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.

All Contributors npm Language grade: JavaScript CI

Key features

  • ๐Ÿฑ Reliable serialization and deserialization
  • ๐Ÿ” Type safety with autocompletion
  • ๐Ÿพ Negligible runtime footprint
  • ๐Ÿ’ซ Framework agnostic
  • ๐Ÿ›  Perfect fix for Next.js's serialisation limitations in getServerSideProps and getInitialProps

Backstory

At Blitz, we have struggled with the limitations of JSON. We often find ourselves working with Date, Map, Set or BigInt, but JSON.stringify doesn't support any of them without going through the hassle of converting manually!

Superjson solves these issues by providing a thin wrapper over JSON.stringify and JSON.parse.

Sponsors

Flightcontrol Logo

Getting started

Install the library with your package manager of choice, e.g.:

yarn add superjson

Basic Usage

The easiest way to use Superjson is with its stringify and parse functions. If you know how to use JSON.stringify, you already know Superjson!

Easily stringify any expression youโ€™d like:

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"}}}'

And parse your JSON like so:

const object = superjson.parse<{ date: Date }>(jsonString);

// object === { date: new Date(0) }

Advanced Usage

For cases where you want lower level access to the json and meta data in the output, you can use the serialize and deserialize functions.

One great use case for this is where you have an API that you want to be JSON compatible for all clients, but you still also want to transmit the meta data so clients can use superjson to fully deserialize it.

For example:

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/",
};

// note that `normal` is not included here; `meta` only has special cases
meta = {
  values: {
    timestamp: ['Date'],
    test: ['regexp'],
  }
};
*/

Using with Next.js

The getServerSideProps, getInitialProps, and getStaticProps data hooks provided by Next.js do not allow you to transmit Javascript objects like Dates. It will error unless you convert Dates to strings, etc.

Thankfully, Superjson is a perfect tool to bypass that limitation!

Next.js SWC Plugin (experimental, v13 or above)

Next.js SWC plugins are experimental, but promise a significant speedup. To use the SuperJSON SWC plugin, install it and add it to your next.config.js:

yarn add next-superjson-plugin
// next.config.js
module.exports = {
  experimental: {
    swcPlugins: [
      [
        'next-superjson-plugin',
        {
          excluded: [],
        },
      ],
    ],
  },
}

Next.js (stable Babel transform)

Install the library with your package manager of choice, e.g.:

yarn add babel-plugin-superjson-next

Add the plugin to your .babelrc. If you don't have one, create it.

{
  "presets": ["next/babel"],
  "plugins": [
    ...
    "superjson-next" // ๐Ÿ‘ˆ
  ]
}

Done! Now you can safely use all JS datatypes in your getServerSideProps / etc. .

API

serialize

Serializes any JavaScript value into a JSON-compatible object.

Examples

const object = {
  normal: 'string',
  timestamp: new Date(),
  test: /superjson/,
};

const { json, meta } = serialize(object);

Returns json and meta, both JSON-compatible values.

deserialize

Deserializes the output of Superjson back into your original value.

Examples

const { json, meta } = serialize(object);

deserialize({ json, meta });

Returns your original value.

stringify

Serializes and then stringifies your JavaScript value.

Examples

const object = {
  normal: 'string',
  timestamp: new Date(),
  test: /superjson/,
};

const jsonString = stringify(object);

Returns string.

parse

Parses and then deserializes the JSON string returned by stringify.

Examples

const jsonString = stringify(object);

parse(jsonString);

Returns your original value.


Superjson supports many extra types which JSON does not. You can serialize all these:

type supported by standard JSON? supported by Superjson?
string โœ… โœ…
number โœ… โœ…
boolean โœ… โœ…
null โœ… โœ…
Array โœ… โœ…
Object โœ… โœ…
undefined โŒ โœ…
bigint โŒ โœ…
Date โŒ โœ…
RegExp โŒ โœ…
Set โŒ โœ…
Map โŒ โœ…
Error โŒ โœ…
URL โŒ โœ…

Recipes

SuperJSON by default only supports built-in data types to keep bundle-size as low as possible. Here are some recipes you can use to extend to non-default data types.

Place them in some central utility file and make sure they're executed before any other SuperJSON calls. In a Next.js project, _app.ts would be a good spot for that.

Decimal.js / Prisma.Decimal

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'
);

Contributors โœจ

Thanks goes to these wonderful people (emoji key):

Dylan Brookes
Dylan Brookes

๐Ÿ’ป ๐Ÿ“– ๐ŸŽจ โš ๏ธ
Simon Knott
Simon Knott

๐Ÿ’ป ๐Ÿค” โš ๏ธ ๐Ÿ“–
Brandon Bayer
Brandon Bayer

๐Ÿค”
Jeremy Liberman
Jeremy Liberman

โš ๏ธ ๐Ÿ’ป
Joris
Joris

๐Ÿ’ป
tomhooijenga
tomhooijenga

๐Ÿ’ป ๐Ÿ›
Ademรญlson F. Tonato
Ademรญlson F. Tonato

โš ๏ธ
Piotr Monwid-Olechnowicz
Piotr Monwid-Olechnowicz

๐Ÿค”
Alex Johansson
Alex Johansson

๐Ÿ’ป โš ๏ธ
Simon Edelmann
Simon Edelmann

๐Ÿ› ๐Ÿ’ป ๐Ÿค”
Sam Garson
Sam Garson

๐Ÿ›
Mark Hughes
Mark Hughes

๐Ÿ›
Lxxyx
Lxxyx

๐Ÿ’ป
Mรกximo Mussini
Mรกximo Mussini

๐Ÿ’ป
Peter Dekkers
Peter Dekkers

๐Ÿ›
Gabe O'Leary
Gabe O'Leary

๐Ÿ“–
Benjamin
Benjamin

๐Ÿ“–
Ionut-Cristian Florescu
Ionut-Cristian Florescu

๐Ÿ›
Chris Johnson
Chris Johnson

๐Ÿ“–
Nicholas Chiang
Nicholas Chiang

๐Ÿ› ๐Ÿ’ป
Datner
Datner

๐Ÿ’ป
ruessej
ruessej

๐Ÿ›
JH.Lee
JH.Lee

๐Ÿ“–
narumincho
narumincho

๐Ÿ’ป
Markus Greystone
Markus Greystone

๐Ÿ›
darthmaim
darthmaim

๐Ÿ’ป
Max Malm
Max Malm

๐Ÿ“–
Tyler Collier
Tyler Collier

๐Ÿ“–

This project follows the all-contributors specification. Contributions of any kind welcome!

See also

Other libraries that aim to solve a similar problem:

More Repositories

1

blitz

โšก๏ธ The Missing Fullstack Toolkit for Next.js
TypeScript
13,675
star
2

next-superjson-plugin

SuperJSON Plugin for Next.js Pages and Components
Rust
182
star
3

blitzjs.com

Website & docs
MDX
180
star
4

babel-plugin-superjson-next

Automatically transform your Next.js Pages to use SuperJSON
TypeScript
125
star
5

awesome-blitzjs

Curated list of awesome resources for blitz.js
90
star
6

blitzjs.com-translation

Nexus of resources and tools for translating the Blitz docs.
TypeScript
14
star
7

ja.blitzjs.com

(Work in progress) Blitzjs.com website in Japanese!
JavaScript
13
star
8

github-bot

Our very own Github Bot
TypeScript
6
star
9

codesandbox-template

TypeScript
5
star
10

drafts

A place for RFCs and other documents to be drafted before official publication
5
star
11

zh-hans.blitzjs.com

(Work in progress) Blitzjs.com website in Simplified Chinese!
JavaScript
4
star
12

fr.blitzjs.com

(Work in progress) Blitzjs.com website in French!
JavaScript
4
star
13

blitz-realworld-example

TypeScript
4
star
14

art

Blitz.js Branding Assets
3
star
15

es.blitzjs.com

(Work in progress) Blitzjs.com website in Spanish!
JavaScript
3
star
16

discord-bot

The bot used on the Blitz Community discord server
TypeScript
3
star
17

id.blitzjs.com

(Work in progress) Blitzjs.com website in Indonesian!
JavaScript
2
star
18

community-intros-matcher

Algorithm to generate community intros matches.
TypeScript
2
star
19

legacy-framework

JavaScript
2
star
20

versions-diff-web

A web tool to support Blitz developers in upgrading their apps.
JavaScript
2
star
21

versions-diff

Shell
2
star
22

it.blitzjs.com

(Work in progress) Blitzjs.com website in Italian!
JavaScript
1
star
23

ko.blitzjs.com

(Work in progress) Blitzjs.com website in Korean!
JavaScript
1
star
24

pt-br.blitzjs.com

(Work in progress) Blitzjs.com website in Brazilian Portuguese!
JavaScript
1
star