Object serialization

suggest change

Serialization turns an in-memory value into a sequence of bytes or characters that can be written to a file, sent over a network, stored in a database or passed to another thread or process. Deserialization rebuilds the value from those bytes.

Node.js has several built-in ways to do it, and they keep different amounts of information:

Method Output Keeps Date, Map, Set, BigInt Keeps cycles Keeps class instances Readable by other languages
JSON.stringify / JSON.parse string no (needs replacer/reviver) no no (needs code) yes
structuredClone() a copy, no bytes yes yes no n/a
v8.serialize / v8.deserialize Buffer yes yes no no
worker.postMessage(), fork() with serialization: 'advanced' internal yes yes no no
hand-written Buffer format Buffer whatever you write whatever you write yes yes, if documented
MessagePack (msgpackr package) Buffer yes, with options yes, with options yes, with extensions yes

The basics of JSON (formatting, toJSON, replacer and reviver, parse errors, files) are covered in JSON. This article is about the harder parts: getting real objects back, choosing a format, versioning, and doing it safely.

The examples were run with Node.js 24. Files ending in .mjs are ES modules.

What gets lost

Every serialization format stores data, not code. Methods live on the prototype, and none of the built-in formats record which class an object came from:

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  length() {
    return Math.hypot(this.x, this.y);
  }
}

const p = new Point(3, 4);
const json = JSON.stringify(p);
const back = JSON.parse(json);

console.log(json);
console.log(back instanceof Point, typeof back.length);

const viaClone = structuredClone(p);
console.log(viaClone instanceof Point, viaClone);
{"x":3,"y":4}
false undefined
false { x: 3, y: 4 }

Both JSON and structuredClone() give back a plain object with the same own properties. If you want a Point back, your code has to know that the data represents a Point and construct one.

toJSON and a static fromJSON

The simplest pattern pairs toJSON(), which decides what gets written, with a static fromJSON(), which validates the data and builds the instance:

class Money {
  constructor(amount, currency) {
    this.amount = amount;
    this.currency = currency;
  }

  toString() {
    return `${this.amount.toFixed(2)} ${this.currency}`;
  }

  toJSON() {
    return { amount: this.amount, currency: this.currency };
  }

  static fromJSON(data) {
    if (typeof data?.amount !== 'number' || typeof data?.currency !== 'string') {
      throw new TypeError('invalid Money');
    }
    return new Money(data.amount, data.currency);
  }
}

const price = new Money(19.9, 'EUR');
const json = JSON.stringify({ sku: 'A-100', price });
console.log(json);

const raw = JSON.parse(json);
const item = { ...raw, price: Money.fromJSON(raw.price) };
console.log(item.price instanceof Money, `${item.price}`);
{"sku":"A-100","price":{"amount":19.9,"currency":"EUR"}}
true 19.90 EUR

This works well when the shape of the data is fixed and known: the code that reads price knows it's Money. The JSON stays clean, so other programs and languages can read it too. Private fields (#field) are never visible to JSON.stringify, so toJSON() is also the only way to include them.

Type-tagged JSON with a class registry

When the data is a mix of types, like a saved application state, it's easier to write the type into the JSON itself. A replacer wraps special values in { "$type": ..., "value": ... } and a reviver unwraps them. Only classes explicitly registered can be created:

// serializer.mjs
const classes = new Map();

export function register(cls) {
  classes.set(cls.name, cls);
  return cls;
}

function replacer(key, value) {
  // `this[key]` is the value before toJSON() ran (Date has toJSON)
  const original = this[key];
  if (original instanceof Date) return { $type: 'Date', value: original.toISOString() };
  if (original instanceof Map) return { $type: 'Map', value: [...original] };
  if (original instanceof Set) return { $type: 'Set', value: [...original] };
  if (typeof original === 'bigint') return { $type: 'BigInt', value: original.toString() };
  if (original !== null && typeof original === 'object') {
    const cls = classes.get(original.constructor?.name);
    if (cls === original.constructor) {
      return { $type: cls.name, value: { ...original } };
    }
  }
  return value;
}

function reviver(key, value) {
  if (value === null || typeof value !== 'object' || typeof value.$type !== 'string') {
    return value;
  }
  switch (value.$type) {
    case 'Date': return new Date(value.value);
    case 'Map': return new Map(value.value);
    case 'Set': return new Set(value.value);
    case 'BigInt': return BigInt(value.value);
  }
  const cls = classes.get(value.$type);
  if (!cls) throw new TypeError(`unknown type: ${value.$type}`);
  return Object.assign(Object.create(cls.prototype), value.value);
}

export const serialize = (value, space) => JSON.stringify(value, replacer, space);
export const deserialize = (text) => JSON.parse(text, reviver);

A few details matter here:

Using it:

import { register, serialize, deserialize } from './serializer.mjs';

class Task {
  constructor(title, due) {
    this.title = title;
    this.due = due;
    this.done = false;
  }

  isOverdue(now = new Date()) {
    return !this.done && this.due < now;
  }
}
register(Task);

class Project {
  constructor(name) {
    this.name = name;
    this.tasks = new Map();
    this.tags = new Set();
    this.budget = 0n;
  }
}
register(Project);

const project = new Project('website');
project.tasks.set(1, new Task('design', new Date('2026-09-01T00:00:00Z')));
project.tasks.set(2, new Task('launch', new Date('2027-01-15T00:00:00Z')));
project.tags.add('web').add('q4');
project.budget = 12_000_000_000_000_000_000n;

const text = serialize(project);
console.log(text.length, text.slice(0, 70) + '...');

const copy = deserialize(text);
console.log(copy instanceof Project, copy.tasks.get(1) instanceof Task);
console.log(copy.tasks.get(1).due instanceof Date, copy.tags.has('q4'), copy.budget);
console.log(copy.tasks.get(1).isOverdue(new Date('2026-10-17')));
421 {"$type":"Project","value":{"name":"website","tasks":{"$type":"Map","v...
true true
true true 12000000000000000000n
true

Limitations to keep in mind: class names must be unique (minifiers may rename classes, so register with an explicit name if you bundle), ordinary data must not contain a $type key, and cycles still throw. If you need cycles, use v8.serialize or MessagePack with structuredClone: true, both shown below.

Versioning stored data

Data written today will be read by a newer version of your program. Store a version number next to the data and upgrade old data step by step when loading:

const CURRENT_VERSION = 3;

const migrations = {
  // v1 had a single "name" field
  1: (d) => {
    const [first, ...rest] = d.name.split(' ');
    const { name, ...other } = d;
    return { ...other, firstName: first, lastName: rest.join(' ') };
  },
  // v2 stored "age", v3 stores "birthYear"
  2: (d) => {
    const { age, ...other } = d;
    return { ...other, birthYear: 2026 - age };
  },
};

function saveSettings(user) {
  return JSON.stringify({ version: CURRENT_VERSION, data: user });
}

function loadSettings(text) {
  let { version = 1, data } = JSON.parse(text);
  if (version > CURRENT_VERSION) {
    throw new Error(`data version ${version} is newer than this program`);
  }
  while (version < CURRENT_VERSION) {
    data = migrations[version](data);
    version++;
  }
  return data;
}

console.log(loadSettings('{"data":{"name":"Ada King Lovelace","age":36}}'));
console.log(loadSettings('{"version":2,"data":{"firstName":"Alan","lastName":"Turing","age":41}}'));
console.log(loadSettings(saveSettings({ firstName: 'Grace', lastName: 'Hopper', birthYear: 1906 })));
try {
  loadSettings('{"version":4,"data":{}}');
} catch (err) {
  console.log(err.message);
}
{ firstName: 'Ada', lastName: 'King Lovelace', birthYear: 1990 }
{ firstName: 'Alan', lastName: 'Turing', birthYear: 1985 }
{ firstName: 'Grace', lastName: 'Hopper', birthYear: 1906 }
data version 4 is newer than this program

Each migration only knows about one step, so you never have to write a converter from every old version to the newest one. Data without a version field is treated as version 1, which lets you add versioning to a format that didn't have it.

structuredClone

structuredClone() uses the HTML structured clone algorithm, the same one used by postMessage(). It doesn't produce bytes; it produces a deep copy. It supports far more types than JSON and keeps shared references and cycles:

const shared = { name: 'shared' };
const original = {
  when: new Date('2026-10-17T12:00:00Z'),
  pattern: /ab+c/gi,
  big: 2n ** 64n,
  missing: undefined,
  scores: new Map([['alice', 10]]),
  ids: new Set([1, 2]),
  bytes: new Uint8Array([1, 2, 3]),
  a: shared,
  b: shared,
};
original.self = original;

const clone = structuredClone(original);
console.log(clone);
console.log(clone.a === clone.b, clone.self === clone, clone.a === shared);

const err = structuredClone(new RangeError('out of range', { cause: 42 }));
console.log(err instanceof RangeError, err.message, err.cause);
<ref *1> {
  when: 2026-10-17T12:00:00.000Z,
  pattern: /ab+c/gi,
  big: 18446744073709551616n,
  missing: undefined,
  scores: Map(1) { 'alice' => 10 },
  ids: Set(2) { 1, 2 },
  bytes: Uint8Array(3) [ 1, 2, 3 ],
  a: { name: 'shared' },
  b: { name: 'shared' },
  self: [Circular *1]
}
true true false
true out of range 42

clone.a and clone.b are still the same object, just not the original shared. JSON would have written shared twice and read back two different objects.

Some values can't be cloned at all, and some lose information silently:

const tries = {
  function: { fn: () => 1 },
  symbol: { s: Symbol('x') },
  promise: { p: Promise.resolve(1) },
  weakmap: { w: new WeakMap() },
};

for (const [name, value] of Object.entries(tries)) {
  try {
    structuredClone(value);
    console.log(name, 'ok');
  } catch (err) {
    console.log(name, err.name, '-', err.message);
  }
}

class Account {
  #pin = 1234;
  static kind = 'account';
  constructor(owner) {
    this.owner = owner;
  }
  get label() {
    return `account of ${this.owner}`;
  }
}

const copy = structuredClone({ acct: new Account('bob'), [Symbol('k')]: 1 });
console.log(copy, copy.acct.label);
function DataCloneError - () => 1 could not be cloned.
symbol DataCloneError - Symbol(x) could not be cloned.
promise DataCloneError - #<Promise> could not be cloned.
weakmap DataCloneError - #<WeakMap> could not be cloned.
{ acct: { owner: 'bob' } } undefined

Functions, symbols, promises and weak collections throw a DataCloneError. Class instances become plain objects: the prototype, getters, private fields and symbol-keyed properties are gone.

Large binary data can be moved instead of copied with the transfer option. The original ArrayBuffer becomes detached (length 0) and the clone takes over its memory:

const buffer = new ArrayBuffer(16 * 1024 * 1024);
const msg = { id: 1, payload: buffer };

const moved = structuredClone(msg, { transfer: [buffer] });
console.log(moved.payload.byteLength, buffer.byteLength, buffer.detached);
16777216 0 true

v8.serialize and v8.deserialize

The node:v8 module exposes the serializer behind structuredClone() and returns the bytes as a Buffer. You can write them to a file or a cache and read them back later:

import v8 from 'node:v8';
import { writeFile, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

const state = {
  savedAt: new Date('2026-10-17T12:00:00Z'),
  users: new Map([[1, { name: 'alice', roles: new Set(['admin']) }]]),
  counter: 2n ** 70n,
  avatar: Buffer.from('89504e47', 'hex'),
};

const bytes = v8.serialize(state);
console.log(Buffer.isBuffer(bytes), bytes.length);

const file = join(tmpdir(), 'state.bin');
await writeFile(file, bytes);

const restored = v8.deserialize(await readFile(file));
console.log(restored);
console.log(Buffer.isBuffer(restored.avatar));
await rm(file);
true 110
{
  savedAt: 2026-10-17T12:00:00.000Z,
  users: Map(1) { 1 => { name: 'alice', roles: [Set] } },
  counter: 1180591620717411303424n,
  avatar: <Buffer 89 50 4e 47>
}
true

Node's default serializer also restores Buffer objects as Buffer, not just Uint8Array.

The format is V8's internal format. The data starts with a version header (ff 0f in Node.js 24), and V8 can read older versions, but there's no promise that an older Node.js can read data written by a newer one, and nothing outside V8 can read it. Use it for caches and short-lived files that the same program reads back, not for long-term storage or data exchange.

It's also not automatically faster than JSON. For plain objects, V8's JSON implementation is very optimized:

import v8 from 'node:v8';

const rows = Array.from({ length: 100_000 }, (_, i) => ({
  id: i,
  name: `user${i}`,
  score: i * 1.5,
  active: i % 2 === 0,
}));

function time(label, fn) {
  const start = performance.now();
  const result = fn();
  console.log(label.padEnd(16), `${(performance.now() - start).toFixed(1)} ms`);
  return result;
}

const json = time('JSON.stringify', () => JSON.stringify(rows));
time('JSON.parse', () => JSON.parse(json));
const bin = time('v8.serialize', () => v8.serialize(rows));
time('v8.deserialize', () => v8.deserialize(bin));
time('structuredClone', () => structuredClone(rows));

console.log('JSON bytes:', Buffer.byteLength(json), ' v8 bytes:', bin.length);
JSON.stringify   14.0 ms
JSON.parse       27.3 ms
v8.serialize     13.8 ms
v8.deserialize   45.2 ms
structuredClone  53.8 ms
JSON bytes: 6153706  v8 bytes: 5280645

Exact numbers vary between runs and machines, but the picture is typical: the V8 format is slightly smaller, and reading it back is slower than JSON.parse. Choose v8.serialize because it supports more types, not for speed.

Sending objects to workers and child processes

worker.postMessage() uses structured clone, so dates, maps, BigInts and typed arrays arrive intact in a worker thread:

import { Worker } from 'node:worker_threads';

const worker = new Worker(
  `
  const { parentPort } = require('node:worker_threads');
  parentPort.on('message', (msg) => {
    parentPort.postMessage({
      year: msg.when.getUTCFullYear(),
      total: [...msg.prices.values()].reduce((a, b) => a + b, 0n),
    });
  });
  `,
  { eval: true },
);

worker.postMessage({
  when: new Date('2026-10-17T00:00:00Z'),
  prices: new Map([['a', 10n], ['b', 32n]]),
});

worker.once('message', (reply) => {
  console.log(reply);
  worker.terminate();
});
{ year: 2026, total: 42n }

The IPC channel of child_process.fork() uses JSON by default. Pass serialization: 'advanced' to switch it to the V8 serializer:

import { fork } from 'node:child_process';

if (process.argv[2] === 'child') {
  process.on('message', (msg) => {
    process.send({ type: typeof msg.when, isMap: msg.tags instanceof Map });
    process.disconnect();
  });
} else {
  for (const serialization of ['json', 'advanced']) {
    const child = fork(import.meta.filename, ['child'], { serialization });
    child.send({ when: new Date(0), tags: new Map([['a', 1]]) });
    const reply = await new Promise((resolve) => child.once('message', resolve));
    console.log(serialization.padEnd(8), reply);
  }
}
json     { type: 'string', isMap: false }
advanced { type: 'object', isMap: true }

With JSON the date arrives as a string and the map as {}. Both processes run the same Node.js binary, so the V8 format's version limits don't matter here.

A custom binary format with Buffer

When you control both sides and the records have a fixed structure, such as sensor data, log entries or game state sent many times per second, a hand-written binary layout is compact and fast. Buffer has read and write methods for every integer and floating-point size, and each write* method returns the offset just after the written value:

// Layout of one reading (little-endian):
//   u32 sensorId | f64 value | i64 timestamp (ms) | u16 nameLen | name (UTF-8)
function encodeReadings(readings) {
  const names = readings.map((r) => Buffer.from(r.name, 'utf8'));
  const size = 4 + names.reduce((sum, n) => sum + 4 + 8 + 8 + 2 + n.length, 0);
  const buf = Buffer.alloc(size);

  let off = buf.writeUInt32LE(readings.length, 0);
  readings.forEach((r, i) => {
    off = buf.writeUInt32LE(r.sensorId, off);
    off = buf.writeDoubleLE(r.value, off);
    off = buf.writeBigInt64LE(BigInt(r.at.getTime()), off);
    off = buf.writeUInt16LE(names[i].length, off);
    off += names[i].copy(buf, off);
  });
  return buf;
}

function decodeReadings(buf) {
  const count = buf.readUInt32LE(0);
  const readings = [];
  let off = 4;
  for (let i = 0; i < count; i++) {
    const sensorId = buf.readUInt32LE(off);
    const value = buf.readDoubleLE(off + 4);
    const at = new Date(Number(buf.readBigInt64LE(off + 12)));
    const nameLen = buf.readUInt16LE(off + 20);
    const name = buf.toString('utf8', off + 22, off + 22 + nameLen);
    off += 22 + nameLen;
    readings.push({ sensorId, value, at, name });
  }
  return readings;
}

const readings = [
  { sensorId: 7, value: 21.5, at: new Date('2026-10-17T08:00:00Z'), name: 'kitchen' },
  { sensorId: 9, value: -3.25, at: new Date('2026-10-17T08:00:05Z'), name: 'garage ❄' },
];

const buf = encodeReadings(readings);
console.log(buf.length, 'bytes vs', Buffer.byteLength(JSON.stringify(readings)), 'bytes of JSON');
console.log(decodeReadings(buf));
65 bytes vs 159 bytes of JSON
[
  {
    sensorId: 7,
    value: 21.5,
    at: 2026-10-17T08:00:00.000Z,
    name: 'kitchen'
  },
  {
    sensorId: 9,
    value: -3.25,
    at: 2026-10-17T08:00:05.000Z,
    name: 'garage ❄'
  }
]

Things to get right with binary formats:

MessagePack

MessagePack is a binary format with the same data model as JSON plus binary data, timestamps and application-defined extension types. Libraries exist for most languages, so it's a good choice for compact data exchange. The fastest Node.js implementation is the msgpackr package (npm install msgpackr):

import { pack, unpack } from 'msgpackr';

const order = {
  id: 1001,
  customer: 'alice',
  createdAt: new Date('2026-10-17T12:00:00Z'),
  items: [
    { sku: 'A-100', qty: 2, price: 19.9 },
    { sku: 'B-200', qty: 1, price: 5.5 },
  ],
  tags: new Set(['priority']),
};

const bytes = pack(order);
console.log(bytes.length, 'bytes vs', Buffer.byteLength(JSON.stringify(order)), 'bytes of JSON');
console.log(unpack(bytes));
128 bytes vs 162 bytes of JSON
{
  id: 1001,
  customer: 'alice',
  createdAt: 2026-10-17T12:00:00.000Z,
  items: [
    { sku: 'A-100', qty: 2, price: 19.9 },
    { sku: 'B-200', qty: 1, price: 5.5 }
  ],
  tags: [ 'priority' ]
}

Dates survive as MessagePack timestamps. A Set becomes an array by default. Create a Packr with structuredClone: true to keep sets, maps and cycles (this uses msgpackr-specific extensions that other MessagePack libraries won't understand):

import { Packr } from 'msgpackr';

const packr = new Packr({ structuredClone: true });
const data = { tags: new Set(['priority']), byId: new Map([[1, 'alice']]) };
data.self = data;

const copy = packr.unpack(packr.pack(data));
console.log(copy, copy.self === copy);
<ref *1> {
  tags: Set(1) { 'priority' },
  byId: Map(1) { 1 => 'alice' },
  self: [Circular *1]
} true

Extension types let you round-trip your own classes. You give each class a type number and functions to convert to and from serializable data:

import { Packr, addExtension } from 'msgpackr';

class Money {
  constructor(cents, currency) {
    this.cents = cents;
    this.currency = currency;
  }
  toString() {
    return `${(this.cents / 100).toFixed(2)} ${this.currency}`;
  }
}

addExtension({
  Class: Money,
  type: 1, // application-defined extension type, 1-100
  write: (m) => [m.cents, m.currency],
  read: ([cents, currency]) => new Money(cents, currency),
});

const packr = new Packr();
const bytes = packr.pack({ total: new Money(4530, 'EUR') });
const { total } = packr.unpack(bytes);
console.log(bytes.length, total instanceof Money, `${total}`);
21 true 45.30 EUR

For strictly typed data shared across many services, schema-based formats like Protocol Buffers (protobufjs) or Avro add field-level versioning rules on top of a compact encoding.

Security: deserializing untrusted data

Deserialization is a common source of vulnerabilities. Rules worth following:

A subtle problem is prototype pollution. JSON.parse creates a normal own property named __proto__, which is harmless by itself, but a naive deep merge copies it with an assignment, and assigning to target.__proto__ modifies Object.prototype:

function merge(target, source) {
  for (const key of Object.keys(source)) {
    if (typeof source[key] === 'object' && source[key] !== null) {
      target[key] ??= {};
      merge(target[key], source[key]);
    } else {
      target[key] = source[key];
    }
  }
  return target;
}

const input = JSON.parse('{"theme":"dark","__proto__":{"isAdmin":true}}');
console.log(Object.keys(input));

merge({}, input);
const user = {};
console.log(user.isAdmin);
[ 'theme', '__proto__' ]
true

After one merge of user input, every object in the process has isAdmin === true. Skip the dangerous keys and only recurse into objects the target owns:

function safeMerge(target, source) {
  for (const key of Object.keys(source)) {
    if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
    const value = source[key];
    if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
      if (!Object.hasOwn(target, key)) target[key] = Object.create(null);
      safeMerge(target[key], value);
    } else {
      target[key] = value;
    }
  }
  return target;
}

const input = JSON.parse('{"theme":"dark","__proto__":{"isAdmin":true}}');
const settings = safeMerge({}, input);
console.log(settings, ({}).isAdmin);
{ theme: 'dark' } undefined

Node.js also has a --disable-proto=delete flag that removes the __proto__ accessor entirely, which blocks this whole class of bugs if your dependencies don't rely on it.

Choosing a format

Summary

Task Code
control JSON output of a class toJSON() { return {...}; }
rebuild a class from JSON static fromJSON(data) { ... return new Cls(...); }
instance without running the constructor Object.assign(Object.create(Cls.prototype), data)
original value in a replacer function (key, value) { const v = this[key]; ... }
deep copy with Date, Map, Set, cycles structuredClone(value)
move an ArrayBuffer structuredClone(value, { transfer: [buf] })
object to bytes (V8 format) v8.serialize(value)
bytes to object (V8 format) v8.deserialize(buffer)
rich IPC with a child process fork(file, args, { serialization: 'advanced' })
write a 32-bit int to a buffer off = buf.writeUInt32LE(n, off)
MessagePack pack(value) / unpack(bytes) from msgpackr
MessagePack with Set, Map, cycles new Packr({ structuredClone: true })

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents