Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.
Installations
npm install superjson
Developer
Developer Guide
Module System
ESM
Min. Node Version
>=16
Typescript Support
No
Node Version
20.9.0
NPM Version
10.1.0
Statistics
4,184 Stars
287 Commits
90 Forks
11 Watching
41 Branches
29 Contributors
Updated on 29 Nov 2024
Bundle Size
11.01 kB
Minified
3.77 kB
Minified + Gzipped
Languages
TypeScript (96.4%)
JavaScript (3.51%)
Shell (0.09%)
Total Downloads
Cumulative downloads
Total Downloads
113,543,180
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
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.
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
andgetInitialProps
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
Superjson logo by NUMI:
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:
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) }
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:
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*/
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
:
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};
Next.js (stable Babel transform)
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. .
API
serialize
Serializes any JavaScript value into a JSON-compatible object.
Examples
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.
deserialize
Deserializes the output of Superjson back into your original value.
Examples
1const { json, meta } = serialize(object); 2 3deserialize({ json, meta });
Returns your original value
.
stringify
Serializes and then stringifies your JavaScript value.
Examples
1const object = { 2 normal: 'string', 3 timestamp: new Date(), 4 test: /superjson/, 5}; 6 7const jsonString = stringify(object);
Returns string
.
parse
Parses and then deserializes the JSON string returned by stringify
.
Examples
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 | ❌ | ✅ |
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
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);
Contributors ✨
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!
See also
Other libraries that aim to solve a similar problem:
- Serialize JavaScript by Eric Ferraiuolo
- devalue by Rich Harris
- next-json by Daniele Ricci
Stable Version
The latest stable version of the package.
Stable Version
2.2.1
CRITICAL
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
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
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
- Warn: no topLevel permission defined: .github/workflows/main.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/flightcontrolhq/superjson/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/flightcontrolhq/superjson/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:25: update your workflow using https://app.stepsecurity.io/secureworkflow/flightcontrolhq/superjson/main.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/main.yml:50: update your workflow using https://app.stepsecurity.io/secureworkflow/flightcontrolhq/superjson/main.yml/main?enable=pin
- Info: 0 out of 3 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 third-party GitHubAction dependencies pinned
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 19 are checked with a SAST tool
Reason
23 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-93q8-gq69-wqmw
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-gxpj-cx7g-858c
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-29mw-wpgm-hmr9
- Warn: Project is vulnerable to: GHSA-35jh-r3h4-6jhm
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-vxvm-qww3-2fh7
- Warn: Project is vulnerable to: GHSA-5fw9-fq32-wv5p
- Warn: Project is vulnerable to: GHSA-p8p7-x288-28g6
- Warn: Project is vulnerable to: GHSA-gcx4-mw62-g8wm
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-hxcc-f52p-wc94
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
- Warn: Project is vulnerable to: GHSA-92r3-m2mg-pj97
- Warn: Project is vulnerable to: GHSA-c24v-8rfc-w8vw
- Warn: Project is vulnerable to: GHSA-8jhw-289h-jh2g
- Warn: Project is vulnerable to: GHSA-64vr-g452-qvp3
- Warn: Project is vulnerable to: GHSA-9cwx-2883-4wfx
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
Score
3.4
/10
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 MoreOther packages similar to superjson
superjson-cjs
<p align="center"> <img alt="superjson" src="./docs/superjson-banner.png" width="800" /> </p>
next-superjson-plugin
Automatically transform your Next.js Pages to use SuperJSON with SWC
next-superjson
Automatically transform your Next.js Pages to use SuperJSON, without losing swc support
remix-typedjson
This package is a replacement for superjson to use in your Remix app. It handles a subset of types that `superjson` supports, but is faster and smaller.