0
# Serialize JavaScript
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: serialize-javascript
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install serialize-javascript`
10
11
## Core Imports
12
13
```javascript
14
const serialize = require('serialize-javascript');
15
```
16
17
For ES modules (requires compatible bundler or transpilation):
18
19
```javascript
20
import serialize from 'serialize-javascript';
21
```
22
23
## Basic Usage
24
25
```javascript
26
const serialize = require('serialize-javascript');
27
28
// Serialize complex JavaScript objects
29
const result = serialize({
30
str: 'string',
31
num: 42,
32
bool: true,
33
nil: null,
34
undef: undefined,
35
inf: Infinity,
36
date: new Date("2016-04-28T22:02:17.000Z"),
37
map: new Map([['hello', 'world']]),
38
set: new Set([123, 456]),
39
fn: function echo(arg) { return arg; },
40
re: /([^\s]+)/g,
41
big: BigInt(10),
42
url: new URL('https://example.com/')
43
});
44
45
// Safe for embedding in HTML
46
const htmlSafe = serialize({ script: '</script>' });
47
// Result: '{"script":"\\u003C\\u002Fscript\\u003E"}'
48
```
49
50
## Architecture
51
52
Serialize JavaScript uses a sophisticated multi-phase approach to handle complex JavaScript types:
53
54
- **Placeholder System**: Complex types (functions, regexps, dates, etc.) are replaced with unique placeholder strings during JSON.stringify()
55
- **Type Preservation**: Each type has a specific placeholder pattern with unique identifiers to prevent collisions
56
- **String Replacement**: After JSON stringification, placeholders are replaced with executable JavaScript representations
57
- **Security Layer**: HTML characters and line terminators are automatically escaped unless explicitly disabled
58
- **UID Generation**: Uses cryptographically random UIDs to make placeholder patterns unpredictable and secure
59
60
## Capabilities
61
62
### JavaScript Serialization
63
64
Converts JavaScript objects to executable JavaScript strings, supporting complex types beyond JSON.
65
66
```javascript { .api }
67
/**
68
* Serializes JavaScript objects to a superset of JSON
69
* @param {any} obj - The object to serialize
70
* @param {SerializeOptions|number|string} [options] - Serialization options or space for indentation (legacy)
71
* @returns {string} JavaScript code representation of the serialized object
72
* @throws {TypeError} When attempting to serialize native functions
73
*/
74
module.exports = function serialize(obj, options);
75
```
76
77
### Serialization Options
78
79
Configure serialization behavior with comprehensive options for security, performance, and formatting.
80
81
```javascript { .api }
82
interface SerializeOptions {
83
/** Number of spaces (0-10) or string for indentation (same as JSON.stringify space parameter) */
84
space?: number | string;
85
86
/** Optimize for pure JSON objects - enables 3x faster serialization when true */
87
isJSON?: boolean;
88
89
/** Skip XSS protection escaping when explicitly set to true (dangerous - use with caution) */
90
unsafe?: boolean;
91
92
/** Exclude functions from serialization - functions become undefined (treat like JSON.stringify) */
93
ignoreFunction?: boolean;
94
}
95
```
96
97
**Usage Examples:**
98
99
```javascript
100
const serialize = require('serialize-javascript');
101
102
// Pretty printing with indentation
103
const formatted = serialize(data, { space: 2 });
104
105
// Fast path for pure JSON data
106
const jsonOnly = serialize(data, { isJSON: true });
107
108
// Exclude functions
109
const noFunctions = serialize(data, { ignoreFunction: true });
110
111
// Disable XSS protection (use with caution)
112
const unsafe = serialize(data, { unsafe: true });
113
114
// Legacy space parameter (backwards compatibility)
115
const legacy = serialize(data, 2);
116
const legacyString = serialize(data, '\t'); // Tab indentation
117
```
118
119
## Supported Data Types
120
121
The serialize function handles all standard JavaScript types and many complex types that JSON.stringify() cannot process:
122
123
**JSON-Compatible Types:**
124
- `string`, `number`, `boolean`, `null`
125
- Arrays and objects
126
127
**Extended JavaScript Types:**
128
- `undefined` - serialized as literal `undefined`
129
- `Infinity` and `-Infinity` - preserved as literal values
130
- `NaN` - preserved as literal value
131
- `Date` objects - serialized as `new Date("ISO string")`
132
- `RegExp` objects - serialized as `new RegExp(source, "flags")`
133
- `Function` objects - serialized with full function body (arrow, async, generator functions supported)
134
- `Map` objects - serialized as `new Map([entries])`
135
- `Set` objects - serialized as `new Set([values])`
136
- `BigInt` values - serialized as `BigInt("value")`
137
- `URL` objects - serialized as `new URL("url")`
138
- Sparse arrays - properly handled with correct length and holes
139
140
## Security Features
141
142
Automatic protection against XSS attacks and injection vulnerabilities when embedding serialized data in HTML documents.
143
144
**HTML Character Escaping:**
145
- `<` becomes `\u003C`
146
- `>` becomes `\u003E`
147
- `/` becomes `\u002F`
148
149
**JavaScript Line Terminator Escaping:**
150
- `\u2028` (Line Separator) - properly escaped
151
- `\u2029` (Paragraph Separator) - properly escaped
152
153
**Function Security:**
154
- Native functions (e.g., `Math.max`) throw `TypeError` to prevent security issues
155
- User-defined functions are safely serialized with their complete source code
156
157
```javascript
158
// Safe embedding in HTML
159
const data = { script: '</script><script>alert("xss")</script>' };
160
const safe = serialize(data);
161
// Result: '{"script":"\\u003C\\u002Fscript\\u003E\\u003Cscript\\u003Ealert(\\"xss\\")\\u003C\\u002Fscript\\u003E"}'
162
```
163
164
## Error Handling
165
166
```javascript { .api }
167
/**
168
* TypeError thrown when attempting to serialize native functions
169
* Native functions (like Math.max, Array.prototype.slice) cannot be safely serialized
170
* and will throw this error to prevent security vulnerabilities
171
*
172
* @example
173
* serialize(Math.max) // Throws: TypeError: Serializing native function: max
174
* serialize({fn: Array.prototype.slice}) // Throws: TypeError: Serializing native function: slice
175
*/
176
class TypeError extends Error {
177
/** Error message in format: "Serializing native function: <function_name>" */
178
message: string;
179
/** Standard error name property */
180
name: 'TypeError';
181
}
182
```
183
184
**Common Error Scenarios:**
185
- Attempting to serialize native/built-in functions (`Math.max`, `Array.prototype.slice`, etc.)
186
- Functions with `[native code]` in their string representation
187
- Built-in browser APIs and Node.js core module functions
188
189
## Compatibility Requirements
190
191
- **ES6 Sets & Maps**: Require `Array.from` support (Node.js >= 0.12 or polyfill for older environments)
192
- **Browser Support**: Depends on JavaScript features used in serialized code
193
- **Dependencies**: `randombytes` (^2.1.0) for internal UID generation