@unikvs/superjson
How to use @unikvs/superjson, middleware that serializes values with SuperJSON.
Overview
Middleware that serializes values with SuperJSON. Middleware
It preserves type information lost by plain JSON, such as Date, Map, Set, BigInt, and undefined. Streams convert each item to one JSON Lines row.
nameis"Superjson".isOpenis alwaystrue.
Install with:
npm install @unikvs/superjsonpnpm add @unikvs/superjsonyarn add @unikvs/superjsonbun add @unikvs/superjsonnub add @unikvs/superjsonaube add @unikvs/superjsonUsage
Superjson implements IMiddleware. Pass it to UniKvs with use().
import { Superjson } from "@unikvs/superjson";
The following example stores an object holding a date without losing type information, and reads it back as a Date.
import { Memory } from "@unikvs/memory";
import { Superjson } from "@unikvs/superjson";
import * as unikvs from "unikvs";
const kvs = new unikvs.Builder<{ event: unikvs.Value<{ readonly at: Date }> }>()
.use(new Superjson())
.persist(new Memory())
.build();
await kvs.open();
await kvs.set("event", { at: new Date("2026-01-01T00:00:00Z") });
const event = await kvs.get("event");
await kvs.close();
Data types
| Method | Input | Output |
|---|---|---|
encode |
unknown |
Uint8Array<ArrayBuffer> |
decode |
Uint8Array<ArrayBuffer> |
unknown |
encodeStream |
unknown |
Uint8Array<ArrayBuffer> |
decodeStream |
Uint8Array<ArrayBuffer> |
unknown |
encodeconverts a value to a SuperJSON string and encodes it as UTF-8 bytes.decodeconverts bytes back to a UTF-8 string and parses it as SuperJSON.encodeStreamemits one line per input item (<SuperJSON>\n) in JSON Lines format.decodeStreambuffers received bytes as a string and parses lines as newlines become available.- One trailing CR is stripped per line, and empty lines are skipped.
- If there is no trailing newline, the remaining buffer is processed as the final line.
- Functions and symbols are rejected upfront because SuperJSON would silently convert them to
"{}".
Errors
Errors thrown by this package:
SuperjsonUnsupportedValueError
Thrown when passing a value of a type SuperJSON cannot handle.
typestring
`typeof` of the value being converted.
stringMeaning
Functions and symbols are converted to "{}" by SuperJSON without an error, so they are rejected upfront to prevent data loss. meta.type holds the target’s typeof.
How to fix
Do not include functions or symbols in values.
Native errors received while decoding invalid SuperJSON or UTF-8 propagate unchanged.