Serialize JavaScript Objects

3.1.2 · active · verified Sun Apr 19

serialize-to-js is a utility library for converting JavaScript objects into a string representation that can be safely evaluated as JavaScript code. Unlike `JSON.stringify`, it supports a wider range of JavaScript types including `RegExp`, `Date`, `Buffer`, `Set`, `Map`, `Error`, and various `TypedArray` types, while also handling circular references. The current stable version is 3.1.2. The library primarily focuses on robust serialization to executable JavaScript strings and has undergone breaking changes to enhance security, notably by removing the `deserialize` function in v2.0.0 due to Denial-of-Service vulnerabilities. It is particularly useful for scenarios requiring the exact re-creation of JavaScript objects, including their methods and non-primitive types, in environments where `eval` can be controlled.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to serialize a complex JavaScript object, including various primitive types, objects, arrays, regular expressions, dates, buffers, sets, and maps, into a JavaScript string. It shows the output format and hints at how to (cautiously) deserialize it.

import serialize from 'serialize-to-js';

const obj = {
  str: '<script>var a = 0 > 1</script>',
  num: 3.1415,
  bool: true,
  nil: null,
  undef: undefined,
  obj: { foo: 'bar' },
  arr: [1, '2'],
  regexp: /^test?$/,
  date: new Date('2023-01-15T10:00:00.000Z'), // Consistent date for example
  buffer: Buffer.from('data'), // Requires Node.js Buffer or polyfill
  set: new Set([1, 2, 3]),
  map: new Map([['a', 1], ['b', 2]])
};

const serializedString = serialize(obj);
console.log(serializedString);

// To deserialize, one might use eval() in a controlled environment
// const deserializedObj = eval(`(${serializedString})`);
// console.log(deserializedObj.date instanceof Date); // true

view raw JSON →