Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Superjson is a flexible and powerful library for serializing JavaScript data structures, including those that are not supported by JSON, such as Dates, RegExps, Maps, Sets, and more. It allows for seamless serialization and deserialization of complex data types, making it easier to work with complex data in applications that require data persistence or transmission.
Serialization of complex types
Superjson can serialize complex JavaScript types like Dates, Maps, and Sets into a string representation that can be easily transmitted or stored. Upon deserialization, these strings are converted back into their original complex types.
{"date": "2023-04-14T12:00:00.000Z", "map": "[[\"key1\",\"value1\"],[\"key2\",\"value2\"]]", "set": "[\"a\",\"b\",\"c\"]"}
Custom serialization
Developers can define custom serialization and deserialization logic for unsupported types or to override the default behavior for supported types. This feature enhances flexibility and control over how data is serialized.
{"customType": "SerializedValue"}
Flatted is a package that offers serialization and deserialization of complex JavaScript objects, including nested objects and circular references, using a flat structure. Compared to Superjson, Flatted focuses on solving circular reference issues but does not explicitly handle a wide range of JavaScript types like Superjson does.
Serialize-javascript provides serialization of JavaScript objects into a string, including regular expressions and functions. It is similar to Superjson in its ability to handle non-standard JSON data types, but it is more focused on including functions in the serialization process, which Superjson does not inherently support.
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:
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) }
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'],
}
};
*/
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
:
yarn add next-superjson-plugin
// next.config.js
module.exports = {
experimental: {
swcPlugins: [
[
'next-superjson-plugin',
{
excluded: [],
},
],
],
},
};
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. .
Serializes any JavaScript value into a JSON-compatible object.
const object = {
normal: 'string',
timestamp: new Date(),
test: /superjson/,
};
const { json, meta } = serialize(object);
Returns json
and meta
, both JSON-compatible values.
Deserializes the output of Superjson back into your original value.
const { json, meta } = serialize(object);
deserialize({ json, meta });
Returns your original value
.
Serializes and then stringifies your JavaScript value.
const object = {
normal: 'string',
timestamp: new Date(),
test: /superjson/,
};
const jsonString = stringify(object);
Returns string
.
Parses and then deserializes the JSON string returned by stringify
.
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 | β | β |
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'
);
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:
FAQs
Unknown package
The npm package superjson receives a total of 1,704,906 weekly downloads. As such, superjson popularity was classified as popular.
We found that superjson demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Β It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.