or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-serialize-javascript

Serialize JavaScript to a superset of JSON that includes regular expressions and functions.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/serialize-javascript@6.0.x

To install, run

npx @tessl/cli install tessl/npm-serialize-javascript@6.0.0

index.mddocs/

Serialize JavaScript

Serialize 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.

Package Information

  • Package Name: serialize-javascript
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install serialize-javascript

Core Imports

const serialize = require('serialize-javascript');

For ES modules (requires compatible bundler or transpilation):

import serialize from 'serialize-javascript';

Basic Usage

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"}'

Architecture

Serialize JavaScript uses a sophisticated multi-phase approach to handle complex JavaScript types:

  • Placeholder System: Complex types (functions, regexps, dates, etc.) are replaced with unique placeholder strings during JSON.stringify()
  • Type Preservation: Each type has a specific placeholder pattern with unique identifiers to prevent collisions
  • String Replacement: After JSON stringification, placeholders are replaced with executable JavaScript representations
  • Security Layer: HTML characters and line terminators are automatically escaped unless explicitly disabled
  • UID Generation: Uses cryptographically random UIDs to make placeholder patterns unpredictable and secure

Capabilities

JavaScript Serialization

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);

Serialization 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 indentation

Supported Data Types

The serialize function handles all standard JavaScript types and many complex types that JSON.stringify() cannot process:

JSON-Compatible Types:

  • string, number, boolean, null
  • Arrays and objects

Extended JavaScript Types:

  • undefined - serialized as literal undefined
  • Infinity and -Infinity - preserved as literal values
  • NaN - preserved as literal value
  • Date 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")
  • Sparse arrays - properly handled with correct length and holes

Security Features

Automatic protection against XSS attacks and injection vulnerabilities when embedding serialized data in HTML documents.

HTML Character Escaping:

  • < becomes \u003C
  • > becomes \u003E
  • / becomes \u002F

JavaScript Line Terminator Escaping:

  • \u2028 (Line Separator) - properly escaped
  • \u2029 (Paragraph Separator) - properly escaped

Function Security:

  • Native functions (e.g., Math.max) throw TypeError to prevent security issues
  • User-defined functions are safely serialized with their complete source code
// 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"}'

Error Handling

/**
 * 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:

  • Attempting to serialize native/built-in functions (Math.max, Array.prototype.slice, etc.)
  • Functions with [native code] in their string representation
  • Built-in browser APIs and Node.js core module functions

Compatibility Requirements

  • ES6 Sets & Maps: Require Array.from support (Node.js >= 0.12 or polyfill for older environments)
  • Browser Support: Depends on JavaScript features used in serialized code
  • Dependencies: randombytes (^2.1.0) for internal UID generation