express-fast-json-stringify 1.2.9 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,53 +1,73 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.0.0](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.3.0...v2.0.0) (2026-09-20)
4
+
5
+ ### ⚠ BREAKING CHANGES
6
+
7
+ - install once on app.response, the middlewares only choose the schema and the string goes through res.send
8
+
9
+ ### Features
10
+
11
+ - add a landing page with links to fast-json and native-json endpoints ([882c2ed](https://github.com/nigrosimone/express-fast-json-stringify/commit/882c2ed6b191e059f49381be2abf0ca017474140))
12
+ - install once on app.response, the middlewares only choose the schema and the string goes through res.send ([83ab193](https://github.com/nigrosimone/express-fast-json-stringify/commit/83ab19300aad0d19c9e77288832f35c378a517bd))
13
+
14
+ ### Bug Fixes
15
+
16
+ - correct json settings check to avoid false negatives with falsy values ([bc13964](https://github.com/nigrosimone/express-fast-json-stringify/commit/bc139640fc7732dfb4081a8395d1260df83e6d51))
17
+
18
+ ## [1.3.0](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.2.9...v1.3.0) (2026-07-26)
19
+
20
+ ### Features
21
+
22
+ - derive the schema from an OpenAPI or Swagger document ([5ce6622](https://github.com/nigrosimone/express-fast-json-stringify/commit/5ce6622fd216df1074e844c254bef0c7731205cd))
23
+ - opt in override of res.json, so adoption needs no call site changes ([bcfda45](https://github.com/nigrosimone/express-fast-json-stringify/commit/bcfda4579ac8380f53c525b5cadcbc177e835b9c))
24
+
25
+ ### Bug Fixes
26
+
27
+ - align res.fastJson with res.json HTTP semantics; add CI and vitest ([f2c8558](https://github.com/nigrosimone/express-fast-json-stringify/commit/f2c85584c105ce24c6c7327382b6b80022aade10))
28
+
3
29
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
30
 
5
31
  ### [1.2.9](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.2.8...v1.2.9) (2026-01-18)
6
32
 
7
- ### [1.2.8](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.2.6...v1.2.8) (2024-09-29)
8
-
9
-
10
- ### Bug Fixes
11
-
12
- * global type ([56fa47c](https://github.com/nigrosimone/express-fast-json-stringify/commit/56fa47c6b395a1de89dd85bc67f55c8cd3f5d852))
13
-
14
- ### [1.2.6](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.2.4...v1.2.6) (2024-09-29)
15
-
16
-
17
- ### Bug Fixes
18
-
19
- * export ([b753280](https://github.com/nigrosimone/express-fast-json-stringify/commit/b753280af8af5aea830715405d404f3fad6f43d7))
20
-
21
- ### [1.2.4](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.2.2...v1.2.4) (2024-09-29)
22
-
23
-
24
- ### Bug Fixes
25
-
26
- * del deps ([0e9e63a](https://github.com/nigrosimone/express-fast-json-stringify/commit/0e9e63af86e647815002079b1df5ca19ff6f7632))
27
-
28
- ### [1.2.2](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.2.0...v1.2.2) (2024-09-29)
29
-
30
- ## [1.2.0](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.1.4...v1.2.0) (2024-09-29)
31
-
32
-
33
- ### Features
34
-
35
- * add options ([9466dc3](https://github.com/nigrosimone/express-fast-json-stringify/commit/9466dc30c20693a7ceabf2240d5d9701c76280c0))
36
-
37
- ### [1.1.4](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.1.2...v1.1.4) (2024-09-29)
38
-
39
- ### [1.1.2](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.1.0...v1.1.2) (2024-09-29)
40
-
41
- ## 1.1.0 (2024-09-29)
42
-
43
-
44
- ### Features
45
-
46
- * first commit ([5e3cc3e](https://github.com/nigrosimone/express-fast-json-stringify/commit/5e3cc3e46fc0d35c07299697d1133636d21bee9b))
47
- * npmignore ([364b397](https://github.com/nigrosimone/express-fast-json-stringify/commit/364b397ec15c14846c427c8c395b756aec839174))
48
- * vscode ([f962e81](https://github.com/nigrosimone/express-fast-json-stringify/commit/f962e8145aeaa517c8b80dc642f5bca6139dff4d))
49
-
50
-
51
- ### Bug Fixes
52
-
53
- * ignore publish ([ca95f45](https://github.com/nigrosimone/express-fast-json-stringify/commit/ca95f450e1ce22f957fff4cd9f7520386ee70962))
33
+ ### [1.2.8](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.2.6...v1.2.8) (2024-09-29)
34
+
35
+ ### Bug Fixes
36
+
37
+ - global type ([56fa47c](https://github.com/nigrosimone/express-fast-json-stringify/commit/56fa47c6b395a1de89dd85bc67f55c8cd3f5d852))
38
+
39
+ ### [1.2.6](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.2.4...v1.2.6) (2024-09-29)
40
+
41
+ ### Bug Fixes
42
+
43
+ - export ([b753280](https://github.com/nigrosimone/express-fast-json-stringify/commit/b753280af8af5aea830715405d404f3fad6f43d7))
44
+
45
+ ### [1.2.4](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.2.2...v1.2.4) (2024-09-29)
46
+
47
+ ### Bug Fixes
48
+
49
+ - del deps ([0e9e63a](https://github.com/nigrosimone/express-fast-json-stringify/commit/0e9e63af86e647815002079b1df5ca19ff6f7632))
50
+
51
+ ### [1.2.2](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.2.0...v1.2.2) (2024-09-29)
52
+
53
+ ## [1.2.0](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.1.4...v1.2.0) (2024-09-29)
54
+
55
+ ### Features
56
+
57
+ - add options ([9466dc3](https://github.com/nigrosimone/express-fast-json-stringify/commit/9466dc30c20693a7ceabf2240d5d9701c76280c0))
58
+
59
+ ### [1.1.4](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.1.2...v1.1.4) (2024-09-29)
60
+
61
+ ### [1.1.2](https://github.com/nigrosimone/express-fast-json-stringify/compare/v1.1.0...v1.1.2) (2024-09-29)
62
+
63
+ ## 1.1.0 (2024-09-29)
64
+
65
+ ### Features
66
+
67
+ - first commit ([5e3cc3e](https://github.com/nigrosimone/express-fast-json-stringify/commit/5e3cc3e46fc0d35c07299697d1133636d21bee9b))
68
+ - npmignore ([364b397](https://github.com/nigrosimone/express-fast-json-stringify/commit/364b397ec15c14846c427c8c395b756aec839174))
69
+ - vscode ([f962e81](https://github.com/nigrosimone/express-fast-json-stringify/commit/f962e8145aeaa517c8b80dc642f5bca6139dff4d))
70
+
71
+ ### Bug Fixes
72
+
73
+ - ignore publish ([ca95f45](https://github.com/nigrosimone/express-fast-json-stringify/commit/ca95f450e1ce22f957fff4cd9f7520386ee70962))
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2019 Nigro Simone
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2019 Nigro Simone
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,116 +1,307 @@
1
- JSON serialization is a critical task in web development, particularly for applications built with Node.js and Express.js. While the native JSON serialization in Node.js (`JSON.stringify()`) is straightforward and convenient, it can become a performance bottleneck, especially under heavy load. This documentation introduces [express-fast-json-stringify](https://www.npmjs.com/package/express-fast-json-stringify), a custom middleware package that leverages [fast-json-stringify](https://www.npmjs.com/package/fast-json-stringify) to significantly boost JSON serialization performance in Express applications.
2
-
3
- ## What is fast-json-stringify?
4
-
5
- `fast-json-stringify` is a JSON serialization library developed by the Fastify team. It enhances JSON conversion speed by analyzing JSON schema definitions and compiling them into highly optimized serialization functions. This makes it much faster than the native `JSON.stringify()`, particularly beneficial for high-performance applications.
6
-
7
- ## Introducing express-fast-json-stringify
8
-
9
- `express-fast-json-stringify` is an npm package that brings the performance benefits of `fast-json-stringify` to Express.js applications. By integrating this package, you can achieve faster JSON serialization, thus improving the overall performance of your application.
10
-
11
- ## Installation
12
-
13
- First, install the `express-fast-json-stringify` package:
14
-
15
- ```
16
- npm install express-fast-json-stringify
17
- ```
18
-
19
- ## Creating a JSON Schema
20
-
21
- Define a schema object that specifies the structure of your JSON responses. This schema will be used by `fast-json-stringify` to optimize the serialization process.
22
-
23
- ```ts
24
- import { Schema } from 'express-fast-json-stringify';
25
-
26
- const schema: Schema = {
27
- title: 'Example Schema',
28
- type: 'object',
29
- properties: {
30
- firstName: { type: 'string' },
31
- lastName: { type: 'string' },
32
- age: {
33
- description: 'Age in years',
34
- type: 'integer',
35
- },
36
- },
37
- };
38
- ```
39
-
40
- ## Applying the Middleware
41
-
42
- Use the `fastJsonSchema` middleware in your Express routes, passing the schema object as an argument. This will set up the optimized JSON serialization for that route.
43
-
44
- ```ts
45
- import express from 'express';
46
- import { fastJsonSchema, Schema } from 'express-fast-json-stringify';
47
-
48
- const app = express();
49
-
50
- const exampleSchema: Schema = {
51
- title: 'Example Schema',
52
- type: 'object',
53
- properties: {
54
- firstName: { type: 'string' },
55
- lastName: { type: 'string' },
56
- age: { type: 'integer' },
57
- },
58
- };
59
-
60
- app.get('/', fastJsonSchema(exampleSchema), (req, res, next) => {});
61
- ```
62
-
63
- ## Sending JSON Responses
64
-
65
- Instead of using the default `res.json()` method, use the `res.fastJson()` method provided by the middleware to send JSON responses. This leverages the speed benefits of fast-json-stringify.
66
-
67
- ```ts
68
- import express from 'express';
69
- import { fastJsonSchema, Schema } from 'express-fast-json-stringify';
70
-
71
- const app = express();
72
-
73
- const schema: Schema = {
74
- title: 'Example Schema',
75
- type: 'object',
76
- properties: {
77
- firstName: { type: 'string' },
78
- lastName: { type: 'string' },
79
- age: {
80
- description: 'Age in years',
81
- type: 'integer',
82
- },
83
- },
84
- };
85
-
86
- app.get('/', fastJsonSchema(schema), (req, res, next) => {
87
- try {
88
- const data = {
89
- firstName: 'Simone',
90
- lastName: 'Nigro',
91
- age: 40,
92
- };
93
- res.fastJson(data);
94
- } catch (error) {
95
- next(error);
96
- }
97
- });
98
- ```
99
-
100
- ## Performance Benefits
101
-
102
- Using `express-fast-json-stringify` offers several performance benefits:
103
-
104
- 1. **Increased Speed**: `fast-json-stringify` can serialize JSON data much faster than JSON.stringify(), especially for complex JSON objects.
105
- 2. **Reduced CPU Usage**: Faster serialization means less CPU time spent on processing, allowing your server to handle more concurrent requests.
106
- 3. **Consistency and Validation**: By defining JSON schemas, you ensure that the serialized data adheres to a predefined structure, improving data consistency and reducing the likelihood of errors.
107
-
108
- ## Conclusion
109
-
110
- Integrating `express-fast-json-stringify` into your Express.js application can provide substantial performance improvements, especially in scenarios where JSON serialization is a bottleneck. By leveraging the power of `fast-json-stringify`, you can achieve faster response times and handle higher loads, making your application more efficient and scalable.
111
-
112
- To start using `express-fast-json-stringify`, follow the steps outlined in this documentation, and enjoy the benefits of faster JSON serialization in your Express applications. For a live demo, you can check out the [StackBlitz demo](https://stackblitz.com/edit/express-fast-json-stringify).
113
-
114
- ## Support
115
-
116
- This is an open-source project. Star this [repository](https://github.com/nigrosimone/express-fast-json-stringify), if you like it, or even [donate](https://www.paypal.com/paypalme/snwp). Thank you so much!
1
+ JSON serialization is a critical task in web development, particularly for applications built with Node.js and Express.js. While the native JSON serialization in Node.js (`JSON.stringify()`) is straightforward and convenient, it can become a performance bottleneck, especially under heavy load. This documentation introduces [express-fast-json-stringify](https://www.npmjs.com/package/express-fast-json-stringify), a custom middleware package that leverages [fast-json-stringify](https://www.npmjs.com/package/fast-json-stringify) to significantly boost JSON serialization performance in Express applications.
2
+
3
+ Run it now on [StackBlitz](https://stackblitz.com/github/nigrosimone/express-fast-json-stringify) — it boots the Express server, serves the same payload through `res.json()` and `res.fastJson()`, and prints both responses side by side. The [sources](./example) are in this repository.
4
+
5
+ ## What is fast-json-stringify?
6
+
7
+ `fast-json-stringify` is a JSON serialization library developed by the Fastify team. It analyzes JSON schema definitions and compiles them into serialization functions specialized for the exact shape of your payload, so it can skip everything the schema does not describe instead of walking the object generically like `JSON.stringify()` has to.
8
+
9
+ ## Introducing express-fast-json-stringify
10
+
11
+ `express-fast-json-stringify` is an npm package that brings the performance benefits of `fast-json-stringify` to Express.js applications. By integrating this package, you can achieve faster JSON serialization, thus improving the overall performance of your application.
12
+
13
+ ## Installation
14
+
15
+ First, install the `express-fast-json-stringify` package:
16
+
17
+ ```
18
+ npm install express-fast-json-stringify
19
+ ```
20
+
21
+ It requires Express 4.16 or newer (Express 5 included) and Node.js 20 or newer.
22
+
23
+ ## Creating a JSON Schema
24
+
25
+ Define a schema object that specifies the structure of your JSON responses. This schema will be used by `fast-json-stringify` to optimize the serialization process.
26
+
27
+ ```ts
28
+ import { Schema } from 'express-fast-json-stringify';
29
+
30
+ const schema: Schema = {
31
+ title: 'Example Schema',
32
+ type: 'object',
33
+ properties: {
34
+ firstName: { type: 'string' },
35
+ lastName: { type: 'string' },
36
+ age: {
37
+ description: 'Age in years',
38
+ type: 'integer',
39
+ },
40
+ },
41
+ };
42
+ ```
43
+
44
+ ## Installing it on the app
45
+
46
+ Call `installFastJson(app)` once, when the app is built. It adds `res.fastJson()` to the
47
+ responses of that app, on `app.response`, so no request pays for it.
48
+
49
+ ```ts
50
+ import express from 'express';
51
+ import { installFastJson } from 'express-fast-json-stringify';
52
+
53
+ const app = express();
54
+ installFastJson(app);
55
+ ```
56
+
57
+ ## Applying the Middleware
58
+
59
+ Use the `fastJsonSchema` middleware in your Express routes, passing the schema object as an argument. It picks the serializer for that route.
60
+
61
+ ```ts
62
+ import express from 'express';
63
+ import { fastJsonSchema, installFastJson, Schema } from 'express-fast-json-stringify';
64
+
65
+ const app = express();
66
+ installFastJson(app);
67
+
68
+ const exampleSchema: Schema = {
69
+ title: 'Example Schema',
70
+ type: 'object',
71
+ properties: {
72
+ firstName: { type: 'string' },
73
+ lastName: { type: 'string' },
74
+ age: { type: 'integer' },
75
+ },
76
+ };
77
+
78
+ app.get('/', fastJsonSchema(exampleSchema), (req, res, next) => {});
79
+ ```
80
+
81
+ ## Sending JSON Responses
82
+
83
+ Instead of using the default `res.json()` method, use the `res.fastJson()` method provided by the middleware to send JSON responses. This leverages the speed benefits of fast-json-stringify.
84
+
85
+ ```ts
86
+ import express from 'express';
87
+ import { fastJsonSchema, installFastJson, Schema } from 'express-fast-json-stringify';
88
+
89
+ const app = express();
90
+ installFastJson(app);
91
+
92
+ const schema: Schema = {
93
+ title: 'Example Schema',
94
+ type: 'object',
95
+ properties: {
96
+ firstName: { type: 'string' },
97
+ lastName: { type: 'string' },
98
+ age: {
99
+ description: 'Age in years',
100
+ type: 'integer',
101
+ },
102
+ },
103
+ };
104
+
105
+ app.get('/', fastJsonSchema(schema), (req, res, next) => {
106
+ try {
107
+ const data = {
108
+ firstName: 'Simone',
109
+ lastName: 'Nigro',
110
+ age: 40,
111
+ };
112
+ res.fastJson(data);
113
+ } catch (error) {
114
+ next(error);
115
+ }
116
+ });
117
+ ```
118
+
119
+ ## Response semantics
120
+
121
+ `res.fastJson()` is a drop-in replacement for `res.json()`: only the
122
+ serialization changes. The string then goes through `res.send()`, the same
123
+ call `res.json()` makes, so every HTTP detail is the one the framework gives.
124
+
125
+ | Behavior | What `res.fastJson()` does |
126
+ | -------------------- | --------------------------------------------------------------------------------------------------- |
127
+ | `Content-Type` | `application/json; charset=utf-8`; a type the route set with `res.type()` is kept, charset added. |
128
+ | `Content-Length` | Set by `res.send()`, so the response is never chunked. |
129
+ | `ETag` | Follows the app `etag` setting, exactly like `res.send()`. Set `app.set('etag', false)` to skip it. |
130
+ | Conditional requests | A matching `If-None-Match` answers `304` with no body. |
131
+ | `204` and `304` | No body and no `Content-Type`/`Content-Length`/`Transfer-Encoding`. |
132
+ | `HEAD` | Headers only, `Content-Length` included. |
133
+
134
+ The payload is serialized before the status code is inspected, so a body that
135
+ does not match the schema still throws on a `204` — just like `res.json()`.
136
+
137
+ A route without a schema falls back to `res.json()`. Pass
138
+ `installFastJson(app, { strict: true })` to get an error instead.
139
+
140
+ ## Taking the schema from your OpenAPI document
141
+
142
+ If you already publish an OpenAPI (or Swagger) document, the response schemas
143
+ are written there — no need to repeat them in the routes. `fastJsonOpenApi`
144
+ takes that document and resolves the schema per route and per status code.
145
+ It installs itself, so there is no `installFastJson(app)` to call and no
146
+ middleware runs per request:
147
+
148
+ ```ts
149
+ import express from 'express';
150
+ import { fastJsonOpenApi } from 'express-fast-json-stringify';
151
+
152
+ import document from './openapi.json' with { type: 'json' };
153
+
154
+ const app = express();
155
+
156
+ // Once for the whole app.
157
+ fastJsonOpenApi(app, document);
158
+
159
+ app.get('/users/:id', (req, res, next) => {
160
+ try {
161
+ // Serialized with the schema of `get /users/{id}` -> `200`.
162
+ res.fastJson(user);
163
+ } catch (error) {
164
+ next(error);
165
+ }
166
+ });
167
+
168
+ app.post('/users', (req, res, next) => {
169
+ try {
170
+ // ...and this one with the schema of `post /users` -> `201`.
171
+ res.status(201).fastJson(user);
172
+ } catch (error) {
173
+ next(error);
174
+ }
175
+ });
176
+ ```
177
+
178
+ The document is a plain object, so this works with whatever produces yours:
179
+
180
+ | Tool | How to pass it |
181
+ | --------------------------- | ---------------------------------------------------------------------- |
182
+ | `swagger-jsdoc` | `fastJsonOpenApi(swaggerJsdoc(options))` |
183
+ | `swagger-ui-express` | the same object you hand to `swaggerUi.setup(document)` |
184
+ | `express-openapi-validator` | the same document you pass as `apiSpec` (or the parsed YAML/JSON file) |
185
+ | `tsoa` | the generated `swagger.json` |
186
+ | hand written | `import document from './openapi.json' with { type: 'json' }` |
187
+
188
+ There is no dependency on any of them: the middleware only reads `paths`,
189
+ `components.schemas` (OpenAPI 3.x) and `definitions` (Swagger 2.0).
190
+
191
+ ### What it resolves
192
+
193
+ - **The operation** comes from the matched Express route, so `/users/:id`
194
+ under a router mounted at `/api` looks up `/api/users/{id}`. Parameter
195
+ modifiers (`:id?`, `:id(\d+)`) are ignored, as OpenAPI has no equivalent.
196
+ A `HEAD` request falls back to the `get` operation, the way Express does.
197
+ - **The response** is matched most specific first: the exact status code, then
198
+ the wildcard range (`2XX`), then `default`. `res.status(404).fastJson(...)`
199
+ therefore serializes with the `404` schema.
200
+ - **`$ref`** is resolved against the document, including recursive references,
201
+ so `#/components/schemas/User` and `#/definitions/User` both just work.
202
+ - **OpenAPI 3.0 and 3.1** are both supported; `nullable: true` is honoured and
203
+ annotation keywords (`example`, `discriminator`, `xml`, ...) are ignored.
204
+
205
+ Routes the document does not describe fall back to `res.json()`, so installing
206
+ it app-wide cannot break an undocumented endpoint. Pass `{ strict: true }` to
207
+ get an error instead of a silent fallback.
208
+
209
+ The serializer of a route is found from the route object the framework
210
+ matched and kept beside it, so a request does not rebuild the path or look up
211
+ a string.
212
+
213
+ ```ts
214
+ // Read a different media type, forward fast-json-stringify options
215
+ fastJsonOpenApi(app, document, { contentType: 'application/vnd.api+json', rounding: 'ceil' });
216
+
217
+ // A route the document spells differently: take the schema out by hand
218
+ app.get('/v2/people/:id', fastJsonSchema(openApiSchema(document, '/users/{id}', 'get')!), handler);
219
+ ```
220
+
221
+ Because the schema decides what gets written, a property that is not in the
222
+ document can never reach a client — `npm run example:openapi` shows a
223
+ `passwordHash` being dropped from an otherwise ordinary response object.
224
+
225
+ ### Adopting it without touching your routes
226
+
227
+ Everything above needs you to call `res.fastJson()`. In an existing codebase
228
+ that means editing every `res.json()` call site, which is a lot of churn for a
229
+ serialization change. `overrideJson` removes that step:
230
+
231
+ ```ts
232
+ fastJsonOpenApi(app, document, { overrideJson: true });
233
+
234
+ // Unchanged route. It is now serialized from the `get /users/{id}` -> `200`
235
+ // schema, with no edit at the call site.
236
+ app.get('/users/:id', (req, res) => res.json(user));
237
+ ```
238
+
239
+ Only `res.json` is replaced, once, on `app.response`. Express implements
240
+ `res.send(object)` by calling `res.json(object)`, so both entry points are
241
+ covered by the one hook, while `res.send` of a string or a Buffer is left alone.
242
+
243
+ **The override cannot break a route.** It steps aside, and the stock
244
+ `res.json()` runs, whenever:
245
+
246
+ - the document describes no schema for that route and status code;
247
+ - the app sets `json replacer`, `json spaces` or `json escape` — those change
248
+ the bytes `res.json()` writes and a compiled serializer cannot reproduce them;
249
+ - the serializer rejects the body, for instance because a required property is
250
+ missing. Pass `onError` to be told when that happens:
251
+
252
+ ```ts
253
+ fastJsonOpenApi(app, document, {
254
+ overrideJson: true,
255
+ onError: (error, req) => logger.warn({ error, url: req.originalUrl }, 'schema mismatch'),
256
+ });
257
+ ```
258
+
259
+ `strict` does not apply here: it governs explicit `res.fastJson()` calls, while
260
+ an overridden `res.json()` always falls back rather than throw.
261
+
262
+ `installFastJson(app, { overrideJson: true })` does the same for the routes
263
+ that carry a `fastJsonSchema`, with one difference: a single schema describes
264
+ the _successful_ payload, so only `2xx` responses take the fast path. An error
265
+ body would otherwise be rewritten into the shape of the success schema.
266
+
267
+ ```ts
268
+ installFastJson(app, { overrideJson: true });
269
+
270
+ app.get('/users/:id', fastJsonSchema(userSchema), (req, res) => {
271
+ res.json(user); // serialized through the schema
272
+ res.status(500).json({ error: 'boom' }); // untouched, stock res.json()
273
+ });
274
+ ```
275
+
276
+ ## Performance Benefits
277
+
278
+ Using `express-fast-json-stringify` offers several benefits:
279
+
280
+ 1. **Increased Speed**: a compiled serializer only writes the properties the schema describes, so the more your objects carry that the response does not need, the more time it saves.
281
+ 2. **Reduced CPU Usage**: faster serialization means less CPU time spent on processing, allowing your server to handle more concurrent requests.
282
+ 3. **Consistency and Validation**: by defining JSON schemas, you ensure that the serialized data adheres to a predefined structure, improving data consistency and reducing the likelihood of errors — and properties missing from the schema never leak into a response.
283
+
284
+ How much you gain depends on the payload, and on a current V8 it is not a win across the board. Measured on Node.js 26 by `npm run example`:
285
+
286
+ | Case | `fast-json-stringify` vs `JSON.stringify` |
287
+ | ------------------------------------------ | ------------------------------------------- |
288
+ | objects carrying fields outside the schema | much faster (≈9x when 17 of 20 are dropped) |
289
+ | a single small object | comparable |
290
+ | every field serialized | comparable |
291
+ | long strings | slower |
292
+
293
+ Run `npm run example` to get the numbers for your own Node.js version and payload shape before adopting it in a hot path.
294
+
295
+ ### On fulmine.js
296
+
297
+ [fulmine.js](https://www.npmjs.com/package/fulmine.js) is Express on uWebSockets.js, and it reads the source of every middleware and handler at startup: when none of them can read a request header, the header copy is skipped for that route. The `fastJsonSchema` middleware only writes `res.locals` and calls `next()`, so it keeps that skip, and so does a handler calling `res.json()`. A handler calling `res.fastJson()` does not, because that is not a method fulmine knows, so on fulmine prefer `overrideJson` and plain `res.json()`. Measured on an API endpoint with eleven request headers, the previous design of this package cost 5 to 9 microseconds of CPU per request there; this one is within half a microsecond of serializing by hand.
298
+
299
+ ## Conclusion
300
+
301
+ Integrating `express-fast-json-stringify` into your Express.js application can provide substantial performance improvements when JSON serialization is a bottleneck and your schemas let the serializer skip work. It also guarantees that responses carry exactly the properties the schema describes, which is worth having on its own.
302
+
303
+ To start using `express-fast-json-stringify`, follow the steps outlined in this documentation, and enjoy the benefits of faster JSON serialization in your Express applications. For a runnable demo, open it on [StackBlitz](https://stackblitz.com/github/nigrosimone/express-fast-json-stringify) or run it locally from [example/](./example): `npm install && npm run example`.
304
+
305
+ ## Support
306
+
307
+ This is an open-source project. Star this [repository](https://github.com/nigrosimone/express-fast-json-stringify), if you like it, or even [donate](https://www.paypal.com/paypalme/snwp). Thank you so much!
@@ -1 +1,3 @@
1
+ export { type Application, installFastJson, type FastJsonOptions, type OverrideErrorHandler } from './lib/install';
1
2
  export * from './lib/middleware';
3
+ export * from './lib/openapi';
@@ -14,5 +14,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.installFastJson = void 0;
18
+ var install_1 = require("./lib/install");
19
+ Object.defineProperty(exports, "installFastJson", { enumerable: true, get: function () { return install_1.installFastJson; } });
17
20
  __exportStar(require("./lib/middleware"), exports);
18
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7OztBQUFBLG1EQUFpQyJ9
21
+ __exportStar(require("./lib/openapi"), exports);
22
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFBQSx5Q0FBbUg7QUFBeEYsMEdBQUEsZUFBZSxPQUFBO0FBQzFDLG1EQUFpQztBQUNqQyxnREFBOEIifQ==