Registry / serialization / serialize-javascript

serialize-javascript

JSON →
library7.0.5jsnpmunverified

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.

npm install serialize-javascript
INSTALL
IMPORT
SIG · SERIALIZE-JAVASCRI
S
serialize-javascript
serializationjavascriptv7.0.5
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

serialize
import serialize from 'serialize-javascript';
import { serialize } from 'serialize-javascript';
The primary export is a default export, not a named one. While `require('serialize-javascript')` works for CommonJS, ESM users should use the default import.
serialize
const serialize = require('serialize-javascript');
const { serialize } = require('serialize-javascript');
For CommonJS, the module exports the `serialize` function directly as its default. Destructuring `require` will result in `undefined`.
serialize
import serialize from 'serialize-javascript'; // ... later usage ... const output = serialize(myObject, { unsafe: true });
import serialize from 'serialize-javascript'; // ... later usage ... const output = serialize(myObject, { is)unsafe: true });
The `unsafe` option, used to disable automatic HTML character escaping, is a boolean property and should be correctly spelled and cased. Misconfigurations can lead to XSS vulnerabilities.

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); }
Debug
Known issues
breakingVersion 7.0.0 introduced a breaking change by requiring Node.js v20.0.0 or greater. Projects running on older Node.js versions must upgrade Node.js or remain on `serialize-javascript` v6.x.
fix
Upgrade your Node.js environment to version 20.0.0 or higher. Alternatively, pin your `serialize-javascript` dependency to a `6.x` version (e.g., `^6.0.0`).
affects: >=7.0.0
breakingVersions prior to 3.1.0 were vulnerable to Remote Code Execution (RCE) via insecure deserialization, specifically related to the `deleteFunctions` within `index.js` (CVE-2020-7660). An attacker could inject arbitrary code by crafting malicious payloads.
fix
Upgrade to `serialize-javascript` version 3.1.0 or newer immediately. Note that versions 7.0.3 and later include further fixes for related RCE issues.
affects: <3.1.0
breakingVersions up to 7.0.2 were vulnerable to Code Injection (GHSA-5c6j-r48x-rmvq) due to incomplete sanitization of `RegExp.flags` and `Date.prototype.toISOString()` output. Attackers could inject malicious JavaScript via these properties if they controlled the input to `serialize()`, leading to RCE when the output was `eval()`ed or embedded in `<script>` tags. This was an incomplete fix for CVE-2020-7660.
fix
Upgrade to `serialize-javascript` version 7.0.3 or later to mitigate this code injection vulnerability.
affects: <7.0.3
gotchaVersions prior to 7.0.5 could lead to a Denial of Service (DoS) via CPU exhaustion when serializing specially crafted 'array-like' objects (objects inheriting from `Array.prototype` with a very large `length` property). This could cause the process to hang indefinitely.
fix
Upgrade to `serialize-javascript` version 7.0.5 or later. If upgrading is not immediately possible, thoroughly validate and sanitize all input, especially array-like objects, before passing them to the `serialize()` function.
affects: <7.0.5
gotchaWhile `serialize-javascript` can serialize functions, it is generally unsafe and strongly discouraged to use this package to pass arbitrary functions to worker threads. Serialized functions often rely on their surrounding scope (closed-over variables, imports), which are not serialized and will lead to unexpected runtime behavior or errors in a worker thread environment.
fix
Avoid passing arbitrary, non-self-contained functions to worker threads via this serialization method. For worker communication, prefer passing serializable data and defining logic directly within the worker.
affects: >=1.0.0
gotchaThe `unsafe` option can be passed to `serialize()` to disable automatic HTML character escaping. This bypasses a critical security feature designed to prevent XSS. Use this option only when the serialized output is guaranteed not to be embedded directly into HTML or when custom, external escaping is applied.
fix
Always use the default behavior (HTML escaping enabled) unless there's a specific, understood reason to disable it, and ensure adequate alternative sanitization for HTML contexts.
affects: >=1.0.0
Errors
Common errors & fixes
The engine "node" is incompatible with this module. Expected version "20.0.0" or higher.
Attempting to install or run `serialize-javascript` version 7.x or later on a Node.js environment older than v20.0.0.
fix
Upgrade your Node.js runtime to version 20.0.0 or newer. You can use tools like `nvm` (Node Version Manager) to manage multiple Node.js versions.
TypeError: serialize is not a function
Incorrectly importing the `serialize` function as a named import (`import { serialize } from 'serialize-javascript'`) when it is a default export, or attempting to destructure `require` in CommonJS.
fix
For ESM, use `import serialize from 'serialize-javascript';`. For CommonJS, use `const serialize = require('serialize-javascript');`.
SyntaxError: Unexpected token 'function'
Attempting to use `JSON.stringify()` on an object containing functions, regular expressions, or other non-JSON-standard JavaScript types. `JSON.stringify` does not serialize these types correctly, resulting in functions being omitted and regexps becoming empty objects.
fix
Use `serialize-javascript` instead of `JSON.stringify()` when needing to preserve functions, regexps, dates, maps, sets, BigInt, or URLs during serialization.
Upgrade
Version history
7.0.5latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
10 hits · last 30 days
node
8
Resources
serialize-javascript — npm install serialize-javascript · libregistry