fastify 4.19.2 → 4.21.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.
Files changed (58) hide show
  1. package/.c8rc.json +8 -0
  2. package/.taprc +3 -2
  3. package/README.md +2 -1
  4. package/SECURITY.md +9 -0
  5. package/docs/Guides/Prototype-Poisoning.md +2 -2
  6. package/docs/Reference/Errors.md +39 -17
  7. package/docs/Reference/Logging.md +1 -1
  8. package/docs/Reference/Plugins.md +4 -0
  9. package/docs/Reference/Routes.md +8 -0
  10. package/docs/Reference/Server.md +230 -178
  11. package/docs/Reference/TypeScript.md +1 -1
  12. package/fastify.d.ts +3 -2
  13. package/fastify.js +36 -17
  14. package/lib/context.js +6 -0
  15. package/lib/errors.js +51 -20
  16. package/lib/fourOhFour.js +5 -9
  17. package/lib/handleRequest.js +3 -5
  18. package/lib/hooks.js +91 -25
  19. package/lib/logger.js +40 -3
  20. package/lib/reply.js +19 -13
  21. package/lib/reqIdGenFactory.js +18 -3
  22. package/lib/route.js +14 -61
  23. package/lib/schema-controller.js +2 -0
  24. package/lib/server.js +23 -8
  25. package/lib/symbols.js +1 -0
  26. package/package.json +8 -10
  27. package/test/500s.test.js +22 -0
  28. package/test/async-await.test.js +1 -1
  29. package/test/childLoggerFactory.test.js +91 -0
  30. package/test/encapsulated-child-logger-factory.test.js +69 -0
  31. package/test/fastify-instance.test.js +43 -10
  32. package/test/inject.test.js +1 -2
  33. package/test/internals/errors.test.js +843 -0
  34. package/test/internals/hookRunner.test.js +22 -8
  35. package/test/internals/initialConfig.test.js +9 -2
  36. package/test/internals/reply.test.js +82 -45
  37. package/test/internals/reqIdGenFactory.test.js +129 -0
  38. package/test/internals/request-validate.test.js +40 -1
  39. package/test/internals/request.test.js +14 -4
  40. package/test/reply-error.test.js +25 -0
  41. package/test/request-id.test.js +131 -0
  42. package/test/route.test.js +135 -0
  43. package/test/serial/logger.0.test.js +6 -1
  44. package/test/server.test.js +64 -2
  45. package/test/stream.test.js +4 -4
  46. package/test/types/errors.test-d.ts +82 -0
  47. package/test/types/fastify.test-d.ts +4 -0
  48. package/test/types/instance.test-d.ts +37 -0
  49. package/test/types/reply.test-d.ts +26 -0
  50. package/test/types/route.test-d.ts +3 -0
  51. package/test/types/type-provider.test-d.ts +56 -0
  52. package/types/errors.d.ts +29 -23
  53. package/types/instance.d.ts +33 -7
  54. package/types/logger.d.ts +25 -0
  55. package/types/reply.d.ts +8 -6
  56. package/types/route.d.ts +2 -1
  57. package/types/type-provider.d.ts +2 -1
  58. package/types/utils.d.ts +9 -0
@@ -80,6 +80,7 @@ describes the properties available in that options object.
80
80
  - [schemaController](#schemacontroller)
81
81
  - [setNotFoundHandler](#setnotfoundhandler)
82
82
  - [setErrorHandler](#seterrorhandler)
83
+ - [setChildLoggerFactory](#setchildloggerfactory)
83
84
  - [addConstraintStrategy](#addconstraintstrategy)
84
85
  - [hasConstraintStrategy](#hasconstraintstrategy)
85
86
  - [printRoutes](#printroutes)
@@ -91,11 +92,14 @@ describes the properties available in that options object.
91
92
  - [getDefaultJsonParser](#getdefaultjsonparser)
92
93
  - [defaultTextParser](#defaulttextparser)
93
94
  - [errorHandler](#errorhandler)
95
+ - [childLoggerFactory](#childloggerfactory)
94
96
  - [initialConfig](#initialconfig)
95
97
 
96
98
  ### `http`
97
99
  <a id="factory-http"></a>
98
100
 
101
+ + Default: `null`
102
+
99
103
  An object used to configure the server's listening socket. The options
100
104
  are the same as the Node.js core [`createServer`
101
105
  method](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_http_createserver_options_requestlistener).
@@ -103,20 +107,20 @@ method](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_http_create
103
107
  This option is ignored if options [`http2`](#factory-http2) or
104
108
  [`https`](#factory-https) are set.
105
109
 
106
- + Default: `null`
107
-
108
110
  ### `http2`
109
111
  <a id="factory-http2"></a>
110
112
 
113
+ + Default: `false`
114
+
111
115
  If `true` Node.js core's
112
116
  [HTTP/2](https://nodejs.org/dist/latest-v14.x/docs/api/http2.html) module is
113
117
  used for binding the socket.
114
118
 
115
- + Default: `false`
116
-
117
119
  ### `https`
118
120
  <a id="factory-https"></a>
119
121
 
122
+ + Default: `null`
123
+
120
124
  An object used to configure the server's listening socket for TLS. The options
121
125
  are the same as the Node.js core [`createServer`
122
126
  method](https://nodejs.org/dist/latest-v14.x/docs/api/https.html#https_https_createserver_options_requestlistener).
@@ -124,96 +128,100 @@ When this property is `null`, the socket will not be configured for TLS.
124
128
 
125
129
  This option also applies when the [`http2`](#factory-http2) option is set.
126
130
 
127
- + Default: `null`
128
-
129
131
  ### `connectionTimeout`
130
132
  <a id="factory-connection-timeout"></a>
131
133
 
134
+ + Default: `0` (no timeout)
135
+
132
136
  Defines the server timeout in milliseconds. See documentation for
133
137
  [`server.timeout`
134
138
  property](https://nodejs.org/api/http.html#http_server_timeout) to understand
135
- the effect of this option. When `serverFactory` option is specified, this option
136
- is ignored.
139
+ the effect of this option.
137
140
 
138
- + Default: `0` (no timeout)
141
+ When `serverFactory` option is specified this option is ignored.
139
142
 
140
143
  ### `keepAliveTimeout`
141
144
  <a id="factory-keep-alive-timeout"></a>
142
145
 
146
+ + Default: `72000` (72 seconds)
147
+
143
148
  Defines the server keep-alive timeout in milliseconds. See documentation for
144
149
  [`server.keepAliveTimeout`
145
150
  property](https://nodejs.org/api/http.html#http_server_keepalivetimeout) to
146
151
  understand the effect of this option. This option only applies when HTTP/1 is in
147
- use. Also, when `serverFactory` option is specified, this option is ignored.
152
+ use.
148
153
 
149
- + Default: `72000` (72 seconds)
154
+ When `serverFactory` option is specified this option is ignored.
150
155
 
151
156
  ### `forceCloseConnections`
152
157
  <a id="forcecloseconnections"></a>
153
158
 
159
+ + Default: `"idle"` if the HTTP server allows it, `false` otherwise
160
+
154
161
  When set to `true`, upon [`close`](#close) the server will iterate the current
155
162
  persistent connections and [destroy their
156
163
  sockets](https://nodejs.org/dist/latest-v16.x/docs/api/net.html#socketdestroyerror).
157
164
 
158
- > Important: connections are not inspected to determine if requests have been
159
- > completed.
165
+ > **Warning**
166
+ > Connections are not inspected to determine if requests have
167
+ > been completed.
160
168
 
161
169
  Fastify will prefer the HTTP server's
162
170
  [`closeAllConnections`](https://nodejs.org/dist/latest-v18.x/docs/api/http.html#servercloseallconnections)
163
- method if supported, otherwise it will use internal connection tracking.
171
+ method if supported, otherwise, it will use internal connection tracking.
164
172
 
165
173
  When set to `"idle"`, upon [`close`](#close) the server will iterate the current
166
174
  persistent connections which are not sending a request or waiting for a response
167
- and destroy their sockets. The value is supported only if the HTTP server
175
+ and destroy their sockets. The value is only supported if the HTTP server
168
176
  supports the
169
177
  [`closeIdleConnections`](https://nodejs.org/dist/latest-v18.x/docs/api/http.html#servercloseidleconnections)
170
178
  method, otherwise attempting to set it will throw an exception.
171
179
 
172
- + Default: `"idle"` if the HTTP server allows it, `false` otherwise
173
-
174
180
  ### `maxRequestsPerSocket`
175
181
  <a id="factory-max-requests-per-socket"></a>
176
182
 
177
- Defines the maximum number of requests socket can handle before closing keep
178
- alive connection. See documentation for [`server.maxRequestsPerSocket`
183
+ + Default: `0` (no limit)
184
+
185
+ Defines the maximum number of requests a socket can handle before closing keep
186
+ alive connection. See [`server.maxRequestsPerSocket`
179
187
  property](https://nodejs.org/dist/latest/docs/api/http.html#http_server_maxrequestspersocket)
180
188
  to understand the effect of this option. This option only applies when HTTP/1.1
181
189
  is in use. Also, when `serverFactory` option is specified, this option is
182
190
  ignored.
183
- > At the time of this writing, only node version greater or equal to 16.10.0
184
- > support this option. Check the Node.js documentation for availability in the
185
- > version you are running.
186
191
 
187
- + Default: `0` (no limit)
192
+ > **Note**
193
+ > At the time of writing, only node >= v16.10.0 supports this option.
188
194
 
189
195
  ### `requestTimeout`
190
196
  <a id="factory-request-timeout"></a>
191
197
 
198
+ + Default: `0` (no limit)
199
+
192
200
  Defines the maximum number of milliseconds for receiving the entire request from
193
- the client. [`server.requestTimeout`
201
+ the client. See [`server.requestTimeout`
194
202
  property](https://nodejs.org/dist/latest/docs/api/http.html#http_server_requesttimeout)
195
- to understand the effect of this option. Also, when `serverFactory` option is
196
- specified, this option is ignored. It must be set to a non-zero value (e.g. 120
197
- seconds) to protect against potential Denial-of-Service attacks in case the
198
- server is deployed without a reverse proxy in front.
199
- > At the time of this writing, only node version greater or equal to 14.11.0
200
- > support this option. Check the Node.js documentation for availability in the
201
- > version you are running.
203
+ to understand the effect of this option.
202
204
 
203
- + Default: `0` (no limit)
205
+ When `serverFactory` option is specified, this option is ignored.
206
+ It must be set to a non-zero value (e.g. 120 seconds) to protect against potential
207
+ Denial-of-Service attacks in case the server is deployed without a reverse proxy
208
+ in front.
209
+
210
+ > **Note**
211
+ > At the time of writing, only node >= v14.11.0 supports this option
204
212
 
205
213
  ### `ignoreTrailingSlash`
206
214
  <a id="factory-ignore-slash"></a>
207
215
 
216
+ + Default: `false`
217
+
208
218
  Fastify uses [find-my-way](https://github.com/delvedor/find-my-way) to handle
209
- routing. By default, Fastify is set to take into account the trailing slashes.
210
- Paths like `/foo` and `/foo/` will be treated as different paths. If you want to
219
+ routing. By default, Fastify will take into account the trailing slashes.
220
+ Paths like `/foo` and `/foo/` are treated as different paths. If you want to
211
221
  change this, set this flag to `true`. That way, both `/foo` and `/foo/` will
212
222
  point to the same route. This option applies to *all* route registrations for
213
223
  the resulting server instance.
214
224
 
215
- + Default: `false`
216
-
217
225
  ```js
218
226
  const fastify = require('fastify')({
219
227
  ignoreTrailingSlash: true
@@ -233,17 +241,17 @@ fastify.get('/bar', function (req, reply) {
233
241
  ### `ignoreDuplicateSlashes`
234
242
  <a id="factory-ignore-duplicate-slashes"></a>
235
243
 
244
+ + Default: `false`
245
+
236
246
  Fastify uses [find-my-way](https://github.com/delvedor/find-my-way) to handle
237
247
  routing. You can use `ignoreDuplicateSlashes` option to remove duplicate slashes
238
- from the path. It removes duplicate slashes in the route path and in the request
248
+ from the path. It removes duplicate slashes in the route path and the request
239
249
  URL. This option applies to *all* route registrations for the resulting server
240
250
  instance.
241
251
 
242
- Note that when `ignoreTrailingSlash` and `ignoreDuplicateSlashes` are both set
243
- to true, Fastify will remove duplicate slashes, and then trailing slashes,
244
- meaning //a//b//c// will be converted to /a/b/c.
245
-
246
- + Default: `false`
252
+ When `ignoreTrailingSlash` and `ignoreDuplicateSlashes` are both set
253
+ to `true` Fastify will remove duplicate slashes, and then trailing slashes,
254
+ meaning `//a//b//c//` will be converted to `/a/b/c`.
247
255
 
248
256
  ```js
249
257
  const fastify = require('fastify')({
@@ -261,46 +269,45 @@ fastify.get('///foo//bar//', function (req, reply) {
261
269
 
262
270
  You can set a custom length for parameters in parametric (standard, regex, and
263
271
  multi) routes by using `maxParamLength` option; the default value is 100
264
- characters.
272
+ characters. If the maximum length limit is reached, the not found route will
273
+ be invoked.
265
274
 
266
275
  This can be useful especially if you have a regex-based route, protecting you
267
- against [DoS
276
+ against [ReDoS
268
277
  attacks](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS).
269
278
 
270
- *If the maximum length limit is reached, the not found route will be invoked.*
271
-
272
279
  ### `bodyLimit`
273
280
  <a id="factory-body-limit"></a>
274
281
 
275
- Defines the maximum payload, in bytes, the server is allowed to accept.
276
-
277
282
  + Default: `1048576` (1MiB)
278
283
 
284
+ Defines the maximum payload, in bytes, the server is allowed to accept.
285
+
279
286
  ### `onProtoPoisoning`
280
287
  <a id="factory-on-proto-poisoning"></a>
281
288
 
289
+ + Default: `'error'`
290
+
282
291
  Defines what action the framework must take when parsing a JSON object with
283
292
  `__proto__`. This functionality is provided by
284
293
  [secure-json-parse](https://github.com/fastify/secure-json-parse). See
285
294
  [Prototype Poisoning](../Guides/Prototype-Poisoning.md) for more details about
286
295
  prototype poisoning attacks.
287
296
 
288
- Possible values are `'error'`, `'remove'` and `'ignore'`.
289
-
290
- + Default: `'error'`
297
+ Possible values are `'error'`, `'remove'`, or `'ignore'`.
291
298
 
292
299
  ### `onConstructorPoisoning`
293
300
  <a id="factory-on-constructor-poisoning"></a>
294
301
 
302
+ + Default: `'error'`
303
+
295
304
  Defines what action the framework must take when parsing a JSON object with
296
305
  `constructor`. This functionality is provided by
297
306
  [secure-json-parse](https://github.com/fastify/secure-json-parse). See
298
307
  [Prototype Poisoning](../Guides/Prototype-Poisoning.md) for more details about
299
308
  prototype poisoning attacks.
300
309
 
301
- Possible values are `'error'`, `'remove'` and `'ignore'`.
302
-
303
- + Default: `'error'`
310
+ Possible values are `'error'`, `'remove'`, or `'ignore'`.
304
311
 
305
312
  ### `logger`
306
313
  <a id="factory-logger"></a>
@@ -361,13 +368,18 @@ The possible values this property may have are:
361
368
  ### `disableRequestLogging`
362
369
  <a id="factory-disable-request-logging"></a>
363
370
 
364
- By default, when logging is enabled, Fastify will issue an `info` level log
371
+ + Default: `false`
372
+
373
+ When logging is enabled, Fastify will issue an `info` level log
365
374
  message when a request is received and when the response for that request has
366
375
  been sent. By setting this option to `true`, these log messages will be
367
376
  disabled. This allows for more flexible request start and end logging by
368
377
  attaching custom `onRequest` and `onResponse` hooks.
369
378
 
370
- + Default: `false`
379
+ Please note that this option will also disable an error log written by the
380
+ default `onResponse` hook on reply callback errors. Other log messages
381
+ emitted by Fastify will stay enabled, like deprecation warnings and messages
382
+ emitted when requests are received while the server is closing.
371
383
 
372
384
  ```js
373
385
  // Examples of hooks to replicate the disabled functionality.
@@ -382,11 +394,6 @@ fastify.addHook('onResponse', (req, reply, done) => {
382
394
  })
383
395
  ```
384
396
 
385
- Please note that this setting will also disable an error log written by the
386
- default `onResponse` hook on reply callback errors. Other log messages
387
- emitted by Fastify will stay enabled, like deprecation warnings and messages
388
- emitted when requests are received while the server is closing.
389
-
390
397
  ### `serverFactory`
391
398
  <a id="custom-http-server"></a>
392
399
 
@@ -426,13 +433,17 @@ enhance the server instance inside the `serverFactory` function before the
426
433
 
427
434
  + Default: `true`
428
435
 
429
- Internally, and by default, Fastify will automatically infer the root properties
436
+ By default, Fastify will automatically infer the root properties
430
437
  of JSON Schemas if it does not find valid root properties according to the JSON
431
- Schema spec. If you wish to implement your own schema validation compiler, for
432
- example: to parse schemas as JTD instead of JSON Schema, then you can explicitly
438
+ Schema spec. If you wish to implement your own schema validation compiler, to
439
+ parse schemas as JTD instead of JSON Schema for example, then you can explicitly
433
440
  set this option to `false` to make sure the schemas you receive are unmodified
434
441
  and are not being treated internally as JSON Schema.
435
442
 
443
+ Fastify does not throw on invalid schemas so if this option is set to `false`
444
+ in an existing project, check that none of your existing schemas become
445
+ invalid as a result, as they will be treated as catch-alls.
446
+
436
447
  ```js
437
448
  const AjvJTD = require('ajv/dist/jtd'/* only valid for AJV v7+ */)
438
449
  const ajv = new AjvJTD({
@@ -455,21 +466,23 @@ fastify.post('/', {
455
466
  })
456
467
  ```
457
468
 
458
- **Note: Fastify does not currently throw on invalid schemas, so if you turn this
459
- off in an existing project, you need to be careful that none of your existing
460
- schemas become invalid as a result, since they will be treated as a catch-all.**
461
-
462
469
  ### `caseSensitive`
463
470
  <a id="factory-case-sensitive"></a>
464
471
 
465
- By default, value equal to `true`, routes are registered as case sensitive. That
466
- is, `/foo` is not equivalent to `/Foo`. When set to `false`, routes are
467
- registered in a fashion such that `/foo` is equivalent to `/Foo` which is
468
- equivalent to `/FOO`.
472
+ + Default: `true`
473
+
474
+ When `true` routes are registered as case-sensitive. That is, `/foo`
475
+ is not equal to `/Foo`.
476
+ When `false` then routes are case-insensitive.
477
+
478
+ Please note that setting this option to `false` goes against
479
+ [RFC3986](https://tools.ietf.org/html/rfc3986#section-6.2.2.1).
469
480
 
470
481
  By setting `caseSensitive` to `false`, all paths will be matched as lowercase,
471
482
  but the route parameters or wildcards will maintain their original letter
472
- casing.
483
+ casing.
484
+ This option does not affect query strings, please refer to
485
+ [`querystringParser`](#querystringparser) to change their handling.
473
486
 
474
487
  ```js
475
488
  fastify.get('/user/:username', (request, reply) => {
@@ -478,19 +491,13 @@ fastify.get('/user/:username', (request, reply) => {
478
491
  })
479
492
  ```
480
493
 
481
- Please note that setting this option to `false` goes against
482
- [RFC3986](https://tools.ietf.org/html/rfc3986#section-6.2.2.1).
483
-
484
- Also note, this setting will not affect query strings. If you want to change the
485
- way query strings are handled take a look at
486
- [`querystringParser`](#querystringparser).
487
-
488
-
489
494
  ### `allowUnsafeRegex`
490
495
  <a id="factory-allow-unsafe-regex"></a>
491
496
 
492
- The allowUnsafeRegex setting is false by default, so routes only allow safe
493
- regular expressions. To use unsafe expressions, set allowUnsafeRegex to true.
497
+ + Default `false`
498
+
499
+ Disabled by default, so routes only allow safe regular expressions. To use
500
+ unsafe expressions, set `allowUnsafeRegex` to `true`.
494
501
 
495
502
  ```js
496
503
  fastify.get('/user/:id(^([0-9]+){4}$)', (request, reply) => {
@@ -498,18 +505,14 @@ fastify.get('/user/:id(^([0-9]+){4}$)', (request, reply) => {
498
505
  })
499
506
  ```
500
507
 
501
- Under the hood: [FindMyWay](https://github.com/delvedor/find-my-way) More info
502
- about safe regexp: [Safe-regex2](https://www.npmjs.com/package/safe-regex2)
503
-
504
-
505
508
  ### `requestIdHeader`
506
509
  <a id="factory-request-id-header"></a>
507
510
 
511
+ + Default: `'request-id'`
512
+
508
513
  The header name used to set the request-id. See [the
509
514
  request-id](./Logging.md#logging-request-id) section.
510
- Setting `requestIdHeader` to `false` will always use [genReqId](#genreqid)
511
-
512
- + Default: `'request-id'`
515
+ Setting `requestIdHeader` to `false` will always use [genReqId](#genreqid).
513
516
 
514
517
  ```js
515
518
  const fastify = require('fastify')({
@@ -517,25 +520,31 @@ const fastify = require('fastify')({
517
520
  //requestIdHeader: false, // -> always use genReqId
518
521
  })
519
522
  ```
523
+
520
524
  ### `requestIdLogLabel`
521
525
  <a id="factory-request-id-log-label"></a>
522
526
 
523
- Defines the label used for the request identifier when logging the request.
524
-
525
527
  + Default: `'reqId'`
526
528
 
529
+ Defines the label used for the request identifier when logging the request.
530
+
527
531
  ### `genReqId`
528
532
  <a id="factory-gen-request-id"></a>
529
533
 
530
- Function for generating the request-id. It will receive the _raw_ incoming
531
- request as a parameter. This function is expected to be error-free.
532
-
533
534
  + Default: `value of 'request-id' header if provided or monotonically increasing
534
535
  integers`
535
536
 
537
+ Function for generating the request-id. It will receive the _raw_ incoming
538
+ request as a parameter. This function is expected to be error-free.
539
+
536
540
  Especially in distributed systems, you may want to override the default ID
537
541
  generation behavior as shown below. For generating `UUID`s you may want to check
538
- out [hyperid](https://github.com/mcollina/hyperid)
542
+ out [hyperid](https://github.com/mcollina/hyperid).
543
+
544
+ > **Note**
545
+ > `genReqId` will be not called if the header set in
546
+ > <code>[requestIdHeader](#requestidheader)</code> is available (defaults to
547
+ > 'request-id').
539
548
 
540
549
  ```js
541
550
  let i = 0
@@ -544,21 +553,9 @@ const fastify = require('fastify')({
544
553
  })
545
554
  ```
546
555
 
547
- **Note: genReqId will _not_ be called if the header set in
548
- <code>[requestIdHeader](#requestidheader)</code> is available (defaults to
549
- 'request-id').**
550
-
551
556
  ### `trustProxy`
552
557
  <a id="factory-trust-proxy"></a>
553
558
 
554
- By enabling the `trustProxy` option, Fastify will know that it is sitting behind
555
- a proxy and that the `X-Forwarded-*` header fields may be trusted, which
556
- otherwise may be easily spoofed.
557
-
558
- ```js
559
- const fastify = Fastify({ trustProxy: true })
560
- ```
561
-
562
559
  + Default: `false`
563
560
  + `true/false`: Trust all proxies (`true`) or do not trust any proxies
564
561
  (`false`).
@@ -573,6 +570,14 @@ const fastify = Fastify({ trustProxy: true })
573
570
  }
574
571
  ```
575
572
 
573
+ By enabling the `trustProxy` option, Fastify will know that it is sitting behind
574
+ a proxy and that the `X-Forwarded-*` header fields may be trusted, which
575
+ otherwise may be easily spoofed.
576
+
577
+ ```js
578
+ const fastify = Fastify({ trustProxy: true })
579
+ ```
580
+
576
581
  For more examples, refer to the
577
582
  [`proxy-addr`](https://www.npmjs.com/package/proxy-addr) package.
578
583
 
@@ -588,28 +593,32 @@ fastify.get('/', (request, reply) => {
588
593
  })
589
594
  ```
590
595
 
591
- **Note: if a request contains multiple <code>x-forwarded-host</code> or
592
- <code>x-forwarded-proto</code> headers, it is only the last one that is used to
593
- derive <code>request.hostname</code> and <code>request.protocol</code>**
596
+ > **Note**
597
+ > If a request contains multiple `x-forwarded-host` or `x-forwarded-proto`
598
+ > headers, it is only the last one that is used to derive `request.hostname`
599
+ > and `request.protocol`.
594
600
 
595
601
  ### `pluginTimeout`
596
602
  <a id="plugin-timeout"></a>
597
603
 
604
+ + Default: `10000`
605
+
598
606
  The maximum amount of time in *milliseconds* in which a plugin can load. If not,
599
607
  [`ready`](#ready) will complete with an `Error` with code
600
608
  `'ERR_AVVIO_PLUGIN_TIMEOUT'`. When set to `0`, disables this check. This
601
609
  controls [avvio](https://www.npmjs.com/package/avvio) 's `timeout` parameter.
602
610
 
603
- + Default: `10000`
604
-
605
611
  ### `querystringParser`
606
612
  <a id="factory-querystring-parser"></a>
607
613
 
608
614
  The default query string parser that Fastify uses is the Node.js's core
609
615
  `querystring` module.
610
616
 
611
- You can change this default setting by passing the option `querystringParser`
612
- and use a custom one, such as [`qs`](https://www.npmjs.com/package/qs).
617
+ You can use this option to use a custom parser, such as
618
+ [`qs`](https://www.npmjs.com/package/qs).
619
+
620
+ If you only want the keys (and not the values) to be case insensitive we
621
+ recommend using a custom parser to convert only the keys to lowercase.
613
622
 
614
623
  ```js
615
624
  const qs = require('qs')
@@ -618,7 +627,7 @@ const fastify = require('fastify')({
618
627
  })
619
628
  ```
620
629
 
621
- You can also use Fastify's default parser but change some handling behaviour,
630
+ You can also use Fastify's default parser but change some handling behavior,
622
631
  like the example below for case insensitive keys and values:
623
632
 
624
633
  ```js
@@ -628,24 +637,21 @@ const fastify = require('fastify')({
628
637
  })
629
638
  ```
630
639
 
631
- Note, if you only want the keys (and not the values) to be case insensitive we
632
- recommend using a custom parser to convert only the keys to lowercase.
633
-
634
640
  ### `exposeHeadRoutes`
635
641
  <a id="exposeHeadRoutes"></a>
636
642
 
643
+ + Default: `true`
644
+
637
645
  Automatically creates a sibling `HEAD` route for each `GET` route defined. If
638
646
  you want a custom `HEAD` handler without disabling this option, make sure to
639
647
  define it before the `GET` route.
640
648
 
641
- + Default: `true`
642
-
643
649
  ### `constraints`
644
650
  <a id="constraints"></a>
645
651
 
646
- Fastify's built in route constraints are provided by `find-my-way`, which allow
647
- constraining routes by `version` or `host`. You are able to add new constraint
648
- strategies, or override the built in strategies by providing a `constraints`
652
+ Fastify's built-in route constraints are provided by `find-my-way`, which
653
+ allows constraining routes by `version` or `host`. You can add new constraint
654
+ strategies, or override the built-in strategies, by providing a `constraints`
649
655
  object with strategies for `find-my-way`. You can find more information on
650
656
  constraint strategies in the
651
657
  [find-my-way](https://github.com/delvedor/find-my-way) documentation.
@@ -674,11 +680,11 @@ const fastify = require('fastify')({
674
680
  ### `return503OnClosing`
675
681
  <a id="factory-return-503-on-closing"></a>
676
682
 
683
+ + Default: `true`
684
+
677
685
  Returns 503 after calling `close` server method. If `false`, the server routes
678
686
  the incoming request as usual.
679
687
 
680
- + Default: `true`
681
-
682
688
  ### `ajv`
683
689
  <a id="factory-ajv"></a>
684
690
 
@@ -707,7 +713,7 @@ const fastify = require('fastify')({
707
713
 
708
714
  Customize the options of the default
709
715
  [`fast-json-stringify`](https://github.com/fastify/fast-json-stringify#options)
710
- instance that serialize the response's payload:
716
+ instance that serializes the response's payload:
711
717
 
712
718
  ```js
713
719
  const fastify = require('fastify')({
@@ -720,15 +726,17 @@ const fastify = require('fastify')({
720
726
  ### `http2SessionTimeout`
721
727
  <a id="http2-session-timeout"></a>
722
728
 
729
+ + Default: `72000`
730
+
723
731
  Set a default
724
- [timeout](https://nodejs.org/api/http2.html#http2_http2session_settimeout_msecs_callback)
725
- to every incoming HTTP/2 session. The session will be closed on the timeout.
726
- Default: `72000` ms.
732
+ [timeout](https://nodejs.org/api/http2.html#http2sessionsettimeoutmsecs-callback)
733
+ to every incoming HTTP/2 session in milliseconds. The session will be closed on
734
+ the timeout.
727
735
 
728
- Note that this is needed to offer the graceful "close" experience when using
736
+ This option is needed to offer a graceful "close" experience when using
729
737
  HTTP/2. The low default has been chosen to mitigate denial of service attacks.
730
738
  When the server is behind a load balancer or can scale automatically this value
731
- can be increased to fit the use case. Node core defaults this to `0`. `
739
+ can be increased to fit the use case. Node core defaults this to `0`.
732
740
 
733
741
  ### `frameworkErrors`
734
742
  <a id="framework-errors"></a>
@@ -739,8 +747,8 @@ Fastify provides default error handlers for the most common use cases. It is
739
747
  possible to override one or more of those handlers with custom code using this
740
748
  option.
741
749
 
742
- *Note: Only `FST_ERR_BAD_URL` and `FST_ERR_ASYNC_CONSTRAINT` are implemented at
743
- the moment.*
750
+ > **Note**
751
+ > Only `FST_ERR_BAD_URL` and `FST_ERR_ASYNC_CONSTRAINT` are implemented at present.
744
752
 
745
753
  ```js
746
754
  const fastify = require('fastify')({
@@ -792,10 +800,11 @@ function defaultClientErrorHandler (err, socket) {
792
800
  }
793
801
  ```
794
802
 
795
- *Note: `clientErrorHandler` operates with raw socket. The handler is expected to
796
- return a properly formed HTTP response that includes a status line, HTTP headers
797
- and a message body. Before attempting to write the socket, the handler should
798
- check if the socket is still writable as it may have already been destroyed.*
803
+ > **Note**
804
+ > `clientErrorHandler` operates with raw sockets. The handler is expected to
805
+ > return a properly formed HTTP response that includes a status line, HTTP headers
806
+ > and a message body. Before attempting to write the socket, the handler should
807
+ > check if the socket is still writable as it may have already been destroyed.
799
808
 
800
809
  ```js
801
810
  const fastify = require('fastify')({
@@ -824,9 +833,11 @@ const fastify = require('fastify')({
824
833
  <a id="rewrite-url"></a>
825
834
 
826
835
  Set a sync callback function that must return a string that allows rewriting
827
- URLs.
836
+ URLs. This is useful when you are behind a proxy that changes the URL.
837
+ Rewriting a URL will modify the `url` property of the `req` object.
828
838
 
829
- > Rewriting a URL will modify the `url` property of the `req` object
839
+ Note that `rewriteUrl` is called _before_ routing, it is not encapsulated and it
840
+ is an instance-wide configuration.
830
841
 
831
842
  ```js
832
843
  // @param {object} req The raw Node.js HTTP request, not the `FastifyRequest` object.
@@ -842,9 +853,6 @@ function rewriteUrl (req) {
842
853
  }
843
854
  ```
844
855
 
845
- Note that `rewriteUrl` is called _before_ routing, it is not encapsulated and it
846
- is an instance-wide configuration.
847
-
848
856
  ## Instance
849
857
 
850
858
  ### Server Methods
@@ -856,8 +864,9 @@ is an instance-wide configuration.
856
864
  [server](https://nodejs.org/api/http.html#http_class_http_server) object as
857
865
  returned by the [**`Fastify factory function`**](#factory).
858
866
 
859
- >__Warning__: If utilized improperly, certain Fastify features could be disrupted.
860
- >It is recommended to only use it for attaching listeners.
867
+ > **Warning**
868
+ > If utilized improperly, certain Fastify features could be disrupted.
869
+ > It is recommended to only use it for attaching listeners.
861
870
 
862
871
  #### after
863
872
  <a id="after"></a>
@@ -1055,8 +1064,9 @@ Note that the array contains the `fastify.server.address()` too.
1055
1064
  #### getDefaultRoute
1056
1065
  <a id="getDefaultRoute"></a>
1057
1066
 
1058
- **Notice**: this method is deprecated and should be removed in the next Fastify
1059
- major version.
1067
+ > **Warning**
1068
+ > This method is deprecated and will be removed in the next Fastify
1069
+ > major version.
1060
1070
 
1061
1071
  The `defaultRoute` handler handles requests that do not match any URL specified
1062
1072
  by your Fastify application. This defaults to the 404 handler, but can be
@@ -1070,9 +1080,10 @@ const defaultRoute = fastify.getDefaultRoute()
1070
1080
  #### setDefaultRoute
1071
1081
  <a id="setDefaultRoute"></a>
1072
1082
 
1073
- **Notice**: this method is deprecated and should be removed in the next Fastify
1074
- major version. Please, consider to use `setNotFoundHandler` or a wildcard
1075
- matching route.
1083
+ > **Warning**
1084
+ > This method is deprecated and will be removed in the next Fastify
1085
+ > major version. Please, consider using `setNotFoundHandler` or a wildcard
1086
+ > matching route.
1076
1087
 
1077
1088
  The default 404 handler, or one set using `setNotFoundHandler`, will
1078
1089
  never trigger if the default route is overridden. This sets the handler for the
@@ -1115,9 +1126,9 @@ Method to add routes to the server, it also has shorthand functions, check
1115
1126
  <a id="hasRoute"></a>
1116
1127
 
1117
1128
  Method to check if a route is already registered to the internal router. It
1118
- expects an object as payload. `url` and `method` are mandatory fields. It is
1119
- possible to also specify `constraints`. The method returns true if the route is
1120
- registered, and false if it is not registered.
1129
+ expects an object as the payload. `url` and `method` are mandatory fields. It
1130
+ is possible to also specify `constraints`. The method returns `true` if the
1131
+ route is registered or `false` if not.
1121
1132
 
1122
1133
  ```js
1123
1134
  const routeExists = fastify.hasRoute({
@@ -1218,11 +1229,12 @@ different ways to define a name (in order).
1218
1229
  Newlines are replaced by ` -- `. This will help to identify the root cause when
1219
1230
  you deal with many plugins.
1220
1231
 
1221
- Important: If you have to deal with nested plugins, the name differs with the
1222
- usage of the [fastify-plugin](https://github.com/fastify/fastify-plugin) because
1223
- no new scope is created and therefore we have no place to attach contextual
1224
- data. In that case, the plugin name will represent the boot order of all
1225
- involved plugins in the format of `fastify -> plugin-A -> plugin-B`.
1232
+ > **Warning**
1233
+ > If you have to deal with nested plugins, the name differs with the usage of
1234
+ > the [fastify-plugin](https://github.com/fastify/fastify-plugin) because
1235
+ > no new scope is created and therefore we have no place to attach contextual
1236
+ > data. In that case, the plugin name will represent the boot order of all
1237
+ > involved plugins in the format of `fastify -> plugin-A -> plugin-B`.
1226
1238
 
1227
1239
  #### hasPlugin
1228
1240
  <a id="hasPlugin"></a>
@@ -1325,7 +1337,9 @@ Set the schema error formatter for all routes. See
1325
1337
 
1326
1338
  Set the schema serializer compiler for all routes. See
1327
1339
  [#schema-serializer](./Validation-and-Serialization.md#schema-serializer).
1328
- **Note:** [`setReplySerializer`](#set-reply-serializer) has priority if set!
1340
+
1341
+ > **Note**
1342
+ > [`setReplySerializer`](#set-reply-serializer) has priority if set!
1329
1343
 
1330
1344
  #### validatorCompiler
1331
1345
  <a id="validator-compiler"></a>
@@ -1360,9 +1374,7 @@ This property can be used to fully manage:
1360
1374
  - `compilersFactory`: what module must compile the JSON schemas
1361
1375
 
1362
1376
  It can be useful when your schemas are stored in another data structure that is
1363
- unknown to Fastify. See [issue
1364
- #2446](https://github.com/fastify/fastify/issues/2446) for an example of what
1365
- this property helps to resolve.
1377
+ unknown to Fastify.
1366
1378
 
1367
1379
  Another use case is to tweak all the schemas processing. Doing so it is possible
1368
1380
  to use Ajv v8 JTD or Standalone feature. To use such as JTD or the Standalone
@@ -1402,7 +1414,7 @@ const fastify = Fastify({
1402
1414
  },
1403
1415
 
1404
1416
  /**
1405
- * The compilers factory let you fully control the validator and serializer
1417
+ * The compilers factory lets you fully control the validator and serializer
1406
1418
  * in the Fastify's lifecycle, providing the encapsulation to your compilers.
1407
1419
  */
1408
1420
  compilersFactory: {
@@ -1459,10 +1471,12 @@ lifecycle](./Lifecycle.md#lifecycle). *async-await* is supported as well.
1459
1471
  You can also register [`preValidation`](./Hooks.md#route-hooks) and
1460
1472
  [`preHandler`](./Hooks.md#route-hooks) hooks for the 404 handler.
1461
1473
 
1462
- _Note: The `preValidation` hook registered using this method will run for a
1463
- route that Fastify does not recognize and **not** when a route handler manually
1464
- calls [`reply.callNotFound`](./Reply.md#call-not-found)_. In which case, only
1465
- preHandler will be run.
1474
+ > **Note**
1475
+ > The `preValidation` hook registered using this method will run for a
1476
+ > route that Fastify does not recognize and **not** when a route handler manually
1477
+ > calls [`reply.callNotFound`](./Reply.md#call-not-found). In which case, only
1478
+ > preHandler will be run.
1479
+
1466
1480
 
1467
1481
  ```js
1468
1482
  fastify.setNotFoundHandler({
@@ -1493,8 +1507,9 @@ plugins are registered. If you would like to augment the behavior of the default
1493
1507
  arguments `fastify.setNotFoundHandler()` within the context of these registered
1494
1508
  plugins.
1495
1509
 
1496
- > Note: Some config properties from the request object will be
1497
- > undefined inside the custom not found handler. E.g:
1510
+ > **Note**
1511
+ > Some config properties from the request object will be
1512
+ > undefined inside the custom not found handler. E.g.:
1498
1513
  > `request.routerPath`, `routerMethod` and `context.config`.
1499
1514
  > This method design goal is to allow calling the common not found route.
1500
1515
  > To return a per-route customized 404 response, you can do it in
@@ -1508,11 +1523,12 @@ will be called whenever an error happens. The handler is bound to the Fastify
1508
1523
  instance and is fully encapsulated, so different plugins can set different error
1509
1524
  handlers. *async-await* is supported as well.
1510
1525
 
1511
- *Note: If the error `statusCode` is less than 400, Fastify will automatically
1512
- set it at 500 before calling the error handler.*
1526
+ If the error `statusCode` is less than 400, Fastify will automatically
1527
+ set it to 500 before calling the error handler.
1513
1528
 
1514
- *Also note* that `setErrorHandler` will ***not*** catch any error inside
1515
- an `onResponse` hook because the response has already been sent to the client.
1529
+ > **Note**
1530
+ > `setErrorHandler` will ***not*** catch any error inside
1531
+ > an `onResponse` hook because the response has already been sent to the client.
1516
1532
 
1517
1533
  ```js
1518
1534
  fastify.setErrorHandler(function (error, request, reply) {
@@ -1537,6 +1553,35 @@ if (statusCode >= 500) {
1537
1553
  log.error(error)
1538
1554
  }
1539
1555
  ```
1556
+ #### setChildLoggerFactory
1557
+ <a id="set-child-logger-factory"></a>
1558
+
1559
+ `fastify.setChildLoggerFactory(factory(logger, bindings, opts, rawReq))`: Set a
1560
+ function that will be called when creating a child logger instance for each request
1561
+ which allows for modifying or adding child logger bindings and logger options, or
1562
+ returning a custom child logger implementation.
1563
+
1564
+ Child logger bindings have a performance advantage over per-log bindings because
1565
+ they are pre-serialized by Pino when the child logger is created.
1566
+
1567
+ The first parameter is the parent logger instance, followed by the default bindings
1568
+ and logger options which should be passed to the child logger, and finally
1569
+ the raw request (not a Fastify request object). The function is bound with `this`
1570
+ being the Fastify instance.
1571
+
1572
+ For example:
1573
+ ```js
1574
+ const fastify = require('fastify')({
1575
+ childLoggerFactory: function (logger, bindings, opts, rawReq) {
1576
+ // Calculate additional bindings from the request if needed
1577
+ bindings.traceContext = rawReq.headers['x-cloud-trace-context']
1578
+ return logger.child(bindings, opts)
1579
+ }
1580
+ })
1581
+ ```
1582
+
1583
+ The handler is bound to the Fastify instance and is fully encapsulated, so
1584
+ different plugins can set different logger factories.
1540
1585
 
1541
1586
  #### addConstraintStrategy
1542
1587
  <a id="addConstraintStrategy"></a>
@@ -1585,7 +1630,7 @@ a custom constraint strategy with the same name.
1585
1630
  `fastify.printRoutes()`: Fastify router builds a tree of routes for each HTTP
1586
1631
  method. If you call the prettyPrint without specifying an HTTP method, it will
1587
1632
  merge all the trees into one and print it. The merged tree doesn't represent the
1588
- internal router structure. **Don't use it for debugging.**
1633
+ internal router structure. **Do not use it for debugging.**
1589
1634
 
1590
1635
  *Remember to call it inside or after a `ready` call.*
1591
1636
 
@@ -1627,8 +1672,8 @@ param. Printed tree will represent the internal router structure.
1627
1672
  ```
1628
1673
 
1629
1674
  `fastify.printRoutes({ commonPrefix: false })` will print compressed trees. This
1630
- might useful when you have a large number of routes with common prefixes.
1631
- It doesn't represent the internal router structure. **Don't use it for debugging.**
1675
+ may be useful when you have a large number of routes with common prefixes.
1676
+ It doesn't represent the internal router structure. **Do not use it for debugging.**
1632
1677
 
1633
1678
  ```js
1634
1679
  console.log(fastify.printRoutes({ commonPrefix: false }))
@@ -1721,7 +1766,7 @@ fastify.ready(() => {
1721
1766
  <a id="addContentTypeParser"></a>
1722
1767
 
1723
1768
  `fastify.addContentTypeParser(content-type, options, parser)` is used to pass
1724
- custom parser for a given content type. Useful for adding parsers for custom
1769
+ a custom parser for a given content type. Useful for adding parsers for custom
1725
1770
  content types, e.g. `text/json, application/vnd.oasis.opendocument.text`.
1726
1771
  `content-type` can be a string, string array or RegExp.
1727
1772
 
@@ -1810,13 +1855,20 @@ fastify.get('/', {
1810
1855
  }, handler)
1811
1856
  ```
1812
1857
 
1858
+ #### childLoggerFactory
1859
+ <a id="childLoggerFactory"></a>
1860
+
1861
+ `fastify.childLoggerFactory` returns the custom logger factory function for the
1862
+ Fastify instance. See the [`childLoggerFactory` config option](#setchildloggerfactory)
1863
+ for more info.
1864
+
1813
1865
  #### initialConfig
1814
1866
  <a id="initial-config"></a>
1815
1867
 
1816
1868
  `fastify.initialConfig`: Exposes a frozen read-only object registering the
1817
1869
  initial options passed down by the user to the Fastify instance.
1818
1870
 
1819
- Currently the properties that can be exposed are:
1871
+ The properties that can currently be exposed are:
1820
1872
  - connectionTimeout
1821
1873
  - keepAliveTimeout
1822
1874
  - bodyLimit