Serialize JavaScript Objects
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
-
TypeError: serialize(...).deserialize is not a function
cause Attempting to call the `deserialize` method which was removed in version 2.0.0 due to security vulnerabilities.fixRemove all calls to `deserialize`. The package no longer provides a direct deserialization function. If you need to re-create the object, consider using `eval()` in a secure, controlled context with trusted input, or implement a custom parser. -
ReferenceError: Buffer is not defined
cause This error typically occurs when `serialize-to-js` is used in a non-Node.js environment (e.g., browser) and attempts to serialize a `Buffer` object without a global `Buffer` polyfill being available.fixIf running in a browser, ensure you have a `Buffer` polyfill (e.g., `buffer` npm package) imported and made globally available, or avoid serializing `Buffer` objects in client-side code where `Buffer` is not native.
Warnings
- breaking The `deserialize` function was removed in version 2.0.0 due to being vulnerable to Denial-of-Service (DOS) attacks. Users upgrading from v1.x should refactor any usage of `deserialize`.
- gotcha The library serializes objects into a string that represents executable JavaScript code, not a data-interchange format like JSON. Deserializing this string typically requires `eval()`, which is a significant security risk if the source of the serialized string is untrusted.
- gotcha When using the `opts.reference = true` option, the library mutates the `opts` object by adding an `opts.references` array containing information about the created references. This side-effect can be unexpected.
Install
-
npm install serialize-to-js -
yarn add serialize-to-js -
pnpm add serialize-to-js
Imports
- serialize
import { serialize } from 'serialize-to-js';import serialize from 'serialize-to-js';
Quickstart
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