serialize-javascript
Serializes JavaScript values into safe, parseable code for embedding in HTML or scripts, with XSS escaping options.
Official Documentation ↗v7.1.4. Check the official docs for the latest API surface.Installation
npm install serialize-javascriptpnpm add serialize-javascriptMethods
No methods match this filter.
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.
- Note: That when using this option, the output will still be escaped to protect against XSS. (https://github.com/yahoo/serialize-javascript)
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.
Report a problem with this API docOpens a pre-filled issue on GitHub.