API Reference

serialize-javascript

Serializes JavaScript values into safe, parseable code for embedding in HTML or scripts, with XSS escaping options.

Official Documentation ↗
CompatibilityThis documentation covers version v7.1.4. Check the official docs for the latest API surface.

Installation

npmnpm install serialize-javascript
pnpmpnpm add serialize-javascript

Methods

Overview

serialize-javascript serializes JavaScript values into safe, parseable code for embedding in HTML or scripts, with XSS escaping by default. This reference lists the most frequently used APIs with accurate signatures and runnable snippets.

Core APIs

  • serialize — Converts a value into a JavaScript expression string, escaping unsafe characters by default.
  • isJSON option — Emits strict JSON text, which is safe for JSON.parse and for script type=“application/json” blocks.
  • unsafe option — Disables HTML-character escaping for contexts where the output is already trusted.

Example

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

const out = serialize({ id: 1, note: '</script>' });
console.log(out);

Notes

The unsafe option disables HTML escaping, so only use it for trusted contexts. Prefer isJSON when the consumer will call JSON.parse.

Verification

Serialize a string containing “” and confirm the output escapes it so the value cannot terminate the script element.

Security notes

Quoted from the official documentation (https://github.com/yahoo/serialize-javascript); this is not a complete threat model.

FAQ

How does it prevent XSS when embedding in HTML?
By default it escapes characters such as < and / in strings so serialized data cannot break out of a script element.
When should I use isJSON?
Use isJSON when the consumer will call JSON.parse, for example inside a type="application/json" script tag.
Why not use JSON.stringify directly?
JSON.stringify cannot represent functions, undefined, or RegExp, and does not escape HTML-sensitive characters for script embedding.