Open-source project
yahoo/serialize-javascript avatar
yahoo/serialize-javascript

serialize-javascript escapes its output so a script tag cannot close early

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

2,925 stars222 forksJavaScriptLicense varies

At a glance

What is it?
serialize-javascript turns functions, regexps, dates, sets and maps into a string of literal JavaScript that can be saved to a file or dropped into a script element. The escaping that makes it safe is on by default, one flag turns it off, and the page's own warning is that a serialized function only survives if it is entirely self-contained.
Who is it for?
serialize-javascript fits the narrow job of moving server state to a browser when that state contains something JSON cannot express, such as a regular expression in a client-side route table. Three things to check before you depend on it.
Can I use it commercially?
Check first. The repository uses a licence we do not classify automatically, so read its LICENSE file before any commercial use.
Is it still maintained?
Yes. The repository last received commits 30 days ago.
What is it written in?
Mainly JavaScript, according to GitHub's language statistics.

Answers come from the project's GitHub data, last synced on November 25, 2026, and from our analysis. They are not legal advice.

From daily snapshots

Star history

  • yahoo/serialize-javascript2,925 ★ · +2
Star history
Repository2026-09-242026-11-25
yahoo/serialize-javascript2.9k2.9k

2 Stars in the last 62 days, measured from the daily GitHub snapshot. Compare with other projects

Editorial analysis

The escaping exists so a script tag cannot close early

The package's stated purpose is producing a superset of JSON that includes regular expressions, dates and functions, and the output is not JSON at all: it is literal JavaScript source, suitable for saving to a file with a JavaScript extension or for embedding into an HTML document as the content of a script element.

Embedding is the reason the escaping exists, and the page makes that the primary feature. HTML characters and JavaScript line terminators are escaped automatically, so the emitted string cannot terminate the inline script element that contains it. The demonstration is a single property whose value is a closing script tag:

js
serialize({
    haxorXSS: '</script>'
});

and the output has the angle bracket, the slash and the closing bracket replaced by their unicode escape forms, which is why the string can sit inside a script element without ending it.

The same treatment covers JavaScript line terminators, which matters for the same reason: a newline in the wrong place inside a script element is a syntax boundary rather than a string.

So the default behaviour of this package is defensive, and the escaping is not an option you opt into. It is the reason the package is safe to use with untrusted values at all.

One flag turns the escaping off, and the page hands you the responsibility

The escape hatch is a single option, and the page describes it in unusually blunt terms.

Setting unsafe to true signals that a straight conversion is wanted, without the cross-site scripting protection. HTML characters and JavaScript line terminators will not be escaped. And then the sentence that matters: you will have to roll your own.

Two things are worth noticing about how that is scoped. First, the flag must be explicitly set, so it cannot be turned on by accident through a truthy value from a configuration object. Second, it disables escaping for everything, not for one field, so a single unsafe payload in an otherwise trusted object still reaches the document unescaped.

The interaction with the other options is also stated rather than left to be discovered. The isJSON option promises the caller that the object holds no functions or regexps, and that promise buys a faster path; the note under it says the output will still be escaped to protect against cross-site scripting. So the fast path does not weaken the guarantee, and only the explicitly named unsafe flag does.

BigInt comes out as a string and Date comes out normalised

The usage example is worth reading as a table of conversions, because the output string shows exactly what each input type becomes.

Strings, numbers, booleans and null come out as ordinary literals, and the array comes out as an array literal. Infinity is emitted as the bare identifier, and undefined as the bare identifier too, which is not valid JSON but is valid JavaScript and is exactly the reason this package exists. A date is emitted as a constructor call with an ISO 8601 timestamp, normalised from whatever form it was created in, so the sample input written as a date string comes out as an ISO string inside a constructor call. A map and a set are emitted as constructor calls with their contents as literals.

Two entries are the interesting ones. A regular expression comes out as a constructor call with its source and flags as two string arguments, with the source's own backslashes escaped for the extra layer of nesting. A big integer comes out as a constructor call whose argument is a quoted string rather than a numeric literal.

A function comes out as its source text, which is the one conversion in the list with no way of checking that what came back is what went in.

A serialized function only works if it is entirely self-contained

The page carries a warning about worker threads, and it is the most important paragraph in the documentation.

It starts by naming the temptation: it may be tempting to use this package to pass arbitrary functions into a worker thread, since functions cannot be passed directly through the structured clone that post message uses. Then it states the limit plainly. Passing functions between worker threads is not possible in the general case, this package lets you serialize some functions, and it has limitations.

The specific limitation is the closure problem. If a function references something from outside the function body, it will not run properly after being serialized and deserialized. The page names the two usual culprits: closed-over variables and imports from other packages. And then the requirement: for a serialized function to run properly, it must be entirely self-contained.

The closing lines rule out the general case twice. It is not possible to send arbitrary JavaScript to a worker thread and pretend it is running the way it would on the main thread, and this package does not let you do that.

So the feature that looks most powerful is the one with the sharpest precondition: the function body has to carry everything it needs, which in practice means no captured scope and no imports.

Deserialization is not in the module, and the page hands you an eval

The page is explicit that deserialization is not part of this module. For some use cases you might need to deserialize the string, and the way to do that is to write it yourself. The version it suggests is a short function that uses eval on the serialized string, wrapped in parentheses.

The note attached to it explains why the parentheses matter: without them, the opening curly brace of the serialized object is read as the start of a body rather than the start of an expression, so the result is not the object you expected.

This is worth sitting with for a moment, because it is where the security boundary of the whole package sits. The escaping protects the output string against being terminated early inside a script element. What happens to that string afterwards is entirely in the reader's hands, and the reader's code is an eval. The two halves of the round trip therefore have very different risk profiles, and the package only addresses the first one.

One source file, no runtime dependencies, and a built-in test runner

The manifest describes a package with a very small surface. The main entry is a single file called index.js, there are no runtime dependencies at all, and the only development dependency is a benchmarking library.

The scripts are two. One runs the benchmark, and it starts by printing the node version before running a benchmark script from the test directory, so a benchmark result always carries the runtime it was produced on. The other runs the tests, and it uses the test runner built into Node against a glob of unit test files, with no third-party test framework in the list.

The engines field requires Node 20.0.0 or newer. That is a recent floor for a package whose stated purpose includes serving state to a browser, and it is the one hard compatibility statement in the manifest.

The repository root matches the manifest: a GitHub directory, the ignore files, the licence, the readme, the one source file, the lock file, the manifest and a test directory. There is no lint configuration, no formatter configuration and no type definitions, so nothing in the repository describes a style the code is expected to follow beyond what the readme shows.

Three of the four options are promises, not settings

The options object is the second argument to the serialization function, and the page says all options default to undefined. Four are documented, and read as a group they fall into two kinds.

One is a setting. The space option is the same argument that can be passed to the native JSON stringifier, used to add whitespace and indentation to the output; the page also mentions that an optional second argument can define the number of spaces, which is the same thing described earlier in the usage section.

Three are signals from the caller rather than output formatting. isJSON asserts that the object being serialized contains no functions or regexps, and in exchange enables a faster path, described as over three times faster for large amounts of known-pure data. ignoreFunction tells the package to treat functions the way the native stringifier does, with the rest of the package's features still working. And unsafe asserts that the caller has its own escaping.

The README does not say the package checks the isJSON claim, so the option name describes what the caller knows rather than what the library will do.

It began as an internal module, and Sets and Maps need a polyfill

The origin story is in the overview section and it explains the design. The code began its life as an internal module to a state middleware package for Express, and it now lives as an independent package so it can be used outside that context.

The reason for existing at all is stated as a question and an answer: what about the native stringifier. Sometimes you need to serialize functions, regexps, dates, sets or maps, and the example given is a web application with client-side URL routing, where the route definitions are regular expressions that have to be shared from the server to the client. That is a narrow, concrete case.

There is one compatibility note attached to the modern types. Serializing ES6 sets and maps requires support for a particular array conversion function, which the page says is not available in one browser family or in Node before a particular version, so a polyfill is needed there.

The licence is described three ways: the page says the software is free to use under the Yahoo BSD licence and points at the licence file, the manifest declares the BSD-3-Clause identifier, and GitHub metadata reports NOASSERTION, so read the LICENSE file itself.

Editorial conclusion

serialize-javascript fits the narrow job of moving server state to a browser when that state contains something JSON cannot express, such as a regular expression in a client-side route table. Three things to check before you depend on it. Read the worker thread warning rather than the feature list, because the functions it serializes only come back intact when they are self-contained. Keep the escaping on, since the whole point of the output is that it can be embedded in a script element, and the flag that disables it is a promise you have to keep yourself. And write your own deserializer deliberately, because the module does not ship one and the page's version is an eval.

Frequently asked questions

what is serialize javascript

It is a package that serializes JavaScript to a superset of JSON which includes regular expressions, dates and functions. The string it returns is literal JavaScript that can be saved to a file or embedded into an HTML document as the contents of a script element, with HTML characters and line terminators escaped automatically.

What does serialize-javascript do that JSON.stringify does not?

It emits values the native stringifier cannot: functions as source text, regular expressions as constructor calls, dates as normalised ISO constructor calls, and sets and maps as constructor calls. undefined and Infinity are emitted as bare identifiers, which is why the output is JavaScript rather than JSON.

How do I deserialize the output of serialize-javascript?

Deserialization is explicitly not part of the module. The page suggests writing it yourself by wrapping the serialized string in parentheses and evaluating it, and warns that without the parentheses the opening brace is read as the start of a body rather than an expression.

Can I use serialize-javascript to send functions to a worker thread?

The page warns against it. Passing functions between worker threads is not possible in the general case, and a function that references anything outside its own body, such as a closed-over variable or an import from another package, will not run properly after a round trip. A serialized function has to be entirely self-contained.

What do the isJSON and unsafe options do?

isJSON tells the package the object holds no functions or regexps, which enables a faster path of over three times the speed, and the output is still escaped against cross-site scripting. unsafe must be set to true and turns that escaping off entirely, leaving the caller to do it, as the page puts it, rolling your own.

What Node version and dependencies does serialize-javascript need?

The manifest requires Node 20.0.0 or newer. The package has no runtime dependencies, its whole implementation is a single file called index.js, its only development dependency is a benchmarking library, and its tests run with the test runner built into Node.

Official sources

  1. Issues
  2. README
  3. Releases
  4. yahoo/serialize-javascript on GitHub
Add this badge to your README

If you maintain this project, the badge below links readers to this analysis and shows its maintenance status from the daily GitHub snapshot. Paste the markdown into your README; add ?metric=license or ?metric=stars to the image URL for a different field.

Add this badge to your README

markdown
[![Hysen Labs](https://hysenlabs.com/badge/yahoo-serialize-javascript.svg)](https://hysenlabs.com/projects/yahoo-serialize-javascript)

Star history chart for your README

markdown
[![Star history](https://hysenlabs.com/chart/yahoo-serialize-javascript.svg)](https://hysenlabs.com/projects/yahoo-serialize-javascript)

Was this useful?