fastify 5.2.0 → 5.2.2

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 (83) hide show
  1. package/LICENSE +1 -1
  2. package/PROJECT_CHARTER.md +7 -7
  3. package/README.md +65 -67
  4. package/SPONSORS.md +2 -0
  5. package/build/build-validation.js +1 -1
  6. package/docs/Guides/Benchmarking.md +4 -4
  7. package/docs/Guides/Database.md +1 -1
  8. package/docs/Guides/Delay-Accepting-Requests.md +10 -10
  9. package/docs/Guides/Ecosystem.md +5 -1
  10. package/docs/Guides/Fluent-Schema.md +1 -1
  11. package/docs/Guides/Getting-Started.md +9 -5
  12. package/docs/Guides/Index.md +1 -1
  13. package/docs/Guides/Migration-Guide-V4.md +1 -1
  14. package/docs/Guides/Migration-Guide-V5.md +12 -2
  15. package/docs/Guides/Plugins-Guide.md +6 -6
  16. package/docs/Guides/Serverless.md +14 -48
  17. package/docs/Guides/Style-Guide.md +2 -2
  18. package/docs/Guides/Testing.md +2 -2
  19. package/docs/Guides/Write-Plugin.md +2 -3
  20. package/docs/Reference/ContentTypeParser.md +58 -78
  21. package/docs/Reference/Decorators.md +50 -60
  22. package/docs/Reference/Encapsulation.md +28 -33
  23. package/docs/Reference/Errors.md +52 -53
  24. package/docs/Reference/HTTP2.md +7 -7
  25. package/docs/Reference/Hooks.md +31 -30
  26. package/docs/Reference/LTS.md +10 -15
  27. package/docs/Reference/Lifecycle.md +19 -24
  28. package/docs/Reference/Logging.md +59 -56
  29. package/docs/Reference/Middleware.md +19 -19
  30. package/docs/Reference/Plugins.md +55 -71
  31. package/docs/Reference/Principles.md +25 -30
  32. package/docs/Reference/Reply.md +11 -10
  33. package/docs/Reference/Request.md +89 -99
  34. package/docs/Reference/Routes.md +108 -128
  35. package/docs/Reference/Server.md +19 -17
  36. package/docs/Reference/Type-Providers.md +19 -21
  37. package/docs/Reference/TypeScript.md +1 -18
  38. package/docs/Reference/Validation-and-Serialization.md +134 -159
  39. package/docs/Reference/Warnings.md +22 -25
  40. package/fastify.js +1 -1
  41. package/lib/contentTypeParser.js +7 -8
  42. package/lib/error-handler.js +14 -12
  43. package/lib/errors.js +4 -0
  44. package/lib/headRoute.js +4 -2
  45. package/lib/pluginUtils.js +4 -2
  46. package/lib/reply.js +4 -0
  47. package/lib/request.js +13 -9
  48. package/lib/server.js +5 -0
  49. package/lib/validation.js +1 -1
  50. package/lib/warnings.js +9 -0
  51. package/lib/wrapThenable.js +8 -1
  52. package/package.json +28 -17
  53. package/test/build/error-serializer.test.js +2 -1
  54. package/test/bundler/esbuild/package.json +1 -1
  55. package/test/close.test.js +125 -108
  56. package/test/custom-parser-async.test.js +34 -36
  57. package/test/custom-parser.2.test.js +19 -20
  58. package/test/custom-parser.3.test.js +56 -45
  59. package/test/delete.test.js +79 -67
  60. package/test/genReqId.test.js +125 -174
  61. package/test/has-route.test.js +1 -3
  62. package/test/internals/content-type-parser.test.js +1 -1
  63. package/test/internals/errors.test.js +19 -7
  64. package/test/issue-4959.test.js +84 -0
  65. package/test/listen.1.test.js +37 -34
  66. package/test/listen.2.test.js +47 -40
  67. package/test/listen.3.test.js +28 -32
  68. package/test/listen.4.test.js +61 -45
  69. package/test/listen.5.test.js +23 -0
  70. package/test/nullable-validation.test.js +30 -27
  71. package/test/register.test.js +55 -50
  72. package/test/request-error.test.js +114 -94
  73. package/test/route-shorthand.test.js +36 -32
  74. package/test/server.test.js +0 -175
  75. package/test/stream.5.test.js +35 -33
  76. package/test/throw.test.js +87 -91
  77. package/test/toolkit.js +32 -0
  78. package/test/trust-proxy.test.js +23 -23
  79. package/test/types/instance.test-d.ts +1 -0
  80. package/test/upgrade.test.js +32 -30
  81. package/test/web-api.test.js +44 -0
  82. package/types/instance.d.ts +4 -0
  83. package/test/test-reporter.mjs +0 -68
@@ -151,7 +151,7 @@ fastify.get('/', async function (req, rep) {
151
151
  Sets a response header. If the value is omitted or undefined, it is coerced to
152
152
  `''`.
153
153
 
154
- > Note: the header's value must be properly encoded using
154
+ > 🛈 Note: The header's value must be properly encoded using
155
155
  > [`encodeURI`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI)
156
156
  > or similar modules such as
157
157
  > [`encodeurl`](https://www.npmjs.com/package/encodeurl). Invalid characters
@@ -260,11 +260,11 @@ requires heavy resources to be sent after the `data`, for example,
260
260
  `Server-Timing` and `Etag`. It can ensure the client receives the response data
261
261
  as soon as possible.
262
262
 
263
- *Note: The header `Transfer-Encoding: chunked` will be added once you use the
264
- trailer. It is a hard requirement for using trailer in Node.js.*
263
+ > 🛈 Note: The header `Transfer-Encoding: chunked` will be added once you use
264
+ > the trailer. It is a hard requirement for using trailer in Node.js.
265
265
 
266
- *Note: Any error passed to `done` callback will be ignored. If you interested
267
- in the error, you can turn on `debug` level logging.*
266
+ > 🛈 Note: Any error passed to `done` callback will be ignored. If you interested
267
+ > in the error, you can turn on `debug` level logging.*
268
268
 
269
269
  ```js
270
270
  reply.trailer('server-timing', function() {
@@ -314,7 +314,7 @@ reply.getTrailer('server-timing') // undefined
314
314
  Redirects a request to the specified URL, the status code is optional, default
315
315
  to `302` (if status code is not already set by calling `code`).
316
316
 
317
- > Note: the input URL must be properly encoded using
317
+ > 🛈 Note: The input URL must be properly encoded using
318
318
  > [`encodeURI`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI)
319
319
  > or similar modules such as
320
320
  > [`encodeurl`](https://www.npmjs.com/package/encodeurl). Invalid URLs will
@@ -362,7 +362,8 @@ Sets the content type for the response. This is a shortcut for
362
362
  reply.type('text/html')
363
363
  ```
364
364
  If the `Content-Type` has a JSON subtype, and the charset parameter is not set,
365
- `utf-8` will be used as the charset by default.
365
+ `utf-8` will be used as the charset by default. For other content types, the
366
+ charset must be set explicitly.
366
367
 
367
368
  ### .getSerializationFunction(schema | httpStatus, [contentType])
368
369
  <a id="getserializationfunction"></a>
@@ -822,8 +823,8 @@ automatically create an error structured as the following:
822
823
  You can add custom properties to the Error object, such as `headers`, that will
823
824
  be used to enhance the HTTP response.
824
825
 
825
- *Note: If you are passing an error to `send` and the statusCode is less than
826
- 400, Fastify will automatically set it at 500.*
826
+ > 🛈 Note: If you are passing an error to `send` and the statusCode is less than
827
+ > 400, Fastify will automatically set it at 500.
827
828
 
828
829
  Tip: you can simplify errors by using the
829
830
  [`http-errors`](https://npm.im/http-errors) module or
@@ -870,7 +871,7 @@ fastify.get('/', {
870
871
  If you want to customize error handling, check out
871
872
  [`setErrorHandler`](./Server.md#seterrorhandler) API.
872
873
 
873
- *Note: you are responsible for logging when customizing the error handler*
874
+ > 🛈 Note: you are responsible for logging when customizing the error handler.
874
875
 
875
876
  API:
876
877
 
@@ -4,75 +4,71 @@
4
4
  The first parameter of the handler function is `Request`.
5
5
 
6
6
  Request is a core Fastify object containing the following fields:
7
- - `query` - the parsed querystring, its format is specified by
8
- [`querystringParser`](./Server.md#querystringparser)
9
- - `body` - the request payload, see [Content-Type
10
- Parser](./ContentTypeParser.md) for details on what request payloads Fastify
11
- natively parses and how to support other content types
12
- - `params` - the params matching the URL
13
- - [`headers`](#headers) - the headers getter and setter
14
- - `raw` - the incoming HTTP request from Node core
15
- - `server` - The Fastify server instance, scoped to the current [encapsulation
16
- context](./Encapsulation.md)
17
- - `id` - the request ID
18
- - `log` - the logger instance of the incoming request
19
- - `ip` - the IP address of the incoming request
20
- - `ips` - an array of the IP addresses, ordered from closest to furthest, in the
7
+ - `query` - The parsed querystring, its format is specified by
8
+ [`querystringParser`](./Server.md#querystringparser).
9
+ - `body` - The request payload, see [Content-Type Parser](./ContentTypeParser.md)
10
+ for details on what request payloads Fastify natively parses and how to support
11
+ other content types.
12
+ - `params` - The params matching the URL.
13
+ - [`headers`](#headers) - The headers getter and setter.
14
+ - `raw` - The incoming HTTP request from Node core.
15
+ - `server` - The Fastify server instance, scoped to the current
16
+ [encapsulation context](./Encapsulation.md).
17
+ - `id` - The request ID.
18
+ - `log` - The logger instance of the incoming request.
19
+ - `ip` - The IP address of the incoming request.
20
+ - `ips` - An array of the IP addresses, ordered from closest to furthest, in the
21
21
  `X-Forwarded-For` header of the incoming request (only when the
22
- [`trustProxy`](./Server.md#factory-trust-proxy) option is enabled)
23
- - `host` - the host of the incoming request (derived from `X-Forwarded-Host`
22
+ [`trustProxy`](./Server.md#factory-trust-proxy) option is enabled).
23
+ - `host` - The host of the incoming request (derived from `X-Forwarded-Host`
24
24
  header when the [`trustProxy`](./Server.md#factory-trust-proxy) option is
25
- enabled). For HTTP/2 compatibility it returns `:authority` if no host header
26
- exists. The host header may return empty string when using
27
- `requireHostHeader = false`, not suppied when connected with `HTTP/1.0` or
28
- using schema validation that remove the extra headers.
29
- - `hostname` - the host of the `host` property, it may refers the incoming
30
- request hostname
31
- - `port` - the port of the `host` property, it may refers the port thats
32
- the server is listening on
33
- - `protocol` - the protocol of the incoming request (`https` or `http`)
34
- - `method` - the method of the incoming request
35
- - `url` - the URL of the incoming request
36
- - `originalUrl` - similar to `url`, this allows you to access the
37
- original `url` in case of internal re-routing
38
- - `is404` - true if request is being handled by 404 handler, false if it is not
39
- - `socket` - the underlying connection of the incoming request
40
- - `context` - Deprecated, use `request.routeOptions.config` instead.
41
- A Fastify internal object. You should not use
42
- it directly or modify it. It is useful to access one special key:
25
+ enabled). For HTTP/2 compatibility, it returns `:authority` if no host header
26
+ exists. The host header may return an empty string if `requireHostHeader` is
27
+ `false`, not provided with HTTP/1.0, or removed by schema validation.
28
+ - `hostname` - The hostname derived from the `host` property of the incoming request.
29
+ - `port` - The port from the `host` property, which may refer to the port the
30
+ server is listening on.
31
+ - `protocol` - The protocol of the incoming request (`https` or `http`).
32
+ - `method` - The method of the incoming request.
33
+ - `url` - The URL of the incoming request.
34
+ - `originalUrl` - Similar to `url`, allows access to the original `url` in
35
+ case of internal re-routing.
36
+ - `is404` - `true` if request is being handled by 404 handler, `false` otherwise.
37
+ - `socket` - The underlying connection of the incoming request.
38
+ - `context` - Deprecated, use `request.routeOptions.config` instead. A Fastify
39
+ internal object. Do not use or modify it directly. It is useful to access one
40
+ special key:
43
41
  - `context.config` - The route [`config`](./Routes.md#routes-config) object.
44
- - `routeOptions` - The route [`option`](./Routes.md#routes-options) object
45
- - `bodyLimit` - either server limit or route limit
46
- - `config` - the [`config`](./Routes.md#routes-config) object for this route
47
- - `method` - the http method for the route
48
- - `url` - the path of the URL to match this route
49
- - `handler` - the handler for this route
50
- - `attachValidation` - attach `validationError` to request
51
- (if there is a schema defined)
52
- - `logLevel` - log level defined for this route
53
- - `schema` - the JSON schemas definition for this route
54
- - `version` - a semver compatible string that defines the version of the endpoint
55
- - `exposeHeadRoute` - creates a sibling HEAD route for any GET routes
56
- - `prefixTrailingSlash` - string used to determine how to handle passing /
42
+ - `routeOptions` - The route [`option`](./Routes.md#routes-options) object.
43
+ - `bodyLimit` - Either server limit or route limit.
44
+ - `config` - The [`config`](./Routes.md#routes-config) object for this route.
45
+ - `method` - The HTTP method for the route.
46
+ - `url` - The path of the URL to match this route.
47
+ - `handler` - The handler for this route.
48
+ - `attachValidation` - Attach `validationError` to request (if there is
49
+ a schema defined).
50
+ - `logLevel` - Log level defined for this route.
51
+ - `schema` - The JSON schemas definition for this route.
52
+ - `version` - A semver compatible string that defines the version of the endpoint.
53
+ - `exposeHeadRoute` - Creates a sibling HEAD route for any GET routes.
54
+ - `prefixTrailingSlash` - String used to determine how to handle passing `/`
57
55
  as a route with a prefix.
58
56
  - [.getValidationFunction(schema | httpPart)](#getvalidationfunction) -
59
- Returns a validation function for the specified schema or http part,
60
- if any of either are set or cached.
57
+ Returns a validation function for the specified schema or HTTP part, if
58
+ set or cached.
61
59
  - [.compileValidationSchema(schema, [httpPart])](#compilevalidationschema) -
62
- Compiles the specified schema and returns a validation function
63
- using the default (or customized) `ValidationCompiler`.
64
- The optional `httpPart` is forwarded to the `ValidationCompiler`
65
- if provided, defaults to `null`.
60
+ Compiles the specified schema and returns a validation function using the
61
+ default (or customized) `ValidationCompiler`. The optional `httpPart` is
62
+ forwarded to the `ValidationCompiler` if provided, defaults to `null`.
66
63
  - [.validateInput(data, schema | httpPart, [httpPart])](#validate) -
67
- Validates the specified input by using the specified
68
- schema and returns the serialized payload. If the optional
69
- `httpPart` is provided, the function will use the serializer
70
- function given for that HTTP Status Code. Defaults to `null`.
64
+ Validates the input using the specified schema and returns the serialized
65
+ payload. If `httpPart` is provided, the function uses the serializer for
66
+ that HTTP Status Code. Defaults to `null`.
71
67
 
72
68
  ### Headers
73
69
 
74
- The `request.headers` is a getter that returns an Object with the headers of the
75
- incoming request. You can set custom headers like this:
70
+ The `request.headers` is a getter that returns an object with the headers of the
71
+ incoming request. Set custom headers as follows:
76
72
 
77
73
  ```js
78
74
  request.headers = {
@@ -81,15 +77,15 @@ request.headers = {
81
77
  }
82
78
  ```
83
79
 
84
- This operation will add to the request headers the new values that can be read
85
- calling `request.headers.bar`. Moreover, you can still access the standard
86
- request's headers with the `request.raw.headers` property.
80
+ This operation adds new values to the request headers, accessible via
81
+ `request.headers.bar`. Standard request headers remain accessible via
82
+ `request.raw.headers`.
87
83
 
88
- > Note: For performance reason on `not found` route, you may see that we will
89
- add an extra property `Symbol('fastify.RequestAcceptVersion')` on the headers.
84
+ For performance reasons, `Symbol('fastify.RequestAcceptVersion')` may be added
85
+ to headers on `not found` routes.
90
86
 
91
- > Note: When using schema, it may mutate the `request.headers` and
92
- `request.raw.headers` object. So, you may found the headers becomes empty.
87
+ > 🛈 Note: Schema validation may mutate the `request.headers` and
88
+ > `request.raw.headers` objects, causing the headers to become empty.
93
89
 
94
90
  ```js
95
91
  fastify.post('/:params', options, function (request, reply) {
@@ -123,13 +119,12 @@ fastify.post('/:params', options, function (request, reply) {
123
119
  ### .getValidationFunction(schema | httpPart)
124
120
  <a id="getvalidationfunction"></a>
125
121
 
126
- By calling this function using a provided `schema` or `httpPart`,
127
- it will return a `validation` function that can be used to
128
- validate diverse inputs. It returns `undefined` if no
129
- serialization function was found using either of the provided inputs.
122
+ By calling this function with a provided `schema` or `httpPart`, it returns a
123
+ `validation` function to validate diverse inputs. It returns `undefined` if no
124
+ serialization function is found using the provided inputs.
130
125
 
131
- This function has property errors. Errors encountered during the last validation
132
- are assigned to errors
126
+ This function has an `errors` property. Errors encountered during the last
127
+ validation are assigned to `errors`.
133
128
 
134
129
  ```js
135
130
  const validate = request
@@ -152,24 +147,23 @@ console.log(validate({ foo: 0.5 })) // false
152
147
  console.log(validate.errors) // validation errors
153
148
  ```
154
149
 
155
- See [.compileValidationSchema(schema, [httpStatus])](#compilevalidationschema)
156
- for more information on how to compile validation function.
150
+ See [.compileValidationSchema(schema, [httpStatus])](#compileValidationSchema)
151
+ for more information on compiling validation schemas.
157
152
 
158
153
  ### .compileValidationSchema(schema, [httpPart])
159
154
  <a id="compilevalidationschema"></a>
160
155
 
161
- This function will compile a validation schema and
162
- return a function that can be used to validate data.
163
- The function returned (a.k.a. _validation function_) is compiled
164
- by using the provided [`SchemaController#ValidationCompiler`](./Server.md#schema-controller).
165
- A `WeakMap` is used to cached this, reducing compilation calls.
156
+ This function compiles a validation schema and returns a function to validate data.
157
+ The returned function (a.k.a. _validation function_) is compiled using the provided
158
+ [`SchemaController#ValidationCompiler`](./Server.md#schema-controller). A `WeakMap`
159
+ is used to cache this, reducing compilation calls.
166
160
 
167
- The optional parameter `httpPart`, if provided, is forwarded directly
168
- the `ValidationCompiler`, so it can be used to compile the validation
169
- function if a custom `ValidationCompiler` is provided for the route.
161
+ The optional parameter `httpPart`, if provided, is forwarded to the
162
+ `ValidationCompiler`, allowing it to compile the validation function if a custom
163
+ `ValidationCompiler` is provided for the route.
170
164
 
171
- This function has property errors. Errors encountered during the last validation
172
- are assigned to errors
165
+ This function has an `errors` property. Errors encountered during the last
166
+ validation are assigned to `errors`.
173
167
 
174
168
  ```js
175
169
  const validate = request
@@ -199,16 +193,13 @@ console.log(validate({ hello: 'world' })) // false
199
193
  console.log(validate.errors) // validation errors
200
194
  ```
201
195
 
202
- Note that you should be careful when using this function, as it will cache
203
- the compiled validation functions based on the schema provided. If the
204
- schemas provided are mutated or changed, the validation functions will not
205
- detect that the schema has been altered and for instance it will reuse the
206
- previously compiled validation function, as the cache is based on
207
- the reference of the schema (Object) previously provided.
196
+ Be careful when using this function, as it caches compiled validation functions
197
+ based on the provided schema. If schemas are mutated or changed, the validation
198
+ functions will not detect the alterations and will reuse the previously compiled
199
+ validation function, as the cache is based on the schema's reference.
208
200
 
209
- If there is a need to change the properties of a schema, always opt to create
210
- a totally new schema (object), otherwise the implementation will not benefit from
211
- the cache mechanism.
201
+ If schema properties need to be changed, create a new schema object to benefit
202
+ from the cache mechanism.
212
203
 
213
204
  Using the following schema as an example:
214
205
  ```js
@@ -249,12 +240,11 @@ console.log(newValidate === validate) // false
249
240
  ### .validateInput(data, [schema | httpStatus], [httpStatus])
250
241
  <a id="validate"></a>
251
242
 
252
- This function will validate the input based on the provided schema,
253
- or HTTP part passed. If both are provided, the `httpPart` parameter
254
- will take precedence.
243
+ This function validates the input based on the provided schema or HTTP part. If
244
+ both are provided, the `httpPart` parameter takes precedence.
255
245
 
256
- If there is not a validation function for a given `schema`, a new validation
257
- function will be compiled, forwarding the `httpPart` if provided.
246
+ If no validation function exists for a given `schema`, a new validation function
247
+ will be compiled, forwarding the `httpPart` if provided.
258
248
 
259
249
  ```js
260
250
  request
@@ -286,4 +276,4 @@ request
286
276
  ```
287
277
 
288
278
  See [.compileValidationSchema(schema, [httpStatus])](#compileValidationSchema)
289
- for more information on how to compile validation schemas.
279
+ for more information on compiling validation schemas.