Gathering detailed insights and metrics for superjson
Gathering detailed insights and metrics for superjson
Gathering detailed insights and metrics for superjson
Gathering detailed insights and metrics for superjson
Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.
npm install superjson
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
4,183 Stars
287 Commits
90 Forks
11 Watching
41 Branches
29 Contributors
Updated on 27 Nov 2024
Minified
Minified + Gzipped
TypeScript (96.4%)
JavaScript (3.51%)
Shell (0.09%)
Cumulative downloads
Total Downloads
Last day
-16.4%
312,614
Compared to previous day
Last week
-2.6%
1,937,959
Compared to previous week
Last month
4.7%
8,326,324
Compared to previous month
Last year
96.8%
72,662,609
Compared to previous year
Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.
getServerSideProps
and getInitialProps
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
.
Superjson logo by NUMI:
Install the library with your package manager of choice, e.g.:
yarn add superjson
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:
1import superjson from 'superjson'; 2 3const jsonString = superjson.stringify({ date: new Date(0) }); 4 5// jsonString === '{"json":{"date":"1970-01-01T00:00:00.000Z"},"meta":{"values":{date:"Date"}}}'
And parse your JSON like so:
1const object = superjson.parse< 2{ date: Date } 3>(jsonString); 4 5// object === { date: new Date(0) }
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:
1const object = { 2 normal: 'string', 3 timestamp: new Date(), 4 test: /superjson/, 5}; 6 7const { json, meta } = superjson.serialize(object); 8 9/* 10json = { 11 normal: 'string', 12 timestamp: "2020-06-20T04:56:50.293Z", 13 test: "/superjson/", 14}; 15 16// note that `normal` is not included here; `meta` only has special cases 17meta = { 18 values: { 19 timestamp: ['Date'], 20 test: ['regexp'], 21 } 22}; 23*/
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 plugins are experimental, but promise a significant speedup.
To use the SuperJSON SWC plugin, install it and add it to your next.config.js
:
1yarn add next-superjson-plugin
1// next.config.js 2module.exports = { 3 experimental: { 4 swcPlugins: [ 5 [ 6 'next-superjson-plugin', 7 { 8 excluded: [], 9 }, 10 ], 11 ], 12 }, 13};
Install the library with your package manager of choice, e.g.:
1yarn add babel-plugin-superjson-next
Add the plugin to your .babelrc. If you don't have one, create it.
1{ 2 "presets": ["next/babel"], 3 "plugins": [ 4 ... 5 "superjson-next" // 👈 6 ] 7}
Done! Now you can safely use all JS datatypes in your getServerSideProps
/ etc. .
Serializes any JavaScript value into a JSON-compatible object.
1const object = { 2 normal: 'string', 3 timestamp: new Date(), 4 test: /superjson/, 5}; 6 7const { json, meta } = serialize(object);
Returns json
and meta
, both JSON-compatible values.
Deserializes the output of Superjson back into your original value.
1const { json, meta } = serialize(object); 2 3deserialize({ json, meta });
Returns your original value
.
Serializes and then stringifies your JavaScript value.
1const object = { 2 normal: 'string', 3 timestamp: new Date(), 4 test: /superjson/, 5}; 6 7const jsonString = stringify(object);
Returns string
.
Parses and then deserializes the JSON string returned by stringify
.
1const jsonString = stringify(object); 2 3parse(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 | ❌ | ✅ |
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
1import { Decimal } from 'decimal.js';
2
3SuperJSON.registerCustom<Decimal, string>(
4 {
5 isApplicable: (v): v is Decimal => Decimal.isDecimal(v),
6 serialize: v => v.toJSON(),
7 deserialize: v => new Decimal(v),
8 },
9 'decimal.js'
10);
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!
Other libraries that aim to solve a similar problem:
The latest stable version of the package.
Stable Version
1
9.1/10
Summary
Prototype Pollution leading to Remote Code Execution in superjson
Affected Versions
< 1.8.1
Patched Versions
1.8.1
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
Found 10/23 approved changesets -- score normalized to 4
Reason
0 commit(s) and 3 issue activity found in the last 90 days -- score normalized to 2
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
23 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More