Serialize JavaScript Values

7.0.5 · active · verified Sun Apr 19

serialize-javascript is a utility library designed to convert JavaScript values, including complex types like functions, regular expressions, dates, Maps, Sets, BigInt, and URLs, into a string representation that is a superset of JSON. This serialized string is valid literal JavaScript code, suitable for embedding directly into HTML `<script>` tags or saving as `.js` files. Unlike `JSON.stringify()`, it gracefully handles these non-JSON-native types and automatically escapes HTML characters and JavaScript line terminators to prevent Cross-Site Scripting (XSS) vulnerabilities when embedded in HTML. The package is actively maintained, with the current stable version being 7.0.5, and typically sees regular maintenance updates and major version releases as needed. It originated as an internal module for `express-state` before becoming an independent npm package.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to serialize a diverse JavaScript object, including functions, regular expressions, dates, Maps, Sets, BigInt, and URLs, into a JavaScript string. It also shows the automatic HTML character escaping and an example of how the serialized string could be evaluated (with caution) back into an object, illustrating the execution of serialized functions and regexes.

import serialize from 'serialize-javascript';

const dataToSerialize = {
    str  : 'hello world <script>',
    num  : 123.45,
    obj  : { key: 'value', nested: { foo: 'bar' } },
    arr  : [1, null, new Date(), /test/gi],
    bool : false,
    nil  : null,
    undef: undefined,
    inf  : Infinity,
    date : new Date('2023-10-27T10:00:00Z'),
    map  : new Map([['id', 1], ['name', 'Example']]),
    set  : new Set([10, 20, 30]),
    fn   : function greet(name) { return `Hello, ${name}!`; },
    re   : /^user_\d+$/i,
    big  : BigInt(9007199254740991n),
    url  : new URL('https://example.com/path?query=param&id=123'),
    nestedFunc: { action: () => console.log('This will be serialized') }
};

// Serialize with default options (pretty print with 2 spaces)
const serializedData = serialize(dataToSerialize, { space: 2 });
console.log('Serialized Data:\n', serializedData);

// Example of deserialization (requires eval, use with caution on untrusted input)
// In a real application, you would typically embed this in a script tag
// or use it in a server-side rendering context where the source is trusted.
try {
  const deserializedData = eval('(' + serializedData + ')');
  console.log('\nDeserialized Function Output:', deserializedData.fn('Registry'));
  console.log('Deserialized Regex Test:', deserializedData.re.test('user_123'));
} catch (e) {
  console.error('\nError during deserialization:', e.message);
}

view raw JSON →