Serialize JavaScript to a superset of JSON that includes regular expressions and functions.
Installations
npm install serialize-javascript
Score
99.7
Supply Chain
100
Quality
80.6
Maintenance
100
Vulnerability
100
License
Developer
yahoo
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
No
Node Version
20.10.0
NPM Version
10.2.3
Statistics
2,829 Stars
158 Commits
182 Forks
37 Watching
2 Branches
37 Contributors
Updated on 28 Nov 2024
Languages
JavaScript (100%)
Total Downloads
Cumulative downloads
Total Downloads
7,617,018,282
Last day
-22.7%
6,057,041
Compared to previous day
Last week
-4.7%
40,241,923
Compared to previous week
Last month
7.1%
171,922,761
Compared to previous month
Last year
-4.1%
1,876,484,309
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Serialize JavaScript
Serialize JavaScript to a superset of JSON that includes regular expressions, dates and functions.
Overview
The code in this package began its life as an internal module to express-state. To expand its usefulness, it now lives as serialize-javascript
— an independent package on npm.
You're probably wondering: What about JSON.stringify()
!? We've found that sometimes we need to serialize JavaScript functions, regexps, dates, sets or maps. A great example is a web app that uses client-side URL routing where the route definitions are regexps that need to be shared from the server to the client. But this module is also great for communicating between node processes.
The string returned from this package's single export function is literal JavaScript which can be saved to a .js
file, or be embedded into an HTML document by making the content of a <script>
element.
HTML characters and JavaScript line terminators are escaped automatically.
Please note that serialization for ES6 Sets & Maps requires support for Array.from
(not available in IE or Node < 0.12), or an Array.from
polyfill.
Installation
Install using npm:
1$ npm install serialize-javascript
Usage
1var serialize = require('serialize-javascript'); 2 3serialize({ 4 str : 'string', 5 num : 0, 6 obj : {foo: 'foo'}, 7 arr : [1, 2, 3], 8 bool : true, 9 nil : null, 10 undef: undefined, 11 inf : Infinity, 12 date : new Date("Thu, 28 Apr 2016 22:02:17 GMT"), 13 map : new Map([['hello', 'world']]), 14 set : new Set([123, 456]), 15 fn : function echo(arg) { return arg; }, 16 re : /([^\s]+)/g, 17 big : BigInt(10), 18 url : new URL('https://example.com/'), 19});
The above will produce the following string output:
1'{"str":"string","num":0,"obj":{"foo":"foo"},"arr":[1,2,3],"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":new RegExp("([^\\\\s]+)", "g"),"big":BigInt("10"),"url":new URL("https://example.com/")}'
Note: to produce a beautified string, you can pass an optional second argument to serialize()
to define the number of spaces to be used for the indentation.
Automatic Escaping of HTML Characters
A primary feature of this package is to serialize code to a string of literal JavaScript which can be embedded in an HTML document by adding it as the contents of the <script>
element. In order to make this safe, HTML characters and JavaScript line terminators are escaped automatically.
1serialize({ 2 haxorXSS: '</script>' 3});
The above will produce the following string, HTML-escaped output which is safe to put into an HTML document as it will not cause the inline script element to terminate:
1'{"haxorXSS":"\\u003C\\u002Fscript\\u003E"}'
You can pass an optional
unsafe
argument toserialize()
for straight serialization.
Options
The serialize()
function accepts an options
object as its second argument. All options are being defaulted to undefined
:
options.space
This option is the same as the space
argument that can be passed to JSON.stringify
. It can be used to add whitespace and indentation to the serialized output to make it more readable.
1serialize(obj, {space: 2});
options.isJSON
This option is a signal to serialize()
that the object being serialized does not contain any function or regexps values. This enables a hot-path that allows serialization to be over 3x faster. If you're serializing a lot of data, and know its pure JSON, then you can enable this option for a speed-up.
Note: That when using this option, the output will still be escaped to protect against XSS.
1serialize(obj, {isJSON: true});
options.unsafe
This option is to signal serialize()
that we want to do a straight conversion, without the XSS protection. This options needs to be explicitly set to true
. HTML characters and JavaScript line terminators will not be escaped. You will have to roll your own.
1serialize(obj, {unsafe: true});
options.ignoreFunction
This option is to signal serialize()
that we do not want serialize JavaScript function.
Just treat function like JSON.stringify
do, but other features will work as expected.
1serialize(obj, {ignoreFunction: true});
Deserializing
For some use cases you might also need to deserialize the string. This is explicitly not part of this module. However, you can easily write it yourself:
1function deserialize(serializedJavascript){ 2 return eval('(' + serializedJavascript + ')'); 3}
Note: Don't forget the parentheses around the serialized javascript, as the opening bracket {
will be considered to be the start of a body.
License
This software is free to use under the Yahoo! Inc. BSD license. See the LICENSE file for license text and copyright information.
Stable Version
The latest stable version of the package.
Stable Version
6.0.2
HIGH
1
8.1/10
Summary
Insecure serialization leading to RCE in serialize-javascript
Affected Versions
< 3.1.0
Patched Versions
3.1.0
MODERATE
1
4.2/10
Summary
Cross-Site Scripting in serialize-javascript
Affected Versions
< 2.1.1
Patched Versions
2.1.1
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Warn: project license file does not contain an FSF or OSI license.
Reason
3 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-4q6p-r6v2-jvc5
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
Reason
Found 5/8 approved changesets -- score normalized to 6
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/yahoo/serialize-javascript/test.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/yahoo/serialize-javascript/test.yml/main?enable=pin
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 1 out of 1 npmCommand dependencies pinned
Reason
3 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 2
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/test.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 28 are checked with a SAST tool
Score
4.5
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More