fastify 4.0.0 → 4.0.1

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.
@@ -2,8 +2,8 @@
2
2
 
3
3
  ## Routes
4
4
 
5
- The route methods will configure the endpoints of your application. You have
6
- two ways to declare a route with Fastify: the shorthand method and the full
5
+ The route methods will configure the endpoints of your application. You have two
6
+ ways to declare a route with Fastify: the shorthand method and the full
7
7
  declaration.
8
8
 
9
9
  - [Full declaration](#full-declaration)
@@ -13,7 +13,8 @@ declaration.
13
13
  - [Async Await](#async-await)
14
14
  - [Promise resolution](#promise-resolution)
15
15
  - [Route Prefixing](#route-prefixing)
16
- - [Handling of / route inside prefixed plugins](#handling-of--route-inside-prefixed-plugins)
16
+ - [Handling of / route inside prefixed
17
+ plugins](#handling-of--route-inside-prefixed-plugins)
17
18
  - [Custom Log Level](#custom-log-level)
18
19
  - [Custom Log Serializer](#custom-log-serializer)
19
20
  - [Config](#config)
@@ -52,8 +53,9 @@ fastify.route(options)
52
53
  instance option. If you want a custom `HEAD` handler without disabling this
53
54
  option, make sure to define it before the `GET` route.
54
55
  * `attachValidation`: attach `validationError` to request, if there is a schema
55
- validation error, instead of sending the error to the error handler.
56
- The default [error format](https://ajv.js.org/api.html#error-objects) is the Ajv one.
56
+ validation error, instead of sending the error to the error handler. The
57
+ default [error format](https://ajv.js.org/api.html#error-objects) is the Ajv
58
+ one.
57
59
  * `onRequest(request, reply, done)`: a [function](./Hooks.md#onrequest) called
58
60
  as soon as a request is received, it could also be an array of functions.
59
61
  * `preParsing(request, reply, done)`: a [function](./Hooks.md#preparsing) called
@@ -114,7 +116,8 @@ fastify.route(options)
114
116
  * `slash`: Will register only `/prefix/`.
115
117
  * `no-slash`: Will register only `/prefix`.
116
118
 
117
- Note: this option does not override `ignoreTrailingSlash` in [Server](./Server.md) configuration.
119
+ Note: this option does not override `ignoreTrailingSlash` in
120
+ [Server](./Server.md) configuration.
118
121
 
119
122
  * `request` is defined in [Request](./Request.md).
120
123
 
@@ -227,35 +230,66 @@ checked before parametric and wildcard.*
227
230
 
228
231
  ```js
229
232
  // parametric
230
- fastify.get('/example/:userId', (request, reply) => {})
231
- fastify.get('/example/:userId/:secretToken', (request, reply) => {})
233
+ fastify.get('/example/:userId', function (request, reply) {
234
+ // curl ${app-url}/example/12345
235
+ // userId === '12345'
236
+ const { userId } = request.params;
237
+ // your code here
238
+ })
239
+ fastify.get('/example/:userId/:secretToken', function (request, reply) {
240
+ // curl ${app-url}/example/12345/abc.zHi
241
+ // userId === '12345'
242
+ // secretToken === 'abc.zHi'
243
+ const { userId, secretToken } = request.params;
244
+ // your code here
245
+ })
232
246
 
233
247
  // wildcard
234
- fastify.get('/example/*', (request, reply) => {})
248
+ fastify.get('/example/*', function (request, reply) {})
235
249
  ```
236
250
 
237
- Regular expression routes are supported as well, but be aware that you have to escape slashes. Take note that RegExp is also very expensive in terms of performance!
251
+ Regular expression routes are supported as well, but be aware that you have to
252
+ escape slashes. Take note that RegExp is also very expensive in terms of
253
+ performance!
238
254
  ```js
239
255
  // parametric with regexp
240
- fastify.get('/example/:file(^\\d+).png', (request, reply) => {})
256
+ fastify.get('/example/:file(^\\d+).png', function (request, reply) {
257
+ // curl ${app-url}/example/12345.png
258
+ // file === '12345'
259
+ const { file } = request.params;
260
+ // your code here
261
+ })
241
262
  ```
242
263
 
243
264
  It is possible to define more than one parameter within the same couple of slash
244
265
  ("/"). Such as:
245
266
  ```js
246
- fastify.get('/example/near/:lat-:lng/radius/:r', (request, reply) => {})
267
+ fastify.get('/example/near/:lat-:lng/radius/:r', function (request, reply) {
268
+ // curl ${app-url}/example/near/15°N-30°E/radius/20
269
+ // lat === "15°N"
270
+ // lng === "30°E"
271
+ // r ==="20"
272
+ const { lat, lng, r } = request.params;
273
+ // your code here
274
+ })
247
275
  ```
248
276
  *Remember in this case to use the dash ("-") as parameters separator.*
249
277
 
250
278
  Finally, it is possible to have multiple parameters with RegExp:
251
279
  ```js
252
- fastify.get('/example/at/:hour(^\\d{2})h:minute(^\\d{2})m', (request, reply) => {})
280
+ fastify.get('/example/at/:hour(^\\d{2})h:minute(^\\d{2})m', function (request, reply) {
281
+ // curl ${app-url}/example/at/08h24m
282
+ // hour === "08"
283
+ // minute === "24"
284
+ const { hour, minute } = request.params;
285
+ // your code here
286
+ })
253
287
  ```
254
288
  In this case as parameter separator it is possible to use whatever character is
255
289
  not matched by the regular expression.
256
290
 
257
- Having a route with multiple parameters may negatively affect performance,
258
- so prefer a single parameter approach whenever possible, especially on routes that
291
+ Having a route with multiple parameters may negatively affect performance, so
292
+ prefer a single parameter approach whenever possible, especially on routes that
259
293
  are on the hot path of your application. If you are interested in how we handle
260
294
  the routing, check out [find-my-way](https://github.com/delvedor/find-my-way).
261
295
 
@@ -280,8 +314,8 @@ fastify.get('/', options, async function (request, reply) {
280
314
  As you can see, we are not calling `reply.send` to send back the data to the
281
315
  user. You just need to return the body and you are done!
282
316
 
283
- If you need it you can also send back the data to the user with `reply.send`.
284
- In this case do not forget to `return reply` or `await reply` in your `async`
317
+ If you need it you can also send back the data to the user with `reply.send`. In
318
+ this case do not forget to `return reply` or `await reply` in your `async`
285
319
  handler or you will introduce a race condition in certain situations.
286
320
 
287
321
  ```js
@@ -320,22 +354,22 @@ fastify.get('/', options, async function (request, reply) {
320
354
  first one that happens takes precedence, the second value will be discarded,
321
355
  and a *warn* log will also be emitted because you tried to send a response
322
356
  twice.
323
- * Calling `reply.send()` outside of the promise is possible but requires
324
- special attention. For more details read
325
- [promise-resolution](#promise-resolution).
357
+ * Calling `reply.send()` outside of the promise is possible but requires special
358
+ attention. For more details read [promise-resolution](#promise-resolution).
326
359
  * You cannot return `undefined`. For more details read
327
360
  [promise-resolution](#promise-resolution).
328
361
 
329
362
  ### Promise resolution
330
363
  <a id="promise-resolution"></a>
331
364
 
332
- If your handler is an `async` function or returns a promise, you should be aware of
333
- the special behavior that is necessary to support the callback and promise
365
+ If your handler is an `async` function or returns a promise, you should be aware
366
+ of the special behavior that is necessary to support the callback and promise
334
367
  control-flow. When the handler's promise is resolved, the reply will be
335
368
  automatically sent with its value unless you explicitly await or return `reply`
336
369
  in your handler.
337
370
 
338
- 1. If you want to use `async/await` or promises but respond with a value with `reply.send`:
371
+ 1. If you want to use `async/await` or promises but respond with a value with
372
+ `reply.send`:
339
373
  - **Do** `return reply` / `await reply`.
340
374
  - **Do not** forget to call `reply.send`.
341
375
  2. If you want to use `async/await` or promises:
@@ -343,9 +377,9 @@ in your handler.
343
377
  - **Do** return the value that you want to send.
344
378
 
345
379
  In this way, we can support both `callback-style` and `async-await`, with the
346
- minimum trade-off. Despite so much freedom we highly recommend going with
347
- only one style because error handling should be handled in a consistent way
348
- within your application.
380
+ minimum trade-off. Despite so much freedom we highly recommend going with only
381
+ one style because error handling should be handled in a consistent way within
382
+ your application.
349
383
 
350
384
  **Notice**: Every async function returns a promise by itself.
351
385
 
@@ -392,14 +426,55 @@ Now your clients will have access to the following routes:
392
426
  - `/v2/user`
393
427
 
394
428
  You can do this as many times as you want, it also works for nested `register`,
395
- and route parameters are supported as well. Be aware that if you use
396
- [`fastify-plugin`](https://github.com/fastify/fastify-plugin) this option will
397
- not work.
429
+ and route parameters are supported as well.
430
+
431
+ In case you want to use prefix for all of your routes, you can put them inside a
432
+ plugin:
433
+
434
+ ```js
435
+ const fastify = require('fastify')()
436
+
437
+ const route = {
438
+ method: 'POST',
439
+ url: '/login',
440
+ handler: () => {},
441
+ schema: {},
442
+ }
443
+
444
+ fastify.register(function(app, _, done) {
445
+ app.get('/users', () => {})
446
+ app.route(route)
447
+
448
+ done()
449
+ }, { prefix: '/v1' }) // global route prefix
450
+
451
+ await fastify.listen({ port: 0 })
452
+ ```
453
+
454
+ ### Route Prefixing and fastify-plugin
455
+ <a id="fastify-plugin"></a>
456
+
457
+ Be aware that if you use
458
+ [`fastify-plugin`](https://github.com/fastify/fastify-plugin) for wrapping your
459
+ routes, this option will not work. You can still make it work by wrapping a
460
+ plugin in a plugin, e. g.:
461
+ ```js
462
+ const fp = require('fastify-plugin')
463
+ const routes = require('./lib/routes')
464
+
465
+ module.exports = fp(async function (app, opts) {
466
+ app.register(routes, {
467
+ prefix: '/v1',
468
+ })
469
+ }, {
470
+ name: 'my-routes'
471
+ })
472
+ ```
398
473
 
399
474
  #### Handling of / route inside prefixed plugins
400
475
 
401
- The `/` route has different behavior depending on if the prefix ends with `/`
402
- or not. As an example, if we consider a prefix `/something/`, adding a `/` route
476
+ The `/` route has different behavior depending on if the prefix ends with `/` or
477
+ not. As an example, if we consider a prefix `/something/`, adding a `/` route
403
478
  will only match `/something/`. If we consider a prefix `/something`, adding a
404
479
  `/` route will match both `/something` and `/something/`.
405
480
 
@@ -408,8 +483,8 @@ See the `prefixTrailingSlash` route option above to change this behavior.
408
483
  ### Custom Log Level
409
484
  <a id="custom-log-level"></a>
410
485
 
411
- You might need different log levels in your routes; Fastify
412
- achieves this in a very straightforward way.
486
+ You might need different log levels in your routes; Fastify achieves this in a
487
+ very straightforward way.
413
488
 
414
489
  You just need to pass the option `logLevel` to the plugin option or the route
415
490
  option with the
@@ -659,9 +734,9 @@ fastify.route({
659
734
  Fastify will check the HTTP version of every request, based on configuration
660
735
  options ([http2](./Server.md#http2), [https](./Server.md#https), and
661
736
  [serverFactory](./Server.md#serverfactory)), to determine if it matches one or
662
- all of the > following versions: `2.0`, `1.1`, and `1.0`. If Fastify receives
663
- a different HTTP version in the request it will return a
664
- `505 HTTP Version Not Supported` error.
737
+ all of the > following versions: `2.0`, `1.1`, and `1.0`. If Fastify receives a
738
+ different HTTP version in the request it will return a `505 HTTP Version Not
739
+ Supported` error.
665
740
 
666
741
  | | 2.0 | 1.1 | 1.0 | skip |
667
742
  |:------------------------:|:---:|:---:|:---:|:----:|
@@ -673,4 +748,4 @@ a different HTTP version in the request it will return a
673
748
  | serverFactory | | | | ✓ |
674
749
 
675
750
  Note: The internal HTTP version check will be removed in the future when Node
676
- implements [this feature](https://github.com/nodejs/node/issues/43115).
751
+ implements [this feature](https://github.com/nodejs/node/issues/43115).
@@ -136,16 +136,23 @@ use. Also, when `serverFactory` option is specified, this option is ignored.
136
136
  ### `forceCloseConnections`
137
137
  <a id="forcecloseconnections"></a>
138
138
 
139
- When set to `true`, upon [`close`](#close) the server will iterate the
140
- current persistent connections and [destroy their sockets](https://nodejs.org/dist/latest-v16.x/docs/api/net.html#socketdestroyerror).
139
+ When set to `true`, upon [`close`](#close) the server will iterate the current
140
+ persistent connections and [destroy their
141
+ sockets](https://nodejs.org/dist/latest-v16.x/docs/api/net.html#socketdestroyerror).
141
142
 
142
- > Important: connections are not inspected to determine if requests have been completed.
143
+ > Important: connections are not inspected to determine if requests have been
144
+ > completed.
143
145
 
144
- Fastify will prefer the HTTP server's [`closeAllConnections`](https://nodejs.org/dist/latest-v18.x/docs/api/http.html#servercloseallconnections) method if supported, otherwise it will use internal connection tracking.
146
+ Fastify will prefer the HTTP server's
147
+ [`closeAllConnections`](https://nodejs.org/dist/latest-v18.x/docs/api/http.html#servercloseallconnections)
148
+ method if supported, otherwise it will use internal connection tracking.
145
149
 
146
- When set to `"idle"`, upon [`close`](#close) the server will iterate the
147
- current persistent connections which are not sending a request or waiting for a response and destroy their sockets.
148
- The value is supported only if the HTTP server supports the [`closeIdleConnections`](https://nodejs.org/dist/latest-v18.x/docs/api/http.html#servercloseidleconnections) method, otherwise attempting to set it will throw an exception.
150
+ When set to `"idle"`, upon [`close`](#close) the server will iterate the current
151
+ persistent connections which are not sending a request or waiting for a response
152
+ and destroy their sockets. The value is supported only if the HTTP server
153
+ supports the
154
+ [`closeIdleConnections`](https://nodejs.org/dist/latest-v18.x/docs/api/http.html#servercloseidleconnections)
155
+ method, otherwise attempting to set it will throw an exception.
149
156
 
150
157
  + Default: `"idle"` if the HTTP server allows it, `false` otherwise
151
158
 
@@ -184,10 +191,10 @@ server is deployed without a reverse proxy in front.
184
191
  <a id="factory-ignore-slash"></a>
185
192
 
186
193
  Fastify uses [find-my-way](https://github.com/delvedor/find-my-way) to handle
187
- routing. By default, Fastify is set to take into account the trailing slashes.
188
- Paths like `/foo` and `/foo/` will be treated as different paths. If you want
189
- to change this, set this flag to `true`. That way, both `/foo` and `/foo/` will
190
- point to the same route. This option applies to *all* route registrations for
194
+ routing. By default, Fastify is set to take into account the trailing slashes.
195
+ Paths like `/foo` and `/foo/` will be treated as different paths. If you want to
196
+ change this, set this flag to `true`. That way, both `/foo` and `/foo/` will
197
+ point to the same route. This option applies to *all* route registrations for
191
198
  the resulting server instance.
192
199
 
193
200
  + Default: `false`
@@ -214,9 +221,12 @@ fastify.get('/bar', function (req, reply) {
214
221
  Fastify uses [find-my-way](https://github.com/delvedor/find-my-way) to handle
215
222
  routing. You can use `ignoreDuplicateSlashes` option to remove duplicate slashes
216
223
  from the path. It removes duplicate slashes in the route path and in the request
217
- URL. This option applies to *all* route registrations for the resulting server instance.
224
+ URL. This option applies to *all* route registrations for the resulting server
225
+ instance.
218
226
 
219
- Note that when `ignoreTrailingSlash` and `ignoreDuplicateSlashes` are both set to true, Fastify will remove duplicate slashes, and then trailing slashes, meaning //a//b//c// will be converted to /a/b/c.
227
+ Note that when `ignoreTrailingSlash` and `ignoreDuplicateSlashes` are both set
228
+ to true, Fastify will remove duplicate slashes, and then trailing slashes,
229
+ meaning //a//b//c// will be converted to /a/b/c.
220
230
 
221
231
  + Default: `false`
222
232
 
@@ -257,8 +267,8 @@ Defines the maximum payload, in bytes, the server is allowed to accept.
257
267
  Defines what action the framework must take when parsing a JSON object with
258
268
  `__proto__`. This functionality is provided by
259
269
  [secure-json-parse](https://github.com/fastify/secure-json-parse). See
260
- [Prototype Poisoning](../Guides/Prototype-Poisoning.md) for more
261
- details about prototype poisoning attacks.
270
+ [Prototype Poisoning](../Guides/Prototype-Poisoning.md) for more details about
271
+ prototype poisoning attacks.
262
272
 
263
273
  Possible values are `'error'`, `'remove'` and `'ignore'`.
264
274
 
@@ -270,8 +280,8 @@ Possible values are `'error'`, `'remove'` and `'ignore'`.
270
280
  Defines what action the framework must take when parsing a JSON object with
271
281
  `constructor`. This functionality is provided by
272
282
  [secure-json-parse](https://github.com/fastify/secure-json-parse). See
273
- [Prototype Poisoning](../Guides/Prototype-Poisoning.md) for more
274
- details about prototype poisoning attacks.
283
+ [Prototype Poisoning](../Guides/Prototype-Poisoning.md) for more details about
284
+ prototype poisoning attacks.
275
285
 
276
286
  Possible values are `'error'`, `'remove'` and `'ignore'`.
277
287
 
@@ -462,7 +472,8 @@ way query strings are handled take a look at
462
472
  ### `allowUnsafeRegex`
463
473
  <a id="factory-allow-unsafe-regex"></a>
464
474
 
465
- The allowUnsafeRegex setting is false by default, so routes only allow safe regular expressions. To use unsafe expressions, set allowUnsafeRegex to true.
475
+ The allowUnsafeRegex setting is false by default, so routes only allow safe
476
+ regular expressions. To use unsafe expressions, set allowUnsafeRegex to true.
466
477
 
467
478
  ```js
468
479
  fastify.get('/user/:id(^([0-9]+){4}$)', (request, reply) => {
@@ -470,8 +481,8 @@ fastify.get('/user/:id(^([0-9]+){4}$)', (request, reply) => {
470
481
  })
471
482
  ```
472
483
 
473
- Under the hood: [FindMyWay](https://github.com/delvedor/find-my-way)
474
- More info about safe regexp: [Safe-regex2](https://www.npmjs.com/package/safe-regex2)
484
+ Under the hood: [FindMyWay](https://github.com/delvedor/find-my-way) More info
485
+ about safe regexp: [Safe-regex2](https://www.npmjs.com/package/safe-regex2)
475
486
 
476
487
 
477
488
  ### `requestIdHeader`
@@ -562,8 +573,8 @@ derive <code>request.hostname</code> and <code>request.protocol</code>**
562
573
 
563
574
  The maximum amount of time in *milliseconds* in which a plugin can load. If not,
564
575
  [`ready`](#ready) will complete with an `Error` with code
565
- `'ERR_AVVIO_PLUGIN_TIMEOUT'`. When set to `0`, disables this check. This controls
566
- [avvio](https://www.npmjs.com/package/avvio) 's `timeout` parameter.
576
+ `'ERR_AVVIO_PLUGIN_TIMEOUT'`. When set to `0`, disables this check. This
577
+ controls [avvio](https://www.npmjs.com/package/avvio) 's `timeout` parameter.
567
578
 
568
579
  + Default: `10000`
569
580
 
@@ -648,7 +659,8 @@ the incoming request as usual.
648
659
  <a id="factory-ajv"></a>
649
660
 
650
661
  Configure the Ajv v8 instance used by Fastify without providing a custom one.
651
- The default configuration is explained in the [#schema-validator](Validation-and-Serialization.md#schema-validator) section.
662
+ The default configuration is explained in the
663
+ [#schema-validator](Validation-and-Serialization.md#schema-validator) section.
652
664
 
653
665
  ```js
654
666
  const fastify = require('fastify')({
@@ -743,7 +755,11 @@ function defaultClientErrorHandler (err, socket) {
743
755
  this.log.trace({ err }, 'client error')
744
756
 
745
757
  if (socket.writable) {
746
- socket.end(`HTTP/1.1 400 Bad Request\r\nContent-Length: ${body.length}\r\nContent-Type: application/json\r\n\r\n${body}`)
758
+ socket.end([
759
+ 'HTTP/1.1 400 Bad Request',
760
+ `Content-Length: ${body.length}`,
761
+ `Content-Type: application/json\r\n\r\n${body}`
762
+ ].join('\r\n'))
747
763
  }
748
764
  }
749
765
  ```
@@ -767,7 +783,11 @@ const fastify = require('fastify')({
767
783
  this.log.trace({ err }, 'client error')
768
784
 
769
785
  // the handler is responsible for generating a valid HTTP response
770
- socket.end(`HTTP/1.1 400 Bad Request\r\nContent-Length: ${body.length}\r\nContent-Type: application/json\r\n\r\n${body}`)
786
+ socket.end([
787
+ 'HTTP/1.1 400 Bad Request',
788
+ `Content-Length: ${body.length}`,
789
+ `Content-Type: application/json\r\n\r\n${body}`
790
+ ].join('\r\n'))
771
791
  }
772
792
  })
773
793
  ```
@@ -867,17 +887,17 @@ fastify.ready().then(() => {
867
887
  #### listen
868
888
  <a id="listen"></a>
869
889
 
870
- Starts the server and internally waits for the `.ready()` event. The
871
- signature is `.listen([options][, callback])`. Both the `options` object and the
890
+ Starts the server and internally waits for the `.ready()` event. The signature
891
+ is `.listen([options][, callback])`. Both the `options` object and the
872
892
  `callback` parameters follow the [Node.js
873
893
  core][https://nodejs.org/api/net.html#serverlistenoptions-callback] parameter
874
894
  definitions.
875
895
 
876
- By default, the server will listen on the address(es) resolved by `localhost` when no
877
- specific host is provided. If listening on any available interface is desired,
878
- then specifying `0.0.0.0` for the address will listen on all IPv4 addresses.
879
- The following table details the possible values for `host` when targeting
880
- `localhost`, and what the result of those values for `host` will be.
896
+ By default, the server will listen on the address(es) resolved by `localhost`
897
+ when no specific host is provided. If listening on any available interface is
898
+ desired, then specifying `0.0.0.0` for the address will listen on all IPv4
899
+ addresses. The following table details the possible values for `host` when
900
+ targeting `localhost`, and what the result of those values for `host` will be.
881
901
 
882
902
  Host | IPv4 | IPv6
883
903
  --------------|------|-------
@@ -962,9 +982,9 @@ fastify.listen({
962
982
  #### addresses
963
983
  <a id="addresses"></a>
964
984
 
965
- This method returns an array of addresses that the server is listening on.
966
- If you call it before `listen()` is called or after the `close()` function,
967
- it will return an empty array.
985
+ This method returns an array of addresses that the server is listening on. If
986
+ you call it before `listen()` is called or after the `close()` function, it will
987
+ return an empty array.
968
988
 
969
989
  ```js
970
990
  await fastify.listen({ port: 8080 })
@@ -980,9 +1000,10 @@ Note that the array contains the `fastify.server.address()` too.
980
1000
  #### getDefaultRoute
981
1001
  <a id="getDefaultRoute"></a>
982
1002
 
983
- The `defaultRoute` handler handles requests that do not match any URL specified by your Fastify application.
984
- This defaults to the 404 handler, but can be overridden with [setDefaultRoute](#setdefaultroute).
985
- Method to get the `defaultRoute` for the server:
1003
+ The `defaultRoute` handler handles requests that do not match any URL specified
1004
+ by your Fastify application. This defaults to the 404 handler, but can be
1005
+ overridden with [setDefaultRoute](#setdefaultroute). Method to get the
1006
+ `defaultRoute` for the server:
986
1007
 
987
1008
  ```js
988
1009
  const defaultRoute = fastify.getDefaultRoute()
@@ -991,9 +1012,10 @@ const defaultRoute = fastify.getDefaultRoute()
991
1012
  #### setDefaultRoute
992
1013
  <a id="setDefaultRoute"></a>
993
1014
 
994
- **Note**: The default 404 handler, or one set using `setNotFoundHandler`, will never trigger if the default route is overridden.
995
- Use [setNotFoundHandler](#setnotfoundhandler) if you want to customize 404 handling instead.
996
- Method to set the `defaultRoute` for the server:
1015
+ **Note**: The default 404 handler, or one set using `setNotFoundHandler`, will
1016
+ never trigger if the default route is overridden. Use
1017
+ [setNotFoundHandler](#setnotfoundhandler) if you want to customize 404 handling
1018
+ instead. Method to set the `defaultRoute` for the server:
997
1019
 
998
1020
  ```js
999
1021
  const defaultRoute = function (req, res) {
@@ -1089,8 +1111,8 @@ fastify.register(function (instance, opts, done) {
1089
1111
  #### pluginName
1090
1112
  <a id="pluginName"></a>
1091
1113
 
1092
- Name of the current plugin. The root plugin is called `'fastify'`.
1093
- There are three ways to define a name (in order).
1114
+ Name of the current plugin. The root plugin is called `'fastify'`. There are
1115
+ three ways to define a name (in order).
1094
1116
 
1095
1117
  1. If you use [fastify-plugin](https://github.com/fastify/fastify-plugin) the
1096
1118
  metadata `name` is used.
@@ -1112,10 +1134,9 @@ involved plugins in the format of `fastify -> plugin-A -> plugin-B`.
1112
1134
  #### hasPlugin
1113
1135
  <a id="hasPlugin"></a>
1114
1136
 
1115
- Method to check if a specific plugin has been registered.
1116
- Relies on the plugin metadata name.
1117
- Returns `true` if the plugin is registered.
1118
- Otherwise, returns `false`.
1137
+ Method to check if a specific plugin has been registered. Relies on the plugin
1138
+ metadata name. Returns `true` if the plugin is registered. Otherwise, returns
1139
+ `false`.
1119
1140
 
1120
1141
  ```js
1121
1142
  const fastify = require('fastify')()
@@ -1144,7 +1165,8 @@ used by plugins.
1144
1165
  #### inject
1145
1166
  <a id="inject"></a>
1146
1167
 
1147
- Fake HTTP injection (for testing purposes) [here](../Guides/Testing.md#benefits-of-using-fastifyinject).
1168
+ Fake HTTP injection (for testing purposes)
1169
+ [here](../Guides/Testing.md#benefits-of-using-fastifyinject).
1148
1170
 
1149
1171
  #### addSchema
1150
1172
  <a id="add-schema"></a>
@@ -1240,10 +1262,10 @@ unknown to Fastify. See [issue
1240
1262
  #2446](https://github.com/fastify/fastify/issues/2446) for an example of what
1241
1263
  this property helps to resolve.
1242
1264
 
1243
- Another use case is to tweak all the schemas processing.
1244
- Doing so it is possible to use Ajv v8 JTD or Standalone feature. To use such
1245
- as JTD or the Standalone mode, refers to the
1246
- [`@fastify/ajv-compiler` documentation](https://github.com/fastify/ajv-compiler#usage).
1265
+ Another use case is to tweak all the schemas processing. Doing so it is possible
1266
+ to use Ajv v8 JTD or Standalone feature. To use such as JTD or the Standalone
1267
+ mode, refers to the [`@fastify/ajv-compiler`
1268
+ documentation](https://github.com/fastify/ajv-compiler#usage).
1247
1269
 
1248
1270
  ```js
1249
1271
  const fastify = Fastify({
@@ -1251,7 +1273,8 @@ const fastify = Fastify({
1251
1273
  /**
1252
1274
  * This factory is called whenever `fastify.register()` is called.
1253
1275
  * It may receive as input the schemas of the parent context if some schemas have been added.
1254
- * @param {object} parentSchemas these schemas will be returned by the `getSchemas()` method function of the returned `bucket`.
1276
+ * @param {object} parentSchemas these schemas will be returned by the
1277
+ * `getSchemas()` method function of the returned `bucket`.
1255
1278
  */
1256
1279
  bucket: function factory (parentSchemas) {
1257
1280
  return {
@@ -1286,7 +1309,8 @@ const fastify = Fastify({
1286
1309
  * It may be called whenever `fastify.register()` is called only if new schemas have been added to the
1287
1310
  * encapsulation context.
1288
1311
  * It may receive as input the schemas of the parent context if some schemas have been added.
1289
- * @param {object} externalSchemas these schemas will be returned by the `bucket.getSchemas()`. Needed to resolve the external references $ref.
1312
+ * @param {object} externalSchemas these schemas will be returned by the
1313
+ * `bucket.getSchemas()`. Needed to resolve the external references $ref.
1290
1314
  * @param {object} ajvServerOption the server `ajv` options to build your compilers accordingly
1291
1315
  */
1292
1316
  buildValidator: function factory (externalSchemas, ajvServerOption) {
@@ -1303,8 +1327,10 @@ const fastify = Fastify({
1303
1327
  * It may be called whenever `fastify.register()` is called only if new schemas have been added to the
1304
1328
  * encapsulation context.
1305
1329
  * It may receive as input the schemas of the parent context if some schemas have been added.
1306
- * @param {object} externalSchemas these schemas will be returned by the `bucket.getSchemas()`. Needed to resolve the external references $ref.
1307
- * @param {object} serializerOptsServerOption the server `serializerOpts` options to build your compilers accordingly
1330
+ * @param {object} externalSchemas these schemas will be returned by the
1331
+ * `bucket.getSchemas()`. Needed to resolve the external references $ref.
1332
+ * @param {object} serializerOptsServerOption the server `serializerOpts`
1333
+ * options to build your compilers accordingly
1308
1334
  */
1309
1335
  buildSerializer: function factory (externalSchemas, serializerOptsServerOption) {
1310
1336
  // This factory function must return a schema serializer compiler.
@@ -1328,10 +1354,8 @@ is passed to `fastify.register()`. The handler is treated as a regular route
1328
1354
  handler so requests will go through the full [Fastify
1329
1355
  lifecycle](./Lifecycle.md#lifecycle). *async-await* is supported as well.
1330
1356
 
1331
- You can also register
1332
- [`preValidation`](./Hooks.md#route-hooks) and
1333
- [`preHandler`](./Hooks.md#route-hooks) hooks for
1334
- the 404 handler.
1357
+ You can also register [`preValidation`](./Hooks.md#route-hooks) and
1358
+ [`preHandler`](./Hooks.md#route-hooks) hooks for the 404 handler.
1335
1359
 
1336
1360
  _Note: The `preValidation` hook registered using this method will run for a
1337
1361
  route that Fastify does not recognize and **not** when a route handler manually
@@ -1405,9 +1429,13 @@ if (statusCode >= 500) {
1405
1429
  #### addConstraintStrategy
1406
1430
  <a id="addConstraintStrategy"></a>
1407
1431
 
1408
- Function to add a custom constraint strategy. To register a new type of constraint, you must add a new constraint strategy that knows how to match values to handlers, and that knows how to get the constraint value from a request.
1432
+ Function to add a custom constraint strategy. To register a new type of
1433
+ constraint, you must add a new constraint strategy that knows how to match
1434
+ values to handlers, and that knows how to get the constraint value from a
1435
+ request.
1409
1436
 
1410
- Add a custom constraint strategy using the `fastify.addConstraintStrategy` method:
1437
+ Add a custom constraint strategy using the `fastify.addConstraintStrategy`
1438
+ method:
1411
1439
 
1412
1440
  ```js
1413
1441
  const customResponseTypeStrategy = {
@@ -1436,7 +1464,8 @@ router.addConstraintStrategy(customResponseTypeStrategy);
1436
1464
  #### hasConstraintStrategy
1437
1465
  <a id="hasConstraintStrategy"></a>
1438
1466
 
1439
- The `fastify.hasConstraintStrategy(strategyName)` checks if there already exists a custom constraint strategy with the same name.
1467
+ The `fastify.hasConstraintStrategy(strategyName)` checks if there already exists
1468
+ a custom constraint strategy with the same name.
1440
1469
 
1441
1470
  #### printRoutes
1442
1471
  <a id="print-routes"></a>
@@ -1534,7 +1563,11 @@ content types, e.g. `text/json, application/vnd.oasis.opendocument.text`.
1534
1563
  `content-type` can be a string, string array or RegExp.
1535
1564
 
1536
1565
  ```js
1537
- // The two arguments passed to getDefaultJsonParser are for ProtoType poisoning and Constructor Poisoning configuration respectively. The possible values are 'ignore', 'remove', 'error'. ignore skips all validations and it is similar to calling JSON.parse() directly. See the [`secure-json-parse` documentation](https://github.com/fastify/secure-json-parse#api) for more information.
1566
+ // The two arguments passed to getDefaultJsonParser are for ProtoType poisoning
1567
+ // and Constructor Poisoning configuration respectively. The possible values are
1568
+ // 'ignore', 'remove', 'error'. ignore skips all validations and it is similar
1569
+ // to calling JSON.parse() directly. See the
1570
+ // [`secure-json-parse` documentation](https://github.com/fastify/secure-json-parse#api) for more information.
1538
1571
 
1539
1572
  fastify.addContentTypeParser('text/json', { asString: true }, fastify.getDefaultJsonParser('ignore', 'ignore'))
1540
1573
  ```
@@ -1542,8 +1575,8 @@ fastify.addContentTypeParser('text/json', { asString: true }, fastify.getDefault
1542
1575
  #### hasContentTypeParser
1543
1576
  <a id="hasContentTypeParser"></a>
1544
1577
 
1545
- `fastify.hasContentTypeParser(contentType)` is used to check whether there is a content type parser in the current
1546
- context for the specified content type.
1578
+ `fastify.hasContentTypeParser(contentType)` is used to check whether there is a
1579
+ content type parser in the current context for the specified content type.
1547
1580
 
1548
1581
  ```js
1549
1582
  fastify.hasContentTypeParser('text/json')
@@ -1554,8 +1587,9 @@ fastify.hasContentTypeParser(/^.+\/json$/)
1554
1587
  #### removeContentTypeParser
1555
1588
  <a id="removeContentTypeParser"></a>
1556
1589
 
1557
- `fastify.removeContentTypeParser(contentType)` is used to remove content type parsers in the current context. This
1558
- method allows for example to remove the both built-in parsers for `application/json` and `text/plain`.
1590
+ `fastify.removeContentTypeParser(contentType)` is used to remove content type
1591
+ parsers in the current context. This method allows for example to remove the
1592
+ both built-in parsers for `application/json` and `text/plain`.
1559
1593
 
1560
1594
  ```js
1561
1595
  fastify.removeContentTypeParser('application/json')
@@ -1566,11 +1600,14 @@ fastify.removeContentTypeParser(['application/json', 'text/plain'])
1566
1600
  #### removeAllContentTypeParsers
1567
1601
  <a id="removeAllContentTypeParsers"></a>
1568
1602
 
1569
- The `fastify.removeAllContentTypeParsers()` method allows all content type parsers in the current context to be removed.
1570
- A use case of this method is the implementation of catch-all content type parser. Before adding this parser with
1571
- `fastify.addContentTypeParser()` one could call the `removeAllContentTypeParsers` method.
1603
+ The `fastify.removeAllContentTypeParsers()` method allows all content type
1604
+ parsers in the current context to be removed. A use case of this method is the
1605
+ implementation of catch-all content type parser. Before adding this parser with
1606
+ `fastify.addContentTypeParser()` one could call the
1607
+ `removeAllContentTypeParsers` method.
1572
1608
 
1573
- For more details about the usage of the different content type parser APIs see [here](./ContentTypeParser.md#usage).
1609
+ For more details about the usage of the different content type parser APIs see
1610
+ [here](./ContentTypeParser.md#usage).
1574
1611
 
1575
1612
  #### getDefaultJsonParser
1576
1613
  <a id="getDefaultJsonParser"></a>