Serialize JavaScript to a superset of JSON that includes regular expressions and functions.
npx @tessl/cli install tessl/npm-serialize-javascript@6.0.0Serialize JavaScript to a superset of JSON that includes regular expressions, dates, functions, and other complex JavaScript types that JSON.stringify() cannot handle. Includes automatic HTML character escaping for safe embedding in HTML documents, making it ideal for server-to-client data transfer in web applications.
npm install serialize-javascriptconst serialize = require('serialize-javascript');For ES modules (requires compatible bundler or transpilation):
import serialize from 'serialize-javascript';const serialize = require('serialize-javascript');
// Serialize complex JavaScript objects
const result = serialize({
str: 'string',
num: 42,
bool: true,
nil: null,
undef: undefined,
inf: Infinity,
date: new Date("2016-04-28T22:02:17.000Z"),
map: new Map([['hello', 'world']]),
set: new Set([123, 456]),
fn: function echo(arg) { return arg; },
re: /([^\s]+)/g,
big: BigInt(10),
url: new URL('https://example.com/')
});
// Safe for embedding in HTML
const htmlSafe = serialize({ script: '</script>' });
// Result: '{"script":"\\u003C\\u002Fscript\\u003E"}'Serialize JavaScript uses a sophisticated multi-phase approach to handle complex JavaScript types:
Converts JavaScript objects to executable JavaScript strings, supporting complex types beyond JSON.
/**
* Serializes JavaScript objects to a superset of JSON
* @param {any} obj - The object to serialize
* @param {SerializeOptions|number|string} [options] - Serialization options or space for indentation (legacy)
* @returns {string} JavaScript code representation of the serialized object
* @throws {TypeError} When attempting to serialize native functions
*/
module.exports = function serialize(obj, options);Configure serialization behavior with comprehensive options for security, performance, and formatting.
interface SerializeOptions {
/** Number of spaces (0-10) or string for indentation (same as JSON.stringify space parameter) */
space?: number | string;
/** Optimize for pure JSON objects - enables 3x faster serialization when true */
isJSON?: boolean;
/** Skip XSS protection escaping when explicitly set to true (dangerous - use with caution) */
unsafe?: boolean;
/** Exclude functions from serialization - functions become undefined (treat like JSON.stringify) */
ignoreFunction?: boolean;
}Usage Examples:
const serialize = require('serialize-javascript');
// Pretty printing with indentation
const formatted = serialize(data, { space: 2 });
// Fast path for pure JSON data
const jsonOnly = serialize(data, { isJSON: true });
// Exclude functions
const noFunctions = serialize(data, { ignoreFunction: true });
// Disable XSS protection (use with caution)
const unsafe = serialize(data, { unsafe: true });
// Legacy space parameter (backwards compatibility)
const legacy = serialize(data, 2);
const legacyString = serialize(data, '\t'); // Tab indentationThe serialize function handles all standard JavaScript types and many complex types that JSON.stringify() cannot process:
JSON-Compatible Types:
string, number, boolean, nullExtended JavaScript Types:
undefined - serialized as literal undefinedInfinity and -Infinity - preserved as literal valuesNaN - preserved as literal valueDate objects - serialized as new Date("ISO string")RegExp objects - serialized as new RegExp(source, "flags")Function objects - serialized with full function body (arrow, async, generator functions supported)Map objects - serialized as new Map([entries])Set objects - serialized as new Set([values])BigInt values - serialized as BigInt("value")URL objects - serialized as new URL("url")Automatic protection against XSS attacks and injection vulnerabilities when embedding serialized data in HTML documents.
HTML Character Escaping:
< becomes \u003C> becomes \u003E/ becomes \u002FJavaScript Line Terminator Escaping:
\u2028 (Line Separator) - properly escaped\u2029 (Paragraph Separator) - properly escapedFunction Security:
Math.max) throw TypeError to prevent security issues// Safe embedding in HTML
const data = { script: '</script><script>alert("xss")</script>' };
const safe = serialize(data);
// Result: '{"script":"\\u003C\\u002Fscript\\u003E\\u003Cscript\\u003Ealert(\\"xss\\")\\u003C\\u002Fscript\\u003E"}'/**
* TypeError thrown when attempting to serialize native functions
* Native functions (like Math.max, Array.prototype.slice) cannot be safely serialized
* and will throw this error to prevent security vulnerabilities
*
* @example
* serialize(Math.max) // Throws: TypeError: Serializing native function: max
* serialize({fn: Array.prototype.slice}) // Throws: TypeError: Serializing native function: slice
*/
class TypeError extends Error {
/** Error message in format: "Serializing native function: <function_name>" */
message: string;
/** Standard error name property */
name: 'TypeError';
}Common Error Scenarios:
Math.max, Array.prototype.slice, etc.)[native code] in their string representationArray.from support (Node.js >= 0.12 or polyfill for older environments)randombytes (^2.1.0) for internal UID generation