fastify 3.24.0 → 3.25.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.
- package/README.md +30 -29
- package/docs/{Benchmarking.md → Guides/Benchmarking.md} +14 -5
- package/docs/Guides/Ecosystem.md +513 -0
- package/docs/{Fluent-Schema.md → Guides/Fluent-Schema.md} +16 -7
- package/docs/{Getting-Started.md → Guides/Getting-Started.md} +180 -60
- package/docs/Guides/Index.md +30 -4
- package/docs/{Migration-Guide-V3.md → Guides/Migration-Guide-V3.md} +43 -37
- package/docs/{Plugins-Guide.md → Guides/Plugins-Guide.md} +196 -82
- package/docs/{Recommendations.md → Guides/Recommendations.md} +17 -10
- package/docs/{Serverless.md → Guides/Serverless.md} +200 -42
- package/docs/Guides/Style-Guide.md +246 -0
- package/docs/{Testing.md → Guides/Testing.md} +26 -12
- package/docs/Guides/Write-Plugin.md +102 -0
- package/docs/{ContentTypeParser.md → Reference/ContentTypeParser.md} +68 -30
- package/docs/{Decorators.md → Reference/Decorators.md} +52 -47
- package/docs/{Encapsulation.md → Reference/Encapsulation.md} +3 -3
- package/docs/{Errors.md → Reference/Errors.md} +77 -47
- package/docs/{HTTP2.md → Reference/HTTP2.md} +13 -13
- package/docs/{Hooks.md → Reference/Hooks.md} +157 -70
- package/docs/Reference/Index.md +71 -0
- package/docs/{LTS.md → Reference/LTS.md} +31 -32
- package/docs/{Lifecycle.md → Reference/Lifecycle.md} +15 -7
- package/docs/{Logging.md → Reference/Logging.md} +68 -28
- package/docs/Reference/Middleware.md +78 -0
- package/docs/{Plugins.md → Reference/Plugins.md} +91 -34
- package/docs/{Reply.md → Reference/Reply.md} +205 -94
- package/docs/{Request.md → Reference/Request.md} +32 -16
- package/docs/{Routes.md → Reference/Routes.md} +243 -113
- package/docs/{Server.md → Reference/Server.md} +516 -267
- package/docs/{TypeScript.md → Reference/TypeScript.md} +451 -191
- package/docs/{Validation-and-Serialization.md → Reference/Validation-and-Serialization.md} +178 -86
- package/docs/index.md +24 -0
- package/examples/typescript-server.ts +1 -1
- package/fastify.js +2 -3
- package/lib/contentTypeParser.js +11 -6
- package/lib/decorate.js +6 -3
- package/lib/logger.js +1 -1
- package/lib/route.js +1 -1
- package/lib/server.js +9 -8
- package/package.json +9 -4
- package/test/als.test.js +74 -0
- package/test/constrained-routes.test.js +220 -0
- package/test/custom-parser.test.js +11 -2
- package/test/decorator.test.js +38 -0
- package/test/handler-context.test.js +11 -4
- package/test/http2/closing.test.js +14 -5
- package/test/http2/constraint.test.js +91 -0
- package/test/listen.test.js +36 -22
- package/test/logger.test.js +16 -0
- package/test/maxRequestsPerSocket.test.js +10 -0
- package/test/request-error.test.js +2 -8
- package/test/requestTimeout.test.js +4 -1
- package/test/router-options.test.js +10 -1
- package/test/schema-feature.test.js +146 -0
- package/test/stream.test.js +14 -3
- package/test/trust-proxy.test.js +15 -7
- package/test/types/instance.test-d.ts +52 -1
- package/test/types/request.test-d.ts +7 -1
- package/test/types/route.test-d.ts +21 -0
- package/types/hooks.d.ts +12 -1
- package/types/instance.d.ts +16 -6
- package/types/request.d.ts +4 -1
- package/types/route.d.ts +1 -1
- package/docs/Ecosystem.md +0 -211
- package/docs/Middleware.md +0 -53
- package/docs/Style-Guide.md +0 -185
- package/docs/Write-Plugin.md +0 -58
|
@@ -1,113 +1,162 @@
|
|
|
1
1
|
<h1 align="center">Fastify</h1>
|
|
2
2
|
|
|
3
|
-
<a name="factory"></a>
|
|
4
3
|
## Factory
|
|
4
|
+
<a id="factory"></a>
|
|
5
5
|
|
|
6
6
|
The Fastify module exports a factory function that is used to create new
|
|
7
|
-
<code><b>Fastify server</b></code> instances. This factory function accepts
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
- [
|
|
12
|
-
- [
|
|
13
|
-
- [
|
|
14
|
-
- [
|
|
15
|
-
- [
|
|
16
|
-
- [
|
|
17
|
-
- [
|
|
18
|
-
- [
|
|
19
|
-
- [
|
|
20
|
-
- [
|
|
21
|
-
- [
|
|
22
|
-
- [
|
|
23
|
-
- [
|
|
24
|
-
- [
|
|
25
|
-
- [
|
|
26
|
-
- [
|
|
27
|
-
- [
|
|
28
|
-
- [
|
|
29
|
-
- [
|
|
30
|
-
- [
|
|
31
|
-
- [
|
|
32
|
-
- [
|
|
33
|
-
- [
|
|
34
|
-
- [
|
|
35
|
-
- [
|
|
36
|
-
- [
|
|
37
|
-
- [
|
|
38
|
-
- [
|
|
39
|
-
- [
|
|
40
|
-
- [
|
|
41
|
-
- [
|
|
42
|
-
- [
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
7
|
+
<code><b>Fastify server</b></code> instances. This factory function accepts an
|
|
8
|
+
options object which is used to customize the resulting instance. This document
|
|
9
|
+
describes the properties available in that options object.
|
|
10
|
+
|
|
11
|
+
- [Factory](#factory)
|
|
12
|
+
- [`http2`](#http2)
|
|
13
|
+
- [`https`](#https)
|
|
14
|
+
- [`connectionTimeout`](#connectiontimeout)
|
|
15
|
+
- [`keepAliveTimeout`](#keepalivetimeout)
|
|
16
|
+
- [`maxRequestsPerSocket`](#maxrequestspersocket)
|
|
17
|
+
- [`requestTimeout`](#requesttimeout)
|
|
18
|
+
- [`ignoreTrailingSlash`](#ignoretrailingslash)
|
|
19
|
+
- [`maxParamLength`](#maxparamlength)
|
|
20
|
+
- [`bodyLimit`](#bodylimit)
|
|
21
|
+
- [`onProtoPoisoning`](#onprotopoisoning)
|
|
22
|
+
- [`onConstructorPoisoning`](#onconstructorpoisoning)
|
|
23
|
+
- [`logger`](#logger)
|
|
24
|
+
- [`disableRequestLogging`](#disablerequestlogging)
|
|
25
|
+
- [`serverFactory`](#serverfactory)
|
|
26
|
+
- [`jsonShorthand`](#jsonshorthand)
|
|
27
|
+
- [`caseSensitive`](#casesensitive)
|
|
28
|
+
- [`requestIdHeader`](#requestidheader)
|
|
29
|
+
- [`requestIdLogLabel`](#requestidloglabel)
|
|
30
|
+
- [`genReqId`](#genreqid)
|
|
31
|
+
- [`trustProxy`](#trustproxy)
|
|
32
|
+
- [`pluginTimeout`](#plugintimeout)
|
|
33
|
+
- [`querystringParser`](#querystringparser)
|
|
34
|
+
- [`exposeHeadRoutes`](#exposeheadroutes)
|
|
35
|
+
- [`constraints`](#constraints)
|
|
36
|
+
- [`return503OnClosing`](#return503onclosing)
|
|
37
|
+
- [`ajv`](#ajv)
|
|
38
|
+
- [`serializerOpts`](#serializeropts)
|
|
39
|
+
- [`http2SessionTimeout`](#http2sessiontimeout)
|
|
40
|
+
- [`frameworkErrors`](#frameworkerrors)
|
|
41
|
+
- [`clientErrorHandler`](#clienterrorhandler)
|
|
42
|
+
- [`rewriteUrl`](#rewriteurl)
|
|
43
|
+
- [Instance](#instance)
|
|
44
|
+
- [Server Methods](#server-methods)
|
|
45
|
+
- [server](#server)
|
|
46
|
+
- [after](#after)
|
|
47
|
+
- [ready](#ready)
|
|
48
|
+
- [listen](#listen)
|
|
49
|
+
- [getDefaultRoute](#getdefaultroute)
|
|
50
|
+
- [setDefaultRoute](#setdefaultroute)
|
|
51
|
+
- [routing](#routing)
|
|
52
|
+
- [route](#route)
|
|
53
|
+
- [close](#close)
|
|
54
|
+
- [decorate*](#decorate)
|
|
55
|
+
- [register](#register)
|
|
56
|
+
- [addHook](#addhook)
|
|
57
|
+
- [prefix](#prefix)
|
|
58
|
+
- [pluginName](#pluginname)
|
|
59
|
+
- [log](#log)
|
|
60
|
+
- [version](#version)
|
|
61
|
+
- [inject](#inject)
|
|
62
|
+
- [addSchema](#addschema)
|
|
63
|
+
- [getSchemas](#getschemas)
|
|
64
|
+
- [getSchema](#getschema)
|
|
65
|
+
- [setReplySerializer](#setreplyserializer)
|
|
66
|
+
- [setValidatorCompiler](#setvalidatorcompiler)
|
|
67
|
+
- [setSchemaErrorFormatter](#setschemaerrorformatter)
|
|
68
|
+
- [setSerializerCompiler](#setserializercompiler)
|
|
69
|
+
- [validatorCompiler](#validatorcompiler)
|
|
70
|
+
- [serializerCompiler](#serializercompiler)
|
|
71
|
+
- [schemaErrorFormatter](#schemaerrorformatter)
|
|
72
|
+
- [schemaController](#schemacontroller)
|
|
73
|
+
- [Ajv 8 as default schema validator](#ajv-8-as-default-schema-validator)
|
|
74
|
+
- [setNotFoundHandler](#setnotfoundhandler)
|
|
75
|
+
- [setErrorHandler](#seterrorhandler)
|
|
76
|
+
- [printRoutes](#printroutes)
|
|
77
|
+
- [printPlugins](#printplugins)
|
|
78
|
+
- [addContentTypeParser](#addcontenttypeparser)
|
|
79
|
+
- [getDefaultJsonParser](#getdefaultjsonparser)
|
|
80
|
+
- [defaultTextParser](#defaulttextparser)
|
|
81
|
+
- [errorHandler](#errorhandler)
|
|
82
|
+
- [initialConfig](#initialconfig)
|
|
83
|
+
|
|
46
84
|
### `http2`
|
|
85
|
+
<a id="factory-http2"></a>
|
|
47
86
|
|
|
48
|
-
If `true` Node.js core's
|
|
87
|
+
If `true` Node.js core's
|
|
88
|
+
[HTTP/2](https://nodejs.org/dist/latest-v14.x/docs/api/http2.html) module is
|
|
89
|
+
used for binding the socket.
|
|
49
90
|
|
|
50
91
|
+ Default: `false`
|
|
51
92
|
|
|
52
|
-
<a name="factory-https"></a>
|
|
53
93
|
### `https`
|
|
94
|
+
<a id="factory-https"></a>
|
|
54
95
|
|
|
55
96
|
An object used to configure the server's listening socket for TLS. The options
|
|
56
|
-
are the same as the Node.js core
|
|
57
|
-
|
|
97
|
+
are the same as the Node.js core [`createServer`
|
|
98
|
+
method](https://nodejs.org/dist/latest-v14.x/docs/api/https.html#https_https_createserver_options_requestlistener).
|
|
58
99
|
When this property is `null`, the socket will not be configured for TLS.
|
|
59
100
|
|
|
60
|
-
This option also applies when the
|
|
61
|
-
<a href="./Server.md#factory-http2">
|
|
62
|
-
<code><b>http2</b></code>
|
|
63
|
-
</a> option is set.
|
|
101
|
+
This option also applies when the [`http2`](#factory-http2) option is set.
|
|
64
102
|
|
|
65
103
|
+ Default: `null`
|
|
66
104
|
|
|
67
|
-
<a name="factory-connection-timeout"></a>
|
|
68
105
|
### `connectionTimeout`
|
|
106
|
+
<a id="factory-connection-timeout"></a>
|
|
69
107
|
|
|
70
108
|
Defines the server timeout in milliseconds. See documentation for
|
|
71
|
-
[`server.timeout`
|
|
72
|
-
to understand
|
|
73
|
-
|
|
109
|
+
[`server.timeout`
|
|
110
|
+
property](https://nodejs.org/api/http.html#http_server_timeout) to understand
|
|
111
|
+
the effect of this option. When `serverFactory` option is specified, this option
|
|
112
|
+
is ignored.
|
|
74
113
|
|
|
75
114
|
+ Default: `0` (no timeout)
|
|
76
115
|
|
|
77
|
-
<a name="factory-keep-alive-timeout"></a>
|
|
78
116
|
### `keepAliveTimeout`
|
|
117
|
+
<a id="factory-keep-alive-timeout"></a>
|
|
79
118
|
|
|
80
119
|
Defines the server keep-alive timeout in milliseconds. See documentation for
|
|
81
|
-
[`server.keepAliveTimeout`
|
|
82
|
-
|
|
83
|
-
|
|
120
|
+
[`server.keepAliveTimeout`
|
|
121
|
+
property](https://nodejs.org/api/http.html#http_server_keepalivetimeout) to
|
|
122
|
+
understand the effect of this option. This option only applies when HTTP/1 is in
|
|
123
|
+
use. Also, when `serverFactory` option is specified, this option is ignored.
|
|
84
124
|
|
|
85
125
|
+ Default: `5000` (5 seconds)
|
|
86
126
|
|
|
87
|
-
<a name="factory-max-requests-per-socket"></a>
|
|
88
127
|
### `maxRequestsPerSocket`
|
|
128
|
+
<a id="factory-max-requests-per-socket"></a>
|
|
89
129
|
|
|
90
|
-
Defines the maximum number of requests socket can handle before closing keep
|
|
91
|
-
[`server.maxRequestsPerSocket`
|
|
130
|
+
Defines the maximum number of requests socket can handle before closing keep
|
|
131
|
+
alive connection. See documentation for [`server.maxRequestsPerSocket`
|
|
132
|
+
property](https://nodejs.org/dist/latest/docs/api/http.html#http_server_maxrequestspersocket)
|
|
92
133
|
to understand the effect of this option. This option only applies when HTTP/1.1
|
|
93
|
-
is in use. Also, when `serverFactory` option is specified, this option is
|
|
94
|
-
|
|
134
|
+
is in use. Also, when `serverFactory` option is specified, this option is
|
|
135
|
+
ignored.
|
|
136
|
+
> At the time of this writing, only node version greater or equal to 16.10.0
|
|
137
|
+
> support this option. Check the Node.js documentation for availability in the
|
|
138
|
+
> version you are running.
|
|
95
139
|
|
|
96
140
|
+ Default: `0` (no limit)
|
|
97
141
|
|
|
98
|
-
<a name="factory-request-timeout"></a>
|
|
99
142
|
### `requestTimeout`
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
143
|
+
<a id="factory-request-timeout"></a>
|
|
144
|
+
|
|
145
|
+
Defines the maximum number of milliseconds for receiving the entire request from
|
|
146
|
+
the client. [`server.requestTimeout`
|
|
147
|
+
property](https://nodejs.org/dist/latest/docs/api/http.html#http_server_requesttimeout)
|
|
148
|
+
to understand the effect of this option. Also, when `serverFactory` option is
|
|
149
|
+
specified, this option is ignored. It must be set to a non-zero value (e.g. 120
|
|
150
|
+
seconds) to protect against potential Denial-of-Service attacks in case the
|
|
151
|
+
server is deployed without a reverse proxy in front.
|
|
152
|
+
> At the time of this writing, only node version greater or equal to 14.11.0
|
|
153
|
+
> support this option. Check the Node.js documentation for availability in the
|
|
154
|
+
> version you are running.
|
|
106
155
|
|
|
107
156
|
+ Default: `0` (no limit)
|
|
108
157
|
|
|
109
|
-
<a name="factory-ignore-slash"></a>
|
|
110
158
|
### `ignoreTrailingSlash`
|
|
159
|
+
<a id="factory-ignore-slash"></a>
|
|
111
160
|
|
|
112
161
|
Fastify uses [find-my-way](https://github.com/delvedor/find-my-way) to handle
|
|
113
162
|
routing. This option may be set to `true` to ignore trailing slashes in routes.
|
|
@@ -132,47 +181,54 @@ fastify.get('/bar', function (req, reply) {
|
|
|
132
181
|
})
|
|
133
182
|
```
|
|
134
183
|
|
|
135
|
-
<a name="factory-max-param-length"></a>
|
|
136
184
|
### `maxParamLength`
|
|
137
|
-
|
|
138
|
-
|
|
185
|
+
<a id="factory-max-param-length"></a>
|
|
186
|
+
|
|
187
|
+
You can set a custom length for parameters in parametric (standard, regex, and
|
|
188
|
+
multi) routes by using `maxParamLength` option; the default value is 100
|
|
189
|
+
characters.
|
|
190
|
+
|
|
191
|
+
This can be useful especially if you have some regex based route, protecting you
|
|
192
|
+
against [DoS
|
|
193
|
+
attacks](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS).
|
|
194
|
+
|
|
139
195
|
*If the maximum length limit is reached, the not found route will be invoked.*
|
|
140
196
|
|
|
141
|
-
<a name="factory-body-limit"></a>
|
|
142
197
|
### `bodyLimit`
|
|
198
|
+
<a id="factory-body-limit"></a>
|
|
143
199
|
|
|
144
200
|
Defines the maximum payload, in bytes, the server is allowed to accept.
|
|
145
201
|
|
|
146
202
|
+ Default: `1048576` (1MiB)
|
|
147
203
|
|
|
148
|
-
<a name="factory-on-proto-poisoning"></a>
|
|
149
204
|
### `onProtoPoisoning`
|
|
205
|
+
<a id="factory-on-proto-poisoning"></a>
|
|
150
206
|
|
|
151
|
-
Defines what action the framework must take when parsing a JSON object
|
|
152
|
-
|
|
153
|
-
[secure-json-parse](https://github.com/fastify/secure-json-parse).
|
|
154
|
-
|
|
155
|
-
|
|
207
|
+
Defines what action the framework must take when parsing a JSON object with
|
|
208
|
+
`__proto__`. This functionality is provided by
|
|
209
|
+
[secure-json-parse](https://github.com/fastify/secure-json-parse). See
|
|
210
|
+
https://hueniverse.com/a-tale-of-prototype-poisoning-2610fa170061 for more
|
|
211
|
+
details about prototype poisoning attacks.
|
|
156
212
|
|
|
157
213
|
Possible values are `'error'`, `'remove'` and `'ignore'`.
|
|
158
214
|
|
|
159
215
|
+ Default: `'error'`
|
|
160
216
|
|
|
161
|
-
<a name="factory-on-constructor-poisoning"></a>
|
|
162
217
|
### `onConstructorPoisoning`
|
|
218
|
+
<a id="factory-on-constructor-poisoning"></a>
|
|
163
219
|
|
|
164
|
-
Defines what action the framework must take when parsing a JSON object
|
|
165
|
-
|
|
166
|
-
[secure-json-parse](https://github.com/fastify/secure-json-parse).
|
|
167
|
-
|
|
168
|
-
|
|
220
|
+
Defines what action the framework must take when parsing a JSON object with
|
|
221
|
+
`constructor`. This functionality is provided by
|
|
222
|
+
[secure-json-parse](https://github.com/fastify/secure-json-parse). See
|
|
223
|
+
https://hueniverse.com/a-tale-of-prototype-poisoning-2610fa170061 for more
|
|
224
|
+
details about prototype poisoning attacks.
|
|
169
225
|
|
|
170
226
|
Possible values are `'error'`, `'remove'` and `'ignore'`.
|
|
171
227
|
|
|
172
228
|
+ Default: `'error'`
|
|
173
229
|
|
|
174
|
-
<a name="factory-logger"></a>
|
|
175
230
|
### `logger`
|
|
231
|
+
<a id="factory-logger"></a>
|
|
176
232
|
|
|
177
233
|
Fastify includes built-in logging via the [Pino](https://getpino.io/) logger.
|
|
178
234
|
This property is used to configure the internal logger instance.
|
|
@@ -180,15 +236,17 @@ This property is used to configure the internal logger instance.
|
|
|
180
236
|
The possible values this property may have are:
|
|
181
237
|
|
|
182
238
|
+ Default: `false`. The logger is disabled. All logging methods will point to a
|
|
183
|
-
null logger [abstract-logging](https://npm.im/abstract-logging) instance.
|
|
239
|
+
null logger [abstract-logging](https://npm.im/abstract-logging) instance.
|
|
184
240
|
|
|
185
241
|
+ `pinoInstance`: a previously instantiated instance of Pino. The internal
|
|
186
|
-
logger will point to this instance.
|
|
187
|
-
|
|
188
|
-
+ `object`: a standard Pino [options
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
242
|
+
logger will point to this instance.
|
|
243
|
+
|
|
244
|
+
+ `object`: a standard Pino [options
|
|
245
|
+
object](https://github.com/pinojs/pino/blob/c77d8ec5ce/docs/API.md#constructor).
|
|
246
|
+
This will be passed directly to the Pino constructor. If the following
|
|
247
|
+
properties are not present on the object, they will be added accordingly:
|
|
248
|
+
* `level`: the minimum logging level. If not set, it will be set to
|
|
249
|
+
`'info'`.
|
|
192
250
|
* `serializers`: a hash of serialization functions. By default, serializers
|
|
193
251
|
are added for `req` (incoming request objects), `res` (outgoing response
|
|
194
252
|
objects), and `err` (standard `Error` objects). When a log method receives
|
|
@@ -202,8 +260,9 @@ are not present on the object, they will be added accordingly:
|
|
|
202
260
|
```
|
|
203
261
|
Any user-supplied serializer will override the default serializer of the
|
|
204
262
|
corresponding property.
|
|
205
|
-
+ `loggerInstance`: a custom logger instance. The logger must conform to the
|
|
206
|
-
interface by having the following methods: `info`, `error`, `debug`,
|
|
263
|
+
+ `loggerInstance`: a custom logger instance. The logger must conform to the
|
|
264
|
+
Pino interface by having the following methods: `info`, `error`, `debug`,
|
|
265
|
+
`fatal`, `warn`, `trace`, `child`. For example:
|
|
207
266
|
```js
|
|
208
267
|
const pino = require('pino')();
|
|
209
268
|
|
|
@@ -224,13 +283,14 @@ interface by having the following methods: `info`, `error`, `debug`, `fatal`, `w
|
|
|
224
283
|
const fastify = require('fastify')({logger: customLogger});
|
|
225
284
|
```
|
|
226
285
|
|
|
227
|
-
<a name="factory-disable-request-logging"></a>
|
|
228
286
|
### `disableRequestLogging`
|
|
287
|
+
<a id="factory-disable-request-logging"></a>
|
|
288
|
+
|
|
229
289
|
By default, when logging is enabled, Fastify will issue an `info` level log
|
|
230
290
|
message when a request is received and when the response for that request has
|
|
231
|
-
been sent. By setting this option to `true`, these log messages will be
|
|
232
|
-
This allows for more flexible request start and end logging by
|
|
233
|
-
custom `onRequest` and `onResponse` hooks.
|
|
291
|
+
been sent. By setting this option to `true`, these log messages will be
|
|
292
|
+
disabled. This allows for more flexible request start and end logging by
|
|
293
|
+
attaching custom `onRequest` and `onResponse` hooks.
|
|
234
294
|
|
|
235
295
|
+ Default: `false`
|
|
236
296
|
|
|
@@ -247,12 +307,18 @@ fastify.addHook('onResponse', (req, reply, done) => {
|
|
|
247
307
|
})
|
|
248
308
|
```
|
|
249
309
|
|
|
250
|
-
Please note that this setting will also disable an error log written by the
|
|
310
|
+
Please note that this setting will also disable an error log written by the
|
|
311
|
+
default `onResponse` hook on reply callback errors.
|
|
251
312
|
|
|
252
|
-
<a name="custom-http-server"></a>
|
|
253
313
|
### `serverFactory`
|
|
254
|
-
|
|
255
|
-
|
|
314
|
+
<a id="custom-http-server"></a>
|
|
315
|
+
|
|
316
|
+
You can pass a custom HTTP server to Fastify by using the `serverFactory`
|
|
317
|
+
option.
|
|
318
|
+
|
|
319
|
+
`serverFactory` is a function that takes a `handler` parameter, which takes the
|
|
320
|
+
`request` and `response` objects as parameters, and an options object, which is
|
|
321
|
+
the same you have passed to Fastify.
|
|
256
322
|
|
|
257
323
|
```js
|
|
258
324
|
const serverFactory = (handler, opts) => {
|
|
@@ -272,14 +338,23 @@ fastify.get('/', (req, reply) => {
|
|
|
272
338
|
fastify.listen(3000)
|
|
273
339
|
```
|
|
274
340
|
|
|
275
|
-
Internally Fastify uses the API of Node core HTTP server, so if you are using a
|
|
341
|
+
Internally Fastify uses the API of Node core HTTP server, so if you are using a
|
|
342
|
+
custom server you must be sure to have the same API exposed. If not, you can
|
|
343
|
+
enhance the server instance inside the `serverFactory` function before the
|
|
344
|
+
`return` statement.
|
|
345
|
+
|
|
276
346
|
|
|
277
|
-
<a name="schema-json-shorthand"></a>
|
|
278
347
|
### `jsonShorthand`
|
|
348
|
+
<a id="schema-json-shorthand"></a>
|
|
279
349
|
|
|
280
350
|
+ Default: `true`
|
|
281
351
|
|
|
282
|
-
Internally, and by default, Fastify will automatically infer the root properties
|
|
352
|
+
Internally, and by default, Fastify will automatically infer the root properties
|
|
353
|
+
of JSON Schemas if it does not find valid root properties according to the JSON
|
|
354
|
+
Schema spec. If you wish to implement your own schema validation compiler, for
|
|
355
|
+
example: to parse schemas as JTD instead of JSON Schema, then you can explicitly
|
|
356
|
+
set this option to `false` to make sure the schemas you receive are unmodified
|
|
357
|
+
and are not being treated internally as JSON Schema.
|
|
283
358
|
|
|
284
359
|
```js
|
|
285
360
|
const AjvJTD = require('ajv/dist/jtd'/* only valid for AJV v7+ */)
|
|
@@ -303,14 +378,21 @@ fastify.post('/', {
|
|
|
303
378
|
})
|
|
304
379
|
```
|
|
305
380
|
|
|
306
|
-
**Note: Fastify does not currently throw on invalid schemas, so if you turn this
|
|
381
|
+
**Note: Fastify does not currently throw on invalid schemas, so if you turn this
|
|
382
|
+
off in an existing project, you need to be careful that none of your existing
|
|
383
|
+
schemas become invalid as a result, since they will be treated as a catch-all.**
|
|
307
384
|
|
|
308
|
-
<a name="factory-case-sensitive"></a>
|
|
309
385
|
### `caseSensitive`
|
|
386
|
+
<a id="factory-case-sensitive"></a>
|
|
310
387
|
|
|
311
|
-
By default, value equal to `true`, routes are registered as case sensitive. That
|
|
388
|
+
By default, value equal to `true`, routes are registered as case sensitive. That
|
|
389
|
+
is, `/foo` is not equivalent to `/Foo`. When set to `false`, routes are
|
|
390
|
+
registered in a fashion such that `/foo` is equivalent to `/Foo` which is
|
|
391
|
+
equivalent to `/FOO`.
|
|
312
392
|
|
|
313
|
-
By setting `caseSensitive` to `false`, all paths will be matched as lowercase,
|
|
393
|
+
By setting `caseSensitive` to `false`, all paths will be matched as lowercase,
|
|
394
|
+
but the route parameters or wildcards will maintain their original letter
|
|
395
|
+
casing.
|
|
314
396
|
|
|
315
397
|
```js
|
|
316
398
|
fastify.get('/user/:username', (request, reply) => {
|
|
@@ -322,30 +404,37 @@ fastify.get('/user/:username', (request, reply) => {
|
|
|
322
404
|
Please note that setting this option to `false` goes against
|
|
323
405
|
[RFC3986](https://tools.ietf.org/html/rfc3986#section-6.2.2.1).
|
|
324
406
|
|
|
325
|
-
Also note, this setting will not affect query strings. If you want to change the
|
|
407
|
+
Also note, this setting will not affect query strings. If you want to change the
|
|
408
|
+
way query strings are handled take a look at
|
|
409
|
+
[`querystringParser`](#querystringparser).
|
|
326
410
|
|
|
327
|
-
<a name="factory-request-id-header"></a>
|
|
328
411
|
### `requestIdHeader`
|
|
412
|
+
<a id="factory-request-id-header"></a>
|
|
329
413
|
|
|
330
|
-
The header name used to know the request-id. See [the
|
|
414
|
+
The header name used to know the request-id. See [the
|
|
415
|
+
request-id](./Logging.md#logging-request-id) section.
|
|
331
416
|
|
|
332
417
|
+ Default: `'request-id'`
|
|
333
418
|
|
|
334
|
-
<a name="factory-request-id-log-label"></a>
|
|
335
419
|
### `requestIdLogLabel`
|
|
420
|
+
<a id="factory-request-id-log-label"></a>
|
|
336
421
|
|
|
337
422
|
Defines the label used for the request identifier when logging the request.
|
|
338
423
|
|
|
339
424
|
+ Default: `'reqId'`
|
|
340
425
|
|
|
341
|
-
<a name="factory-gen-request-id"></a>
|
|
342
426
|
### `genReqId`
|
|
427
|
+
<a id="factory-gen-request-id"></a>
|
|
343
428
|
|
|
344
|
-
Function for generating the request-id. It will receive the incoming request as
|
|
429
|
+
Function for generating the request-id. It will receive the incoming request as
|
|
430
|
+
a parameter.
|
|
345
431
|
|
|
346
|
-
+ Default: `value of 'request-id' header if provided or monotonically increasing
|
|
432
|
+
+ Default: `value of 'request-id' header if provided or monotonically increasing
|
|
433
|
+
integers`
|
|
347
434
|
|
|
348
|
-
Especially in distributed systems, you may want to override the default ID
|
|
435
|
+
Especially in distributed systems, you may want to override the default ID
|
|
436
|
+
generation behavior as shown below. For generating `UUID`s you may want to check
|
|
437
|
+
out [hyperid](https://github.com/mcollina/hyperid)
|
|
349
438
|
|
|
350
439
|
```js
|
|
351
440
|
let i = 0
|
|
@@ -354,20 +443,26 @@ const fastify = require('fastify')({
|
|
|
354
443
|
})
|
|
355
444
|
```
|
|
356
445
|
|
|
357
|
-
**Note: genReqId will _not_ be called if the header set in
|
|
446
|
+
**Note: genReqId will _not_ be called if the header set in
|
|
447
|
+
<code>[requestIdHeader](#requestidheader)</code> is available (defaults to
|
|
448
|
+
'request-id').**
|
|
358
449
|
|
|
359
|
-
<a name="factory-trust-proxy"></a>
|
|
360
450
|
### `trustProxy`
|
|
451
|
+
<a id="factory-trust-proxy"></a>
|
|
361
452
|
|
|
362
|
-
By enabling the `trustProxy` option, Fastify will know that it is sitting behind
|
|
453
|
+
By enabling the `trustProxy` option, Fastify will know that it is sitting behind
|
|
454
|
+
a proxy and that the `X-Forwarded-*` header fields may be trusted, which
|
|
455
|
+
otherwise may be easily spoofed.
|
|
363
456
|
|
|
364
457
|
```js
|
|
365
458
|
const fastify = Fastify({ trustProxy: true })
|
|
366
459
|
```
|
|
367
460
|
|
|
368
461
|
+ Default: `false`
|
|
369
|
-
+ `true/false`: Trust all proxies (`true`) or do not trust any proxies
|
|
370
|
-
|
|
462
|
+
+ `true/false`: Trust all proxies (`true`) or do not trust any proxies
|
|
463
|
+
(`false`).
|
|
464
|
+
+ `string`: Trust only given IP/CIDR (e.g. `'127.0.0.1'`). May be a list of
|
|
465
|
+
comma separated values (e.g. `'127.0.0.1,192.168.1.1/24'`).
|
|
371
466
|
+ `Array<string>`: Trust only given IP/CIDR list (e.g. `['127.0.0.1']`).
|
|
372
467
|
+ `number`: Trust the nth hop from the front-facing proxy server as the client.
|
|
373
468
|
+ `Function`: Custom trust function that takes `address` as first arg
|
|
@@ -377,9 +472,11 @@ const fastify = Fastify({ trustProxy: true })
|
|
|
377
472
|
}
|
|
378
473
|
```
|
|
379
474
|
|
|
380
|
-
For more examples, refer to the
|
|
475
|
+
For more examples, refer to the
|
|
476
|
+
[`proxy-addr`](https://www.npmjs.com/package/proxy-addr) package.
|
|
381
477
|
|
|
382
|
-
You may access the `ip`, `ips`, `hostname` and `protocol` values on the
|
|
478
|
+
You may access the `ip`, `ips`, `hostname` and `protocol` values on the
|
|
479
|
+
[`request`](./Request.md) object.
|
|
383
480
|
|
|
384
481
|
```js
|
|
385
482
|
fastify.get('/', (request, reply) => {
|
|
@@ -390,22 +487,27 @@ fastify.get('/', (request, reply) => {
|
|
|
390
487
|
})
|
|
391
488
|
```
|
|
392
489
|
|
|
393
|
-
**Note: if a request contains multiple <code>x-forwarded-host</code> or
|
|
490
|
+
**Note: if a request contains multiple <code>x-forwarded-host</code> or
|
|
491
|
+
<code>x-forwarded-proto</code> headers, it is only the last one that is used to
|
|
492
|
+
derive <code>request.hostname</code> and <code>request.protocol</code>**
|
|
394
493
|
|
|
395
|
-
<a name="plugin-timeout"></a>
|
|
396
494
|
### `pluginTimeout`
|
|
495
|
+
<a id="plugin-timeout"></a>
|
|
397
496
|
|
|
398
|
-
The maximum amount of time in *milliseconds* in which a plugin can load.
|
|
399
|
-
|
|
400
|
-
|
|
497
|
+
The maximum amount of time in *milliseconds* in which a plugin can load. If not,
|
|
498
|
+
[`ready`](#ready) will complete with an `Error` with code
|
|
499
|
+
`'ERR_AVVIO_PLUGIN_TIMEOUT'`.
|
|
401
500
|
|
|
402
501
|
+ Default: `10000`
|
|
403
502
|
|
|
404
|
-
<a name="factory-querystring-parser"></a>
|
|
405
503
|
### `querystringParser`
|
|
504
|
+
<a id="factory-querystring-parser"></a>
|
|
505
|
+
|
|
506
|
+
The default query string parser that Fastify uses is the Node.js's core
|
|
507
|
+
`querystring` module.
|
|
406
508
|
|
|
407
|
-
|
|
408
|
-
|
|
509
|
+
You can change this default setting by passing the option `querystringParser`
|
|
510
|
+
and use a custom one, such as [`qs`](https://www.npmjs.com/package/qs).
|
|
409
511
|
|
|
410
512
|
```js
|
|
411
513
|
const qs = require('qs')
|
|
@@ -414,7 +516,8 @@ const fastify = require('fastify')({
|
|
|
414
516
|
})
|
|
415
517
|
```
|
|
416
518
|
|
|
417
|
-
You can also use Fastify's default parser but change some handling behaviour,
|
|
519
|
+
You can also use Fastify's default parser but change some handling behaviour,
|
|
520
|
+
like the example below for case insensitive keys and values:
|
|
418
521
|
|
|
419
522
|
```js
|
|
420
523
|
const querystring = require('querystring')
|
|
@@ -423,19 +526,27 @@ const fastify = require('fastify')({
|
|
|
423
526
|
})
|
|
424
527
|
```
|
|
425
528
|
|
|
426
|
-
Note, if you only want the keys (and not the values) to be case insensitive we
|
|
529
|
+
Note, if you only want the keys (and not the values) to be case insensitive we
|
|
530
|
+
recommend using a custom parser to convert only the keys to lowercase.
|
|
427
531
|
|
|
428
|
-
<a name="exposeHeadRoutes"></a>
|
|
429
532
|
### `exposeHeadRoutes`
|
|
533
|
+
<a id="exposeHeadRoutes"></a>
|
|
430
534
|
|
|
431
|
-
Automatically creates a sibling `HEAD` route for each `GET` route defined. If
|
|
535
|
+
Automatically creates a sibling `HEAD` route for each `GET` route defined. If
|
|
536
|
+
you want a custom `HEAD` handler without disabling this option, make sure to
|
|
537
|
+
define it before the `GET` route.
|
|
432
538
|
|
|
433
539
|
+ Default: `false`
|
|
434
540
|
|
|
435
|
-
<a name="constraints"></a>
|
|
436
541
|
### `constraints`
|
|
542
|
+
<a id="constraints"></a>
|
|
437
543
|
|
|
438
|
-
Fastify's built in route constraints are provided by `find-my-way`, which allow
|
|
544
|
+
Fastify's built in route constraints are provided by `find-my-way`, which allow
|
|
545
|
+
constraining routes by `version` or `host`. You are able to add new constraint
|
|
546
|
+
strategies, or override the built in strategies by providing a `constraints`
|
|
547
|
+
object with strategies for `find-my-way`. You can find more information on
|
|
548
|
+
constraint strategies in the
|
|
549
|
+
[find-my-way](https://github.com/delvedor/find-my-way) documentation.
|
|
439
550
|
|
|
440
551
|
```js
|
|
441
552
|
const customVersionStrategy = {
|
|
@@ -460,16 +571,16 @@ const fastify = require('fastify')({
|
|
|
460
571
|
})
|
|
461
572
|
```
|
|
462
573
|
|
|
463
|
-
<a name="factory-return-503-on-closing"></a>
|
|
464
574
|
### `return503OnClosing`
|
|
575
|
+
<a id="factory-return-503-on-closing"></a>
|
|
465
576
|
|
|
466
|
-
Returns 503 after calling `close` server method.
|
|
467
|
-
|
|
577
|
+
Returns 503 after calling `close` server method. If `false`, the server routes
|
|
578
|
+
the incoming request as usual.
|
|
468
579
|
|
|
469
580
|
+ Default: `true`
|
|
470
581
|
|
|
471
|
-
<a name="factory-ajv"></a>
|
|
472
582
|
### `ajv`
|
|
583
|
+
<a id="factory-ajv"></a>
|
|
473
584
|
|
|
474
585
|
Configure the Ajv v6 instance used by Fastify without providing a custom one.
|
|
475
586
|
|
|
@@ -504,10 +615,12 @@ const fastify = require('fastify')({
|
|
|
504
615
|
})
|
|
505
616
|
```
|
|
506
617
|
|
|
507
|
-
<a name="serializer-opts"></a>
|
|
508
618
|
### `serializerOpts`
|
|
619
|
+
<a id="serializer-opts"></a>
|
|
509
620
|
|
|
510
|
-
Customize the options of the default
|
|
621
|
+
Customize the options of the default
|
|
622
|
+
[`fast-json-stringify`](https://github.com/fastify/fast-json-stringify#options)
|
|
623
|
+
instance that serialize the response's payload:
|
|
511
624
|
|
|
512
625
|
```js
|
|
513
626
|
const fastify = require('fastify')({
|
|
@@ -517,24 +630,27 @@ const fastify = require('fastify')({
|
|
|
517
630
|
})
|
|
518
631
|
```
|
|
519
632
|
|
|
520
|
-
<a name="http2-session-timeout"></a>
|
|
521
633
|
### `http2SessionTimeout`
|
|
634
|
+
<a id="http2-session-timeout"></a>
|
|
522
635
|
|
|
523
636
|
Set a default
|
|
524
|
-
[timeout](https://nodejs.org/api/http2.html#http2_http2session_settimeout_msecs_callback)
|
|
637
|
+
[timeout](https://nodejs.org/api/http2.html#http2_http2session_settimeout_msecs_callback)
|
|
638
|
+
to every incoming HTTP/2 session. The session will be closed on the timeout.
|
|
639
|
+
Default: `5000` ms.
|
|
525
640
|
|
|
526
|
-
Note that this is needed to offer the graceful "close" experience when using
|
|
527
|
-
The low default has been chosen to mitigate denial of service attacks.
|
|
528
|
-
When the server is behind a load balancer or can scale automatically this value
|
|
529
|
-
increased to fit the use case. Node core defaults this to `0`. `
|
|
641
|
+
Note that this is needed to offer the graceful "close" experience when using
|
|
642
|
+
HTTP/2. The low default has been chosen to mitigate denial of service attacks.
|
|
643
|
+
When the server is behind a load balancer or can scale automatically this value
|
|
644
|
+
can be increased to fit the use case. Node core defaults this to `0`. `
|
|
530
645
|
|
|
531
|
-
<a name="framework-errors"></a>
|
|
532
646
|
### `frameworkErrors`
|
|
647
|
+
<a id="framework-errors"></a>
|
|
533
648
|
|
|
534
649
|
+ Default: `null`
|
|
535
650
|
|
|
536
|
-
Fastify provides default error handlers for the most common use cases.
|
|
537
|
-
|
|
651
|
+
Fastify provides default error handlers for the most common use cases. It is
|
|
652
|
+
possible to override one or more of those handlers with custom code using this
|
|
653
|
+
option.
|
|
538
654
|
|
|
539
655
|
*Note: Only `FST_ERR_BAD_URL` is implemented at the moment.*
|
|
540
656
|
|
|
@@ -551,10 +667,13 @@ const fastify = require('fastify')({
|
|
|
551
667
|
})
|
|
552
668
|
```
|
|
553
669
|
|
|
554
|
-
<a name="client-error-handler"></a>
|
|
555
670
|
### `clientErrorHandler`
|
|
671
|
+
<a id="client-error-handler"></a>
|
|
556
672
|
|
|
557
|
-
Set a
|
|
673
|
+
Set a
|
|
674
|
+
[clientErrorHandler](https://nodejs.org/api/http.html#http_event_clienterror)
|
|
675
|
+
that listens to `error` events emitted by client connections and responds with a
|
|
676
|
+
`400`.
|
|
558
677
|
|
|
559
678
|
It is possible to override the default `clientErrorHandler` using this option.
|
|
560
679
|
|
|
@@ -578,7 +697,10 @@ function defaultClientErrorHandler (err, socket) {
|
|
|
578
697
|
}
|
|
579
698
|
```
|
|
580
699
|
|
|
581
|
-
*Note: `clientErrorHandler` operates with raw socket. The handler is expected to
|
|
700
|
+
*Note: `clientErrorHandler` operates with raw socket. The handler is expected to
|
|
701
|
+
return a properly formed HTTP response that includes a status line, HTTP headers
|
|
702
|
+
and a message body. Before attempting to write the socket, the handler should
|
|
703
|
+
check if the socket is still writable as it may have already been destroyed.*
|
|
582
704
|
|
|
583
705
|
```js
|
|
584
706
|
const fastify = require('fastify')({
|
|
@@ -599,10 +721,11 @@ const fastify = require('fastify')({
|
|
|
599
721
|
})
|
|
600
722
|
```
|
|
601
723
|
|
|
602
|
-
<a name="rewrite-url"></a>
|
|
603
724
|
### `rewriteUrl`
|
|
725
|
+
<a id="rewrite-url"></a>
|
|
604
726
|
|
|
605
|
-
Set a sync callback function that must return a string that allows rewriting
|
|
727
|
+
Set a sync callback function that must return a string that allows rewriting
|
|
728
|
+
URLs.
|
|
606
729
|
|
|
607
730
|
> Rewriting a URL will modify the `url` property of the `req` object
|
|
608
731
|
|
|
@@ -612,21 +735,26 @@ function rewriteUrl (req) { // req is the Node.js HTTP request
|
|
|
612
735
|
}
|
|
613
736
|
```
|
|
614
737
|
|
|
615
|
-
Note that `rewriteUrl` is called _before_ routing, it is not encapsulated and it
|
|
738
|
+
Note that `rewriteUrl` is called _before_ routing, it is not encapsulated and it
|
|
739
|
+
is an instance-wide configuration.
|
|
616
740
|
|
|
617
741
|
## Instance
|
|
618
742
|
|
|
619
743
|
### Server Methods
|
|
620
744
|
|
|
621
|
-
<a name="server"></a>
|
|
622
745
|
#### server
|
|
623
|
-
|
|
746
|
+
<a id="server"></a>
|
|
747
|
+
|
|
748
|
+
`fastify.server`: The Node core
|
|
749
|
+
[server](https://nodejs.org/api/http.html#http_class_http_server) object as
|
|
750
|
+
returned by the [**`Fastify factory function`**](#factory).
|
|
624
751
|
|
|
625
|
-
<a name="after"></a>
|
|
626
752
|
#### after
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
753
|
+
<a id="after"></a>
|
|
754
|
+
|
|
755
|
+
Invoked when the current plugin and all the plugins that have been registered
|
|
756
|
+
within it have finished loading. It is always executed before the method
|
|
757
|
+
`fastify.ready`.
|
|
630
758
|
|
|
631
759
|
```js
|
|
632
760
|
fastify
|
|
@@ -665,10 +793,11 @@ await fastify.ready()
|
|
|
665
793
|
console.log('Everything has been loaded')
|
|
666
794
|
```
|
|
667
795
|
|
|
668
|
-
<a name="ready"></a>
|
|
669
796
|
#### ready
|
|
670
|
-
|
|
671
|
-
|
|
797
|
+
<a id="ready"></a>
|
|
798
|
+
|
|
799
|
+
Function called when all the plugins have been loaded. It takes an error
|
|
800
|
+
parameter if something went wrong.
|
|
672
801
|
```js
|
|
673
802
|
fastify.ready(err => {
|
|
674
803
|
if (err) throw err
|
|
@@ -684,9 +813,19 @@ fastify.ready().then(() => {
|
|
|
684
813
|
})
|
|
685
814
|
```
|
|
686
815
|
|
|
687
|
-
<a name="listen"></a>
|
|
688
816
|
#### listen
|
|
689
|
-
|
|
817
|
+
<a id="listen"></a>
|
|
818
|
+
|
|
819
|
+
Starts the server on the given port after all the plugins are loaded, internally
|
|
820
|
+
waits for the `.ready()` event. The callback is the same as the Node core. By
|
|
821
|
+
default, the server will listen on the address resolved by `localhost` when no
|
|
822
|
+
specific address is provided (`127.0.0.1` or `::1` depending on the operating
|
|
823
|
+
system). If listening on any available interface is desired, then specifying
|
|
824
|
+
`0.0.0.0` for the address will listen on all IPv4 addresses. Using `::` for the
|
|
825
|
+
address will listen on all IPv6 addresses and, depending on OS, may also listen
|
|
826
|
+
on all IPv4 addresses. Be careful when deciding to listen on all interfaces; it
|
|
827
|
+
comes with inherent [security
|
|
828
|
+
risks](https://web.archive.org/web/20170831174611/https://snyk.io/blog/mongodb-hack-and-secure-defaults/).
|
|
690
829
|
|
|
691
830
|
```js
|
|
692
831
|
fastify.listen(3000, (err, address) => {
|
|
@@ -719,7 +858,9 @@ fastify.listen(3000, '127.0.0.1', 511, (err, address) => {
|
|
|
719
858
|
})
|
|
720
859
|
```
|
|
721
860
|
|
|
722
|
-
Specifying options is also supported; the object is same as
|
|
861
|
+
Specifying options is also supported; the object is same as
|
|
862
|
+
[options](https://nodejs.org/api/net.html#net_server_listen_options_callback) in
|
|
863
|
+
the Node.js server listen:
|
|
723
864
|
|
|
724
865
|
```js
|
|
725
866
|
fastify.listen({ port: 3000, host: '127.0.0.1', backlog: 511 }, (err) => {
|
|
@@ -763,7 +904,9 @@ fastify.listen({ port: 3000, host: '127.0.0.1', backlog: 511 })
|
|
|
763
904
|
})
|
|
764
905
|
```
|
|
765
906
|
|
|
766
|
-
When deploying to a Docker, and potentially other, containers, it is advisable
|
|
907
|
+
When deploying to a Docker, and potentially other, containers, it is advisable
|
|
908
|
+
to listen on `0.0.0.0` because they do not default to exposing mapped ports to
|
|
909
|
+
`localhost`:
|
|
767
910
|
|
|
768
911
|
```js
|
|
769
912
|
fastify.listen(3000, '0.0.0.0', (err, address) => {
|
|
@@ -774,7 +917,8 @@ fastify.listen(3000, '0.0.0.0', (err, address) => {
|
|
|
774
917
|
})
|
|
775
918
|
```
|
|
776
919
|
|
|
777
|
-
If the `port` is omitted (or is set to zero), a random available port is
|
|
920
|
+
If the `port` is omitted (or is set to zero), a random available port is
|
|
921
|
+
automatically chosen (later available via `fastify.server.address().port`).
|
|
778
922
|
|
|
779
923
|
The default options of listen are:
|
|
780
924
|
|
|
@@ -789,16 +933,18 @@ fastify.listen({
|
|
|
789
933
|
}, (err) => {})
|
|
790
934
|
```
|
|
791
935
|
|
|
792
|
-
<a name="getDefaultRoute"></a>
|
|
793
936
|
#### getDefaultRoute
|
|
937
|
+
<a id="getDefaultRoute"></a>
|
|
938
|
+
|
|
794
939
|
Method to get the `defaultRoute` for the server:
|
|
795
940
|
|
|
796
941
|
```js
|
|
797
942
|
const defaultRoute = fastify.getDefaultRoute()
|
|
798
943
|
```
|
|
799
944
|
|
|
800
|
-
<a name="setDefaultRoute"></a>
|
|
801
945
|
#### setDefaultRoute
|
|
946
|
+
<a id="setDefaultRoute"></a>
|
|
947
|
+
|
|
802
948
|
Method to set the `defaultRoute` for the server:
|
|
803
949
|
|
|
804
950
|
```js
|
|
@@ -809,23 +955,31 @@ const defaultRoute = function (req, res) {
|
|
|
809
955
|
fastify.setDefaultRoute(defaultRoute)
|
|
810
956
|
```
|
|
811
957
|
|
|
812
|
-
<a name="routing"></a>
|
|
813
958
|
#### routing
|
|
814
|
-
|
|
959
|
+
<a id="routing"></a>
|
|
960
|
+
|
|
961
|
+
Method to access the `lookup` method of the internal router and match the
|
|
962
|
+
request to the appropriate handler:
|
|
815
963
|
|
|
816
964
|
```js
|
|
817
965
|
fastify.routing(req, res)
|
|
818
966
|
```
|
|
819
967
|
|
|
820
|
-
<a name="route"></a>
|
|
821
968
|
#### route
|
|
822
|
-
|
|
969
|
+
<a id="route"></a>
|
|
970
|
+
|
|
971
|
+
Method to add routes to the server, it also has shorthand functions, check
|
|
972
|
+
[here](./Routes.md).
|
|
823
973
|
|
|
824
|
-
<a name="close"></a>
|
|
825
974
|
#### close
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
975
|
+
<a id="close"></a>
|
|
976
|
+
|
|
977
|
+
`fastify.close(callback)`: call this function to close the server instance and
|
|
978
|
+
run the [`'onClose'`](./Hooks.md#on-close) hook.
|
|
979
|
+
|
|
980
|
+
Calling `close` will also cause the server to respond to every new incoming
|
|
981
|
+
request with a `503` error and destroy that request. See [`return503OnClosing`
|
|
982
|
+
flags](#factory-return-503-on-closing) for changing this behavior.
|
|
829
983
|
|
|
830
984
|
If it is called without any arguments, it will return a Promise:
|
|
831
985
|
|
|
@@ -837,21 +991,27 @@ fastify.close().then(() => {
|
|
|
837
991
|
})
|
|
838
992
|
```
|
|
839
993
|
|
|
840
|
-
<a name="decorate"></a>
|
|
841
994
|
#### decorate*
|
|
842
|
-
|
|
995
|
+
<a id="decorate"></a>
|
|
996
|
+
|
|
997
|
+
Function useful if you need to decorate the fastify instance, Reply or Request,
|
|
998
|
+
check [here](./Decorators.md).
|
|
843
999
|
|
|
844
|
-
<a name="register"></a>
|
|
845
1000
|
#### register
|
|
846
|
-
|
|
847
|
-
|
|
1001
|
+
<a id="register"></a>
|
|
1002
|
+
|
|
1003
|
+
Fastify allows the user to extend its functionality with plugins. A plugin can
|
|
1004
|
+
be a set of routes, a server decorator, or whatever, check [here](./Plugins.md).
|
|
848
1005
|
|
|
849
|
-
<a name="addHook"></a>
|
|
850
1006
|
#### addHook
|
|
851
|
-
|
|
1007
|
+
<a id="addHook"></a>
|
|
1008
|
+
|
|
1009
|
+
Function to add a specific hook in the lifecycle of Fastify, check
|
|
1010
|
+
[here](./Hooks.md).
|
|
852
1011
|
|
|
853
|
-
<a name="prefix"></a>
|
|
854
1012
|
#### prefix
|
|
1013
|
+
<a id="prefix"></a>
|
|
1014
|
+
|
|
855
1015
|
The full path that will be prefixed to a route.
|
|
856
1016
|
|
|
857
1017
|
Example:
|
|
@@ -878,47 +1038,75 @@ fastify.register(function (instance, opts, done) {
|
|
|
878
1038
|
}, { prefix: '/v1' })
|
|
879
1039
|
```
|
|
880
1040
|
|
|
881
|
-
<a name="pluginName"></a>
|
|
882
1041
|
#### pluginName
|
|
1042
|
+
<a id="pluginName"></a>
|
|
1043
|
+
|
|
883
1044
|
Name of the current plugin. There are three ways to define a name (in order).
|
|
884
1045
|
|
|
885
|
-
1. If you use [fastify-plugin](https://github.com/fastify/fastify-plugin) the
|
|
1046
|
+
1. If you use [fastify-plugin](https://github.com/fastify/fastify-plugin) the
|
|
1047
|
+
metadata `name` is used.
|
|
886
1048
|
2. If you `module.exports` a plugin the filename is used.
|
|
887
|
-
3. If you use a regular [function
|
|
1049
|
+
3. If you use a regular [function
|
|
1050
|
+
declaration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Defining_functions)
|
|
1051
|
+
the function name is used.
|
|
888
1052
|
|
|
889
|
-
*Fallback*: The first two lines of your plugin will represent the plugin name.
|
|
1053
|
+
*Fallback*: The first two lines of your plugin will represent the plugin name.
|
|
1054
|
+
Newlines are replaced by ` -- `. This will help to identify the root cause when
|
|
1055
|
+
you deal with many plugins.
|
|
890
1056
|
|
|
891
|
-
Important: If you have to deal with nested plugins, the name differs with the
|
|
1057
|
+
Important: If you have to deal with nested plugins, the name differs with the
|
|
1058
|
+
usage of the [fastify-plugin](https://github.com/fastify/fastify-plugin) because
|
|
1059
|
+
no new scope is created and therefore we have no place to attach contextual
|
|
1060
|
+
data. In that case, the plugin name will represent the boot order of all
|
|
1061
|
+
involved plugins in the format of `plugin-A -> plugin-B`.
|
|
892
1062
|
|
|
893
|
-
<a name="log"></a>
|
|
894
1063
|
#### log
|
|
895
|
-
|
|
1064
|
+
<a id="log"></a>
|
|
1065
|
+
|
|
1066
|
+
The logger instance, check [here](./Logging.md).
|
|
896
1067
|
|
|
897
|
-
<a name="version"></a>
|
|
898
1068
|
#### version
|
|
899
|
-
|
|
1069
|
+
<a id="version"></a>
|
|
1070
|
+
|
|
1071
|
+
Fastify version of the instance. Used for plugin support. See
|
|
1072
|
+
[Plugins](./Plugins.md#handle-the-scope) for information on how the version is
|
|
1073
|
+
used by plugins.
|
|
900
1074
|
|
|
901
|
-
<a name="inject"></a>
|
|
902
1075
|
#### inject
|
|
903
|
-
|
|
1076
|
+
<a id="inject"></a>
|
|
1077
|
+
|
|
1078
|
+
Fake HTTP injection (for testing purposes) [here](../Guides/Testing.md#benefits-of-using-fastifyinject).
|
|
904
1079
|
|
|
905
|
-
<a name="add-schema"></a>
|
|
906
1080
|
#### addSchema
|
|
907
|
-
|
|
908
|
-
|
|
1081
|
+
<a id="add-schema"></a>
|
|
1082
|
+
|
|
1083
|
+
`fastify.addSchema(schemaObj)`, adds a JSON schema to the Fastify instance. This
|
|
1084
|
+
allows you to reuse it everywhere in your application just by using the standard
|
|
1085
|
+
`$ref` keyword.
|
|
1086
|
+
|
|
1087
|
+
To learn more, read the [Validation and
|
|
1088
|
+
Serialization](./Validation-and-Serialization.md) documentation.
|
|
909
1089
|
|
|
910
|
-
<a name="get-schemas"></a>
|
|
911
1090
|
#### getSchemas
|
|
912
|
-
|
|
1091
|
+
<a id="get-schemas"></a>
|
|
1092
|
+
|
|
1093
|
+
`fastify.getSchemas()`, returns a hash of all schemas added via `.addSchema`.
|
|
1094
|
+
The keys of the hash are the `$id`s of the JSON Schema provided.
|
|
913
1095
|
|
|
914
|
-
<a name="get-schema"></a>
|
|
915
1096
|
#### getSchema
|
|
916
|
-
|
|
1097
|
+
<a id="get-schema"></a>
|
|
1098
|
+
|
|
1099
|
+
`fastify.getSchema(id)`, return the JSON schema added with `.addSchema` and the
|
|
1100
|
+
matching `id`. It returns `undefined` if it is not found.
|
|
917
1101
|
|
|
918
|
-
<a name="set-reply-serializer"></a>
|
|
919
1102
|
#### setReplySerializer
|
|
920
|
-
|
|
921
|
-
|
|
1103
|
+
<a id="set-reply-serializer"></a>
|
|
1104
|
+
|
|
1105
|
+
Set the reply serializer for all the routes. This will be used as default if a
|
|
1106
|
+
[Reply.serializer(func)](./Reply.md#serializerfunc) has not been set. The
|
|
1107
|
+
handler is fully encapsulated, so different plugins can set different error
|
|
1108
|
+
handlers. Note: the function parameter is called only for status `2xx`. Check
|
|
1109
|
+
out the [`setErrorHandler`](#seterrorhandler) for errors.
|
|
922
1110
|
|
|
923
1111
|
```js
|
|
924
1112
|
fastify.setReplySerializer(function (payload, statusCode){
|
|
@@ -927,45 +1115,64 @@ fastify.setReplySerializer(function (payload, statusCode){
|
|
|
927
1115
|
})
|
|
928
1116
|
```
|
|
929
1117
|
|
|
930
|
-
<a name="set-validator-compiler"></a>
|
|
931
1118
|
#### setValidatorCompiler
|
|
932
|
-
|
|
1119
|
+
<a id="set-validator-compiler"></a>
|
|
1120
|
+
|
|
1121
|
+
Set the schema validator compiler for all routes. See
|
|
1122
|
+
[#schema-validator](./Validation-and-Serialization.md#schema-validator).
|
|
933
1123
|
|
|
934
|
-
<a name="set-schema-error-formatter"></a>
|
|
935
1124
|
#### setSchemaErrorFormatter
|
|
936
|
-
|
|
1125
|
+
<a id="set-schema-error-formatter"></a>
|
|
1126
|
+
|
|
1127
|
+
Set the schema error formatter for all routes. See
|
|
1128
|
+
[#error-handling](./Validation-and-Serialization.md#schemaerrorformatter).
|
|
937
1129
|
|
|
938
|
-
<a name="set-serializer-resolver"></a>
|
|
939
1130
|
#### setSerializerCompiler
|
|
940
|
-
|
|
1131
|
+
<a id="set-serializer-resolver"></a>
|
|
1132
|
+
|
|
1133
|
+
Set the schema serializer compiler for all routes. See
|
|
1134
|
+
[#schema-serializer](./Validation-and-Serialization.md#schema-serializer).
|
|
941
1135
|
**Note:** [`setReplySerializer`](#set-reply-serializer) has priority if set!
|
|
942
1136
|
|
|
943
|
-
<a name="validator-compiler"></a>
|
|
944
1137
|
#### validatorCompiler
|
|
945
|
-
|
|
946
|
-
|
|
1138
|
+
<a id="validator-compiler"></a>
|
|
1139
|
+
|
|
1140
|
+
This property can be used to get the schema validator. If not set, it will be
|
|
1141
|
+
`null` until the server starts, then it will be a function with the signature
|
|
1142
|
+
`function ({ schema, method, url, httpPart })` that returns the input `schema`
|
|
1143
|
+
compiled to a function for validating data. The input `schema` can access all
|
|
1144
|
+
the shared schemas added with [`.addSchema`](#add-schema) function.
|
|
947
1145
|
|
|
948
|
-
<a name="serializer-compiler"></a>
|
|
949
1146
|
#### serializerCompiler
|
|
950
|
-
|
|
951
|
-
|
|
1147
|
+
<a id="serializer-compiler"></a>
|
|
1148
|
+
|
|
1149
|
+
This property can be used to get the schema serializer. If not set, it will be
|
|
1150
|
+
`null` until the server starts, then it will be a function with the signature
|
|
1151
|
+
`function ({ schema, method, url, httpPart })` that returns the input `schema`
|
|
1152
|
+
compiled to a function for validating data. The input `schema` can access all
|
|
1153
|
+
the shared schemas added with [`.addSchema`](#add-schema) function.
|
|
952
1154
|
|
|
953
|
-
<a name="schema-error-formatter"></a>
|
|
954
1155
|
#### schemaErrorFormatter
|
|
955
|
-
|
|
1156
|
+
<a id="schema-error-formatter"></a>
|
|
1157
|
+
|
|
1158
|
+
This property can be used to set a function to format errors that happen while
|
|
1159
|
+
the `validationCompiler` fails to validate the schema. See
|
|
1160
|
+
[#error-handling](./Validation-and-Serialization.md#schemaerrorformatter).
|
|
956
1161
|
|
|
957
|
-
<a name="schema-controller"></a>
|
|
958
1162
|
#### schemaController
|
|
959
|
-
|
|
1163
|
+
<a id="schema-controller"></a>
|
|
1164
|
+
|
|
1165
|
+
This property can be used to fully manage:
|
|
960
1166
|
- `bucket`: where the schemas of your application will be stored
|
|
961
1167
|
- `compilersFactory`: what module must compile the JSON schemas
|
|
962
1168
|
|
|
963
|
-
It can be useful when your schemas are stored in another data structure that is
|
|
964
|
-
|
|
1169
|
+
It can be useful when your schemas are stored in another data structure that is
|
|
1170
|
+
unknown to Fastify. See [issue
|
|
1171
|
+
#2446](https://github.com/fastify/fastify/issues/2446) for an example of what
|
|
965
1172
|
this property helps to resolve.
|
|
966
1173
|
|
|
967
|
-
Another use case is to tweak all the schemas processing.
|
|
968
|
-
|
|
1174
|
+
Another use case is to tweak all the schemas processing. Doing so it is possible
|
|
1175
|
+
to use Ajv v8, instead of the default v6! We will see an example of this later.
|
|
969
1176
|
|
|
970
1177
|
```js
|
|
971
1178
|
const fastify = Fastify({
|
|
@@ -1009,11 +1216,11 @@ const fastify = Fastify({
|
|
|
1009
1216
|
* encapsulation context.
|
|
1010
1217
|
* It may receive as input the schemas of the parent context if some schemas have been added.
|
|
1011
1218
|
* @param {object} externalSchemas these schemas will be returned by the `bucket.getSchemas()`. Needed to resolve the external references $ref.
|
|
1012
|
-
* @param {object} ajvServerOption the server `ajv` options to build your compilers accordingly
|
|
1219
|
+
* @param {object} ajvServerOption the server `ajv` options to build your compilers accordingly
|
|
1013
1220
|
*/
|
|
1014
1221
|
buildValidator: function factory (externalSchemas, ajvServerOption) {
|
|
1015
1222
|
// This factory function must return a schema validator compiler.
|
|
1016
|
-
// See [#schema-validator](Validation-and-Serialization.md#schema-validator) for details.
|
|
1223
|
+
// See [#schema-validator](./Validation-and-Serialization.md#schema-validator) for details.
|
|
1017
1224
|
const yourAjvInstance = new Ajv(ajvServerOption.customOptions)
|
|
1018
1225
|
return function validatorCompiler ({ schema, method, url, httpPart }) {
|
|
1019
1226
|
return yourAjvInstance.compile(schema)
|
|
@@ -1026,11 +1233,11 @@ const fastify = Fastify({
|
|
|
1026
1233
|
* encapsulation context.
|
|
1027
1234
|
* It may receive as input the schemas of the parent context if some schemas have been added.
|
|
1028
1235
|
* @param {object} externalSchemas these schemas will be returned by the `bucket.getSchemas()`. Needed to resolve the external references $ref.
|
|
1029
|
-
* @param {object} serializerOptsServerOption the server `serializerOpts` options to build your compilers accordingly
|
|
1236
|
+
* @param {object} serializerOptsServerOption the server `serializerOpts` options to build your compilers accordingly
|
|
1030
1237
|
*/
|
|
1031
1238
|
buildSerializer: function factory (externalSchemas, serializerOptsServerOption) {
|
|
1032
1239
|
// This factory function must return a schema serializer compiler.
|
|
1033
|
-
// See [#schema-serializer](Validation-and-Serialization.md#schema-serializer) for details.
|
|
1240
|
+
// See [#schema-serializer](./Validation-and-Serialization.md#schema-serializer) for details.
|
|
1034
1241
|
return function serializerCompiler ({ schema, method, url, httpStatus }) {
|
|
1035
1242
|
return data => JSON.stringify(data)
|
|
1036
1243
|
}
|
|
@@ -1042,8 +1249,10 @@ const fastify = Fastify({
|
|
|
1042
1249
|
|
|
1043
1250
|
##### Ajv 8 as default schema validator
|
|
1044
1251
|
|
|
1045
|
-
Ajv 8 is the evolution of Ajv 6, and it has a lot of improvements and new
|
|
1046
|
-
To use the new Ajv 8 features such as JTD or the Standalone mode,
|
|
1252
|
+
Ajv 8 is the evolution of Ajv 6, and it has a lot of improvements and new
|
|
1253
|
+
features. To use the new Ajv 8 features such as JTD or the Standalone mode,
|
|
1254
|
+
refer to the [`@fastify/ajv-compiler`
|
|
1255
|
+
documentation](https://github.com/fastify/ajv-compiler#usage).
|
|
1047
1256
|
|
|
1048
1257
|
To use Ajv 8 as default schema validator, you can use the following code:
|
|
1049
1258
|
|
|
@@ -1071,14 +1280,25 @@ const app = fastify({
|
|
|
1071
1280
|
// Done! You can now use Ajv 8 options and keywords in your schemas!
|
|
1072
1281
|
```
|
|
1073
1282
|
|
|
1074
|
-
<a name="set-not-found-handler"></a>
|
|
1075
1283
|
#### setNotFoundHandler
|
|
1284
|
+
<a id="set-not-found-handler"></a>
|
|
1076
1285
|
|
|
1077
|
-
`fastify.setNotFoundHandler(handler(request, reply))`: set the 404 handler. This
|
|
1286
|
+
`fastify.setNotFoundHandler(handler(request, reply))`: set the 404 handler. This
|
|
1287
|
+
call is encapsulated by prefix, so different plugins can set different not found
|
|
1288
|
+
handlers if a different [`prefix` option](./Plugins.md#route-prefixing-option)
|
|
1289
|
+
is passed to `fastify.register()`. The handler is treated as a regular route
|
|
1290
|
+
handler so requests will go through the full [Fastify
|
|
1291
|
+
lifecycle](./Lifecycle.md#lifecycle).
|
|
1078
1292
|
|
|
1079
|
-
You can also register
|
|
1293
|
+
You can also register
|
|
1294
|
+
[`preValidation`](./Hooks.md#route-hooks) and
|
|
1295
|
+
[`preHandler`](./Hooks.md#route-hooks) hooks for
|
|
1296
|
+
the 404 handler.
|
|
1080
1297
|
|
|
1081
|
-
_Note: The `preValidation` hook registered using this method will run for a
|
|
1298
|
+
_Note: The `preValidation` hook registered using this method will run for a
|
|
1299
|
+
route that Fastify does not recognize and **not** when a route handler manually
|
|
1300
|
+
calls [`reply.callNotFound`](./Reply.md#call-not-found)_. In which case, only
|
|
1301
|
+
preHandler will be run.
|
|
1082
1302
|
|
|
1083
1303
|
```js
|
|
1084
1304
|
fastify.setNotFoundHandler({
|
|
@@ -1103,13 +1323,22 @@ fastify.register(function (instance, options, done) {
|
|
|
1103
1323
|
}, { prefix: '/v1' })
|
|
1104
1324
|
```
|
|
1105
1325
|
|
|
1106
|
-
Fastify calls setNotFoundHandler to add a default 404 handler at startup before
|
|
1326
|
+
Fastify calls setNotFoundHandler to add a default 404 handler at startup before
|
|
1327
|
+
plugins are registered. If you would like to augment the behavior of the default
|
|
1328
|
+
404 handler, for example with plugins, you can call setNotFoundHandler with no
|
|
1329
|
+
arguments `fastify.setNotFoundHandler()` within the context of these registered
|
|
1330
|
+
plugins.
|
|
1107
1331
|
|
|
1108
|
-
<a name="set-error-handler"></a>
|
|
1109
1332
|
#### setErrorHandler
|
|
1333
|
+
<a id="set-error-handler"></a>
|
|
1110
1334
|
|
|
1111
|
-
`fastify.setErrorHandler(handler(error, request, reply))`: Set a function that
|
|
1112
|
-
|
|
1335
|
+
`fastify.setErrorHandler(handler(error, request, reply))`: Set a function that
|
|
1336
|
+
will be called whenever an error happens. The handler is bound to the Fastify
|
|
1337
|
+
instance and is fully encapsulated, so different plugins can set different error
|
|
1338
|
+
handlers. *async-await* is supported as well.
|
|
1339
|
+
|
|
1340
|
+
*Note: If the error `statusCode` is less than 400, Fastify will automatically
|
|
1341
|
+
set it at 500 before calling the error handler.*
|
|
1113
1342
|
|
|
1114
1343
|
```js
|
|
1115
1344
|
fastify.setErrorHandler(function (error, request, reply) {
|
|
@@ -1120,7 +1349,9 @@ fastify.setErrorHandler(function (error, request, reply) {
|
|
|
1120
1349
|
})
|
|
1121
1350
|
```
|
|
1122
1351
|
|
|
1123
|
-
Fastify is provided with a default function that is called if no error handler
|
|
1352
|
+
Fastify is provided with a default function that is called if no error handler
|
|
1353
|
+
is set. It can be accessed using `fastify.errorHandler` and it logs the error
|
|
1354
|
+
with respect to its `statusCode`.
|
|
1124
1355
|
|
|
1125
1356
|
```js
|
|
1126
1357
|
var statusCode = error.statusCode
|
|
@@ -1133,10 +1364,13 @@ if (statusCode >= 500) {
|
|
|
1133
1364
|
}
|
|
1134
1365
|
```
|
|
1135
1366
|
|
|
1136
|
-
<a name="print-routes"></a>
|
|
1137
1367
|
#### printRoutes
|
|
1368
|
+
<a id="print-routes"></a>
|
|
1369
|
+
|
|
1370
|
+
`fastify.printRoutes()`: Prints the representation of the internal radix tree
|
|
1371
|
+
used by the router, useful for debugging. Alternatively, `fastify.printRoutes({
|
|
1372
|
+
commonPrefix: false })` can be used to print the flattened routes tree.
|
|
1138
1373
|
|
|
1139
|
-
`fastify.printRoutes()`: Prints the representation of the internal radix tree used by the router, useful for debugging. Alternatively, `fastify.printRoutes({ commonPrefix: false })` can be used to print the flattened routes tree.<br/>
|
|
1140
1374
|
*Remember to call it inside or after a `ready` call.*
|
|
1141
1375
|
|
|
1142
1376
|
```js
|
|
@@ -1160,11 +1394,15 @@ fastify.ready(() => {
|
|
|
1160
1394
|
// │ └── /hello (GET)
|
|
1161
1395
|
// ├── hello/world (GET)
|
|
1162
1396
|
// └── helicopter (GET)
|
|
1163
|
-
|
|
1397
|
+
|
|
1164
1398
|
})
|
|
1165
1399
|
```
|
|
1166
1400
|
|
|
1167
|
-
`fastify.printRoutes({ includeMeta: (true | []) })` will display properties from
|
|
1401
|
+
`fastify.printRoutes({ includeMeta: (true | []) })` will display properties from
|
|
1402
|
+
the `route.store` object for each displayed route. This can be an `array` of
|
|
1403
|
+
keys (e.g. `['onRequest', Symbol('key')]`), or `true` to display all properties.
|
|
1404
|
+
A shorthand option, `fastify.printRoutes({ includeHooks: true })` will include
|
|
1405
|
+
all [hooks](./Hooks.md).
|
|
1168
1406
|
|
|
1169
1407
|
```js
|
|
1170
1408
|
console.log(fastify.printRoutes({ includeHooks: true, includeMeta: ['metaProperty'] }))
|
|
@@ -1181,7 +1419,7 @@ fastify.ready(() => {
|
|
|
1181
1419
|
console.log(fastify.printRoutes({ includeHooks: true }))
|
|
1182
1420
|
// └── /
|
|
1183
1421
|
// ├── test (GET)
|
|
1184
|
-
// │ • (onRequest) ["anonymous()","namedFunction()"]
|
|
1422
|
+
// │ • (onRequest) ["anonymous()","namedFunction()"]
|
|
1185
1423
|
// │ └── /hello (GET)
|
|
1186
1424
|
// └── hel
|
|
1187
1425
|
// ├── lo/world (GET)
|
|
@@ -1189,10 +1427,12 @@ fastify.ready(() => {
|
|
|
1189
1427
|
// └── licopter (GET)
|
|
1190
1428
|
```
|
|
1191
1429
|
|
|
1192
|
-
<a name="print-plugins"></a>
|
|
1193
1430
|
#### printPlugins
|
|
1431
|
+
<a id="print-plugins"></a>
|
|
1432
|
+
|
|
1433
|
+
`fastify.printPlugins()`: Prints the representation of the internal plugin tree
|
|
1434
|
+
used by the avvio, useful for debugging require order issues.
|
|
1194
1435
|
|
|
1195
|
-
`fastify.printPlugins()`: Prints the representation of the internal plugin tree used by the avvio, useful for debugging require order issues.<br/>
|
|
1196
1436
|
*Remember to call it inside or after a `ready` call.*
|
|
1197
1437
|
|
|
1198
1438
|
```js
|
|
@@ -1211,25 +1451,32 @@ fastify.ready(() => {
|
|
|
1211
1451
|
})
|
|
1212
1452
|
```
|
|
1213
1453
|
|
|
1214
|
-
<a name="addContentTypeParser"></a>
|
|
1215
1454
|
#### addContentTypeParser
|
|
1455
|
+
<a id="addContentTypeParser"></a>
|
|
1216
1456
|
|
|
1217
|
-
`fastify.addContentTypeParser(content-type, options, parser)` is used to pass
|
|
1457
|
+
`fastify.addContentTypeParser(content-type, options, parser)` is used to pass
|
|
1458
|
+
custom parser for a given content type. Useful for adding parsers for custom
|
|
1459
|
+
content types, e.g. `text/json, application/vnd.oasis.opendocument.text`.
|
|
1460
|
+
`content-type` can be a string, string array or RegExp.
|
|
1218
1461
|
|
|
1219
1462
|
```js
|
|
1220
|
-
// 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
|
|
1463
|
+
// 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.
|
|
1221
1464
|
|
|
1222
1465
|
fastify.addContentTypeParser('text/json', { asString: true }, fastify.getDefaultJsonParser('ignore', 'ignore'))
|
|
1223
1466
|
```
|
|
1224
1467
|
|
|
1225
|
-
<a name="getDefaultJsonParser"></a>
|
|
1226
1468
|
#### getDefaultJsonParser
|
|
1469
|
+
<a id="getDefaultJsonParser"></a>
|
|
1227
1470
|
|
|
1228
|
-
`fastify.getDefaultJsonParser(onProtoPoisoning, onConstructorPoisoning)` takes
|
|
1471
|
+
`fastify.getDefaultJsonParser(onProtoPoisoning, onConstructorPoisoning)` takes
|
|
1472
|
+
two arguments. First argument is ProtoType poisoning configuration and second
|
|
1473
|
+
argument is constructor poisoning configuration. See the [`secure-json-parse`
|
|
1474
|
+
documentation](https://github.com/fastify/secure-json-parse#api) for more
|
|
1475
|
+
information.
|
|
1229
1476
|
|
|
1230
1477
|
|
|
1231
|
-
<a name="defaultTextParser"></a>
|
|
1232
1478
|
#### defaultTextParser
|
|
1479
|
+
<a id="defaultTextParser"></a>
|
|
1233
1480
|
|
|
1234
1481
|
`fastify.defaultTextParser()` can be used to parse content as plain text.
|
|
1235
1482
|
|
|
@@ -1237,10 +1484,11 @@ fastify.addContentTypeParser('text/json', { asString: true }, fastify.getDefault
|
|
|
1237
1484
|
fastify.addContentTypeParser('text/json', { asString: true }, fastify.defaultTextParser())
|
|
1238
1485
|
```
|
|
1239
1486
|
|
|
1240
|
-
<a name="errorHandler"></a>
|
|
1241
1487
|
#### errorHandler
|
|
1488
|
+
<a id="errorHandler"></a>
|
|
1242
1489
|
|
|
1243
|
-
`fastify.errorHandler` can be used to handle errors using fastify's default
|
|
1490
|
+
`fastify.errorHandler` can be used to handle errors using fastify's default
|
|
1491
|
+
error handler.
|
|
1244
1492
|
|
|
1245
1493
|
```js
|
|
1246
1494
|
fastify.get('/', {
|
|
@@ -1255,11 +1503,11 @@ fastify.get('/', {
|
|
|
1255
1503
|
}, handler)
|
|
1256
1504
|
```
|
|
1257
1505
|
|
|
1258
|
-
<a name="initial-config"></a>
|
|
1259
1506
|
#### initialConfig
|
|
1507
|
+
<a id="initial-config"></a>
|
|
1260
1508
|
|
|
1261
|
-
`fastify.initialConfig`: Exposes a frozen read-only object registering the
|
|
1262
|
-
options passed down by the user to the Fastify instance.
|
|
1509
|
+
`fastify.initialConfig`: Exposes a frozen read-only object registering the
|
|
1510
|
+
initial options passed down by the user to the Fastify instance.
|
|
1263
1511
|
|
|
1264
1512
|
Currently the properties that can be exposed are:
|
|
1265
1513
|
- connectionTimeout
|
|
@@ -1267,7 +1515,8 @@ Currently the properties that can be exposed are:
|
|
|
1267
1515
|
- bodyLimit
|
|
1268
1516
|
- caseSensitive
|
|
1269
1517
|
- http2
|
|
1270
|
-
- https (it will return `false`/`true` or `{ allowHTTP1: true/false }` if
|
|
1518
|
+
- https (it will return `false`/`true` or `{ allowHTTP1: true/false }` if
|
|
1519
|
+
explicitly passed)
|
|
1271
1520
|
- ignoreTrailingSlash
|
|
1272
1521
|
- disableRequestLogging
|
|
1273
1522
|
- maxParamLength
|