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-javascriptVerified import paths — ran on the pinned version, not inferred.
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.
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`).
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.
Upgrade to `serialize-javascript` version 7.0.3 or later to mitigate this code injection vulnerability.
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.
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.
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.
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.
For ESM, use `import serialize from 'serialize-javascript';`. For CommonJS, use `const serialize = require('serialize-javascript');`.Use `serialize-javascript` instead of `JSON.stringify()` when needing to preserve functions, regexps, dates, maps, sets, BigInt, or URLs during serialization.
No dependency data recorded yet.