-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Server.md
1778 lines (1426 loc) · 55.8 KB
/
Server.md
1
2
3
4
5
6
7
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<h1 align="center">Fastify</h1>
## Factory
<a id="factory"></a>
The Fastify module exports a factory function that is used to create new
<code><b>Fastify server</b></code> instances. This factory function accepts an
options object which is used to customize the resulting instance. This document
describes the properties available in that options object.
- [Factory](#factory)
- [`http2`](#http2)
- [`https`](#https)
- [`connectionTimeout`](#connectiontimeout)
- [`keepAliveTimeout`](#keepalivetimeout)
- [`forceCloseConnections`](#forcecloseconnections)
- [`maxRequestsPerSocket`](#maxrequestspersocket)
- [`requestTimeout`](#requesttimeout)
- [`ignoreTrailingSlash`](#ignoretrailingslash)
- [`ignoreDuplicateSlashes`](#ignoreduplicateslashes)
- [`maxParamLength`](#maxparamlength)
- [`bodyLimit`](#bodylimit)
- [`onProtoPoisoning`](#onprotopoisoning)
- [`onConstructorPoisoning`](#onconstructorpoisoning)
- [`logger`](#logger)
- [`disableRequestLogging`](#disablerequestlogging)
- [`serverFactory`](#serverfactory)
- [`jsonShorthand`](#jsonshorthand)
- [`caseSensitive`](#casesensitive)
- [`allowUnsafeRegex`](#allowunsaferegex)
- [`requestIdHeader`](#requestidheader)
- [`requestIdLogLabel`](#requestidloglabel)
- [`genReqId`](#genreqid)
- [`trustProxy`](#trustproxy)
- [`pluginTimeout`](#plugintimeout)
- [`querystringParser`](#querystringparser)
- [`exposeHeadRoutes`](#exposeheadroutes)
- [`constraints`](#constraints)
- [`return503OnClosing`](#return503onclosing)
- [`ajv`](#ajv)
- [`serializerOpts`](#serializeropts)
- [`http2SessionTimeout`](#http2sessiontimeout)
- [`frameworkErrors`](#frameworkerrors)
- [`clientErrorHandler`](#clienterrorhandler)
- [`rewriteUrl`](#rewriteurl)
- [Instance](#instance)
- [Server Methods](#server-methods)
- [server](#server)
- [after](#after)
- [ready](#ready)
- [listen](#listen)
- [addresses](#addresses)
- [getDefaultRoute](#getdefaultroute)
- [setDefaultRoute](#setdefaultroute)
- [routing](#routing)
- [route](#route)
- [hasRoute](#hasRoute)
- [close](#close)
- [decorate*](#decorate)
- [register](#register)
- [addHook](#addhook)
- [prefix](#prefix)
- [pluginName](#pluginname)
- [hasPlugin](#hasplugin)
- [log](#log)
- [version](#version)
- [inject](#inject)
- [addSchema](#addschema)
- [getSchemas](#getschemas)
- [getSchema](#getschema)
- [setReplySerializer](#setreplyserializer)
- [setValidatorCompiler](#setvalidatorcompiler)
- [setSchemaErrorFormatter](#setschemaerrorformatter)
- [setSerializerCompiler](#setserializercompiler)
- [validatorCompiler](#validatorcompiler)
- [serializerCompiler](#serializercompiler)
- [schemaErrorFormatter](#schemaerrorformatter)
- [schemaController](#schemacontroller)
- [setNotFoundHandler](#setnotfoundhandler)
- [setErrorHandler](#seterrorhandler)
- [addConstraintStrategy](#addconstraintstrategy)
- [hasConstraintStrategy](#hasconstraintstrategy)
- [printRoutes](#printroutes)
- [printPlugins](#printplugins)
- [addContentTypeParser](#addcontenttypeparser)
- [hasContentTypeParser](#hascontenttypeparser)
- [removeContentTypeParser](#removecontenttypeparser)
- [removeAllContentTypeParsers](#removeallcontenttypeparsers)
- [getDefaultJsonParser](#getdefaultjsonparser)
- [defaultTextParser](#defaulttextparser)
- [errorHandler](#errorhandler)
- [initialConfig](#initialconfig)
### `http2`
<a id="factory-http2"></a>
If `true` Node.js core's
[HTTP/2](https://nodejs.org/dist/latest-v14.x/docs/api/http2.html) module is
used for binding the socket.
+ Default: `false`
### `https`
<a id="factory-https"></a>
An object used to configure the server's listening socket for TLS. The options
are the same as the Node.js core [`createServer`
method](https://nodejs.org/dist/latest-v14.x/docs/api/https.html#https_https_createserver_options_requestlistener).
When this property is `null`, the socket will not be configured for TLS.
This option also applies when the [`http2`](#factory-http2) option is set.
+ Default: `null`
### `connectionTimeout`
<a id="factory-connection-timeout"></a>
Defines the server timeout in milliseconds. See documentation for
[`server.timeout`
property](https://nodejs.org/api/http.html#http_server_timeout) to understand
the effect of this option. When `serverFactory` option is specified, this option
is ignored.
+ Default: `0` (no timeout)
### `keepAliveTimeout`
<a id="factory-keep-alive-timeout"></a>
Defines the server keep-alive timeout in milliseconds. See documentation for
[`server.keepAliveTimeout`
property](https://nodejs.org/api/http.html#http_server_keepalivetimeout) to
understand the effect of this option. This option only applies when HTTP/1 is in
use. Also, when `serverFactory` option is specified, this option is ignored.
+ Default: `72000` (72 seconds)
### `forceCloseConnections`
<a id="forcecloseconnections"></a>
When set to `true`, upon [`close`](#close) the server will iterate the current
persistent connections and [destroy their
sockets](https://nodejs.org/dist/latest-v16.x/docs/api/net.html#socketdestroyerror).
> Important: connections are not inspected to determine if requests have been
> completed.
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.
When set to `"idle"`, upon [`close`](#close) the server will iterate the current
persistent connections which are not sending a request or waiting for a response
and destroy their sockets. 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.
+ Default: `"idle"` if the HTTP server allows it, `false` otherwise
### `maxRequestsPerSocket`
<a id="factory-max-requests-per-socket"></a>
Defines the maximum number of requests socket can handle before closing keep
alive connection. See documentation for [`server.maxRequestsPerSocket`
property](https://nodejs.org/dist/latest/docs/api/http.html#http_server_maxrequestspersocket)
to understand the effect of this option. This option only applies when HTTP/1.1
is in use. Also, when `serverFactory` option is specified, this option is
ignored.
> At the time of this writing, only node version greater or equal to 16.10.0
> support this option. Check the Node.js documentation for availability in the
> version you are running.
+ Default: `0` (no limit)
### `requestTimeout`
<a id="factory-request-timeout"></a>
Defines the maximum number of milliseconds for receiving the entire request from
the client. [`server.requestTimeout`
property](https://nodejs.org/dist/latest/docs/api/http.html#http_server_requesttimeout)
to understand the effect of this option. Also, when `serverFactory` option is
specified, this option is ignored. It must be set to a non-zero value (e.g. 120
seconds) to protect against potential Denial-of-Service attacks in case the
server is deployed without a reverse proxy in front.
> At the time of this writing, only node version greater or equal to 14.11.0
> support this option. Check the Node.js documentation for availability in the
> version you are running.
+ Default: `0` (no limit)
### `ignoreTrailingSlash`
<a id="factory-ignore-slash"></a>
Fastify uses [find-my-way](https://github.com/delvedor/find-my-way) to handle
routing. By default, Fastify is set to take into account the trailing slashes.
Paths like `/foo` and `/foo/` will be treated as different paths. If you want to
change this, set this flag to `true`. That way, both `/foo` and `/foo/` will
point to the same route. This option applies to *all* route registrations for
the resulting server instance.
+ Default: `false`
```js
const fastify = require('fastify')({
ignoreTrailingSlash: true
})
// registers both "/foo" and "/foo/"
fastify.get('/foo/', function (req, reply) {
reply.send('foo')
})
// registers both "/bar" and "/bar/"
fastify.get('/bar', function (req, reply) {
reply.send('bar')
})
```
### `ignoreDuplicateSlashes`
<a id="factory-ignore-duplicate-slashes"></a>
Fastify uses [find-my-way](https://github.com/delvedor/find-my-way) to handle
routing. You can use `ignoreDuplicateSlashes` option to remove duplicate slashes
from the path. It removes duplicate slashes in the route path and in the request
URL. This option applies to *all* route registrations for the resulting server
instance.
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.
+ Default: `false`
```js
const fastify = require('fastify')({
ignoreDuplicateSlashes: true
})
// registers "/foo/bar/"
fastify.get('///foo//bar//', function (req, reply) {
reply.send('foo')
})
```
### `maxParamLength`
<a id="factory-max-param-length"></a>
You can set a custom length for parameters in parametric (standard, regex, and
multi) routes by using `maxParamLength` option; the default value is 100
characters.
This can be useful especially if you have a regex-based route, protecting you
against [DoS
attacks](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS).
*If the maximum length limit is reached, the not found route will be invoked.*
### `bodyLimit`
<a id="factory-body-limit"></a>
Defines the maximum payload, in bytes, the server is allowed to accept.
+ Default: `1048576` (1MiB)
### `onProtoPoisoning`
<a id="factory-on-proto-poisoning"></a>
Defines what action the framework must take when parsing a JSON object with
`__proto__`. This functionality is provided by
[secure-json-parse](https://github.com/fastify/secure-json-parse). See
[Prototype Poisoning](../Guides/Prototype-Poisoning.md) for more details about
prototype poisoning attacks.
Possible values are `'error'`, `'remove'` and `'ignore'`.
+ Default: `'error'`
### `onConstructorPoisoning`
<a id="factory-on-constructor-poisoning"></a>
Defines what action the framework must take when parsing a JSON object with
`constructor`. This functionality is provided by
[secure-json-parse](https://github.com/fastify/secure-json-parse). See
[Prototype Poisoning](../Guides/Prototype-Poisoning.md) for more details about
prototype poisoning attacks.
Possible values are `'error'`, `'remove'` and `'ignore'`.
+ Default: `'error'`
### `logger`
<a id="factory-logger"></a>
Fastify includes built-in logging via the [Pino](https://getpino.io/) logger.
This property is used to configure the internal logger instance.
The possible values this property may have are:
+ Default: `false`. The logger is disabled. All logging methods will point to a
null logger [abstract-logging](https://npm.im/abstract-logging) instance.
+ `pinoInstance`: a previously instantiated instance of Pino. The internal
logger will point to this instance.
+ `object`: a standard Pino [options
object](https://github.com/pinojs/pino/blob/c77d8ec5ce/docs/API.md#constructor).
This will be passed directly to the Pino constructor. If the following
properties are not present on the object, they will be added accordingly:
* `level`: the minimum logging level. If not set, it will be set to
`'info'`.
* `serializers`: a hash of serialization functions. By default, serializers
are added for `req` (incoming request objects), `res` (outgoing response
objects), and `err` (standard `Error` objects). When a log method receives
an object with any of these properties then the respective serializer will
be used for that property. For example:
```js
fastify.get('/foo', function (req, res) {
req.log.info({req}) // log the serialized request object
res.send('foo')
})
```
Any user-supplied serializer will override the default serializer of the
corresponding property.
+ `loggerInstance`: a custom logger instance. The logger must conform to the
Pino interface by having the following methods: `info`, `error`, `debug`,
`fatal`, `warn`, `trace`, `child`. For example:
```js
const pino = require('pino')();
const customLogger = {
info: function (o, ...n) {},
warn: function (o, ...n) {},
error: function (o, ...n) {},
fatal: function (o, ...n) {},
trace: function (o, ...n) {},
debug: function (o, ...n) {},
child: function() {
const child = Object.create(this);
child.pino = pino.child(...arguments);
return child;
},
};
const fastify = require('fastify')({logger: customLogger});
```
### `disableRequestLogging`
<a id="factory-disable-request-logging"></a>
By default, when logging is enabled, Fastify will issue an `info` level log
message when a request is received and when the response for that request has
been sent. By setting this option to `true`, these log messages will be
disabled. This allows for more flexible request start and end logging by
attaching custom `onRequest` and `onResponse` hooks.
+ Default: `false`
```js
// Examples of hooks to replicate the disabled functionality.
fastify.addHook('onRequest', (req, reply, done) => {
req.log.info({ url: req.raw.url, id: req.id }, 'received request')
done()
})
fastify.addHook('onResponse', (req, reply, done) => {
req.log.info({ url: req.raw.originalUrl, statusCode: reply.raw.statusCode }, 'request completed')
done()
})
```
Please note that this setting will also disable an error log written by the
default `onResponse` hook on reply callback errors.
### `serverFactory`
<a id="custom-http-server"></a>
You can pass a custom HTTP server to Fastify by using the `serverFactory`
option.
`serverFactory` is a function that takes a `handler` parameter, which takes the
`request` and `response` objects as parameters, and an options object, which is
the same you have passed to Fastify.
```js
const serverFactory = (handler, opts) => {
const server = http.createServer((req, res) => {
handler(req, res)
})
return server
}
const fastify = Fastify({ serverFactory })
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
fastify.listen({ port: 3000 })
```
Internally Fastify uses the API of Node core HTTP server, so if you are using a
custom server you must be sure to have the same API exposed. If not, you can
enhance the server instance inside the `serverFactory` function before the
`return` statement.
### `jsonShorthand`
<a id="schema-json-shorthand"></a>
+ Default: `true`
Internally, and by default, Fastify will automatically infer the root properties
of JSON Schemas if it does not find valid root properties according to the JSON
Schema spec. If you wish to implement your own schema validation compiler, for
example: to parse schemas as JTD instead of JSON Schema, then you can explicitly
set this option to `false` to make sure the schemas you receive are unmodified
and are not being treated internally as JSON Schema.
```js
const AjvJTD = require('ajv/dist/jtd'/* only valid for AJV v7+ */)
const ajv = new AjvJTD({
// This would let you throw at start for invalid JTD schema objects
allErrors: process.env.NODE_ENV === 'development'
})
const fastify = Fastify({ jsonShorthand: false })
fastify.setValidatorCompiler(({ schema }) => {
return ajv.compile(schema)
})
fastify.post('/', {
schema: {
body: {
properties: {
foo: { type: 'uint8' }
}
}
},
handler (req, reply) { reply.send({ ok: 1 }) }
})
```
**Note: Fastify does not currently throw on invalid schemas, so if you turn this
off in an existing project, you need to be careful that none of your existing
schemas become invalid as a result, since they will be treated as a catch-all.**
### `caseSensitive`
<a id="factory-case-sensitive"></a>
By default, value equal to `true`, routes are registered as case sensitive. That
is, `/foo` is not equivalent to `/Foo`. When set to `false`, routes are
registered in a fashion such that `/foo` is equivalent to `/Foo` which is
equivalent to `/FOO`.
By setting `caseSensitive` to `false`, all paths will be matched as lowercase,
but the route parameters or wildcards will maintain their original letter
casing.
```js
fastify.get('/user/:username', (request, reply) => {
// Given the URL: /USER/NodeJS
console.log(request.params.username) // -> 'NodeJS'
})
```
Please note that setting this option to `false` goes against
[RFC3986](https://tools.ietf.org/html/rfc3986#section-6.2.2.1).
Also note, this setting will not affect query strings. If you want to change the
way query strings are handled take a look at
[`querystringParser`](#querystringparser).
### `allowUnsafeRegex`
<a id="factory-allow-unsafe-regex"></a>
The allowUnsafeRegex setting is false by default, so routes only allow safe
regular expressions. To use unsafe expressions, set allowUnsafeRegex to true.
```js
fastify.get('/user/:id(^([0-9]+){4}$)', (request, reply) => {
// Throws an error without allowUnsafeRegex = true
})
```
Under the hood: [FindMyWay](https://github.com/delvedor/find-my-way) More info
about safe regexp: [Safe-regex2](https://www.npmjs.com/package/safe-regex2)
### `requestIdHeader`
<a id="factory-request-id-header"></a>
The header name used to set the request-id. See [the
request-id](./Logging.md#logging-request-id) section.
Setting `requestIdHeader` to `false` will always use [genReqId](#genreqid)
+ Default: `'request-id'`
```js
const fastify = require('fastify')({
requestIdHeader: 'x-custom-id', // -> use 'X-Custom-Id' header if available
//requestIdHeader: false, // -> always use genReqId
})
```
### `requestIdLogLabel`
<a id="factory-request-id-log-label"></a>
Defines the label used for the request identifier when logging the request.
+ Default: `'reqId'`
### `genReqId`
<a id="factory-gen-request-id"></a>
Function for generating the request-id. It will receive the incoming request as
a parameter. This function is expected to be error-free.
+ Default: `value of 'request-id' header if provided or monotonically increasing
integers`
Especially in distributed systems, you may want to override the default ID
generation behavior as shown below. For generating `UUID`s you may want to check
out [hyperid](https://github.com/mcollina/hyperid)
```js
let i = 0
const fastify = require('fastify')({
genReqId: function (req) { return i++ }
})
```
**Note: genReqId will _not_ be called if the header set in
<code>[requestIdHeader](#requestidheader)</code> is available (defaults to
'request-id').**
### `trustProxy`
<a id="factory-trust-proxy"></a>
By enabling the `trustProxy` option, Fastify will know that it is sitting behind
a proxy and that the `X-Forwarded-*` header fields may be trusted, which
otherwise may be easily spoofed.
```js
const fastify = Fastify({ trustProxy: true })
```
+ Default: `false`
+ `true/false`: Trust all proxies (`true`) or do not trust any proxies
(`false`).
+ `string`: Trust only given IP/CIDR (e.g. `'127.0.0.1'`). May be a list of
comma separated values (e.g. `'127.0.0.1,192.168.1.1/24'`).
+ `Array<string>`: Trust only given IP/CIDR list (e.g. `['127.0.0.1']`).
+ `number`: Trust the nth hop from the front-facing proxy server as the client.
+ `Function`: Custom trust function that takes `address` as first arg
```js
function myTrustFn(address, hop) {
return address === '1.2.3.4' || hop === 1
}
```
For more examples, refer to the
[`proxy-addr`](https://www.npmjs.com/package/proxy-addr) package.
You may access the `ip`, `ips`, `hostname` and `protocol` values on the
[`request`](./Request.md) object.
```js
fastify.get('/', (request, reply) => {
console.log(request.ip)
console.log(request.ips)
console.log(request.hostname)
console.log(request.protocol)
})
```
**Note: if a request contains multiple <code>x-forwarded-host</code> or
<code>x-forwarded-proto</code> headers, it is only the last one that is used to
derive <code>request.hostname</code> and <code>request.protocol</code>**
### `pluginTimeout`
<a id="plugin-timeout"></a>
The maximum amount of time in *milliseconds* in which a plugin can load. If not,
[`ready`](#ready) will complete with an `Error` with code
`'ERR_AVVIO_PLUGIN_TIMEOUT'`. When set to `0`, disables this check. This
controls [avvio](https://www.npmjs.com/package/avvio) 's `timeout` parameter.
+ Default: `10000`
### `querystringParser`
<a id="factory-querystring-parser"></a>
The default query string parser that Fastify uses is the Node.js's core
`querystring` module.
You can change this default setting by passing the option `querystringParser`
and use a custom one, such as [`qs`](https://www.npmjs.com/package/qs).
```js
const qs = require('qs')
const fastify = require('fastify')({
querystringParser: str => qs.parse(str)
})
```
You can also use Fastify's default parser but change some handling behaviour,
like the example below for case insensitive keys and values:
```js
const querystring = require('querystring')
const fastify = require('fastify')({
querystringParser: str => querystring.parse(str.toLowerCase())
})
```
Note, if you only want the keys (and not the values) to be case insensitive we
recommend using a custom parser to convert only the keys to lowercase.
### `exposeHeadRoutes`
<a id="exposeHeadRoutes"></a>
Automatically creates a sibling `HEAD` route for each `GET` route defined. If
you want a custom `HEAD` handler without disabling this option, make sure to
define it before the `GET` route.
+ Default: `true`
### `constraints`
<a id="constraints"></a>
Fastify's built in route constraints are provided by `find-my-way`, which allow
constraining routes by `version` or `host`. You are able to add new constraint
strategies, or override the built in strategies by providing a `constraints`
object with strategies for `find-my-way`. You can find more information on
constraint strategies in the
[find-my-way](https://github.com/delvedor/find-my-way) documentation.
```js
const customVersionStrategy = {
storage: function () {
const versions = {}
return {
get: (version) => { return versions[version] || null },
set: (version, store) => { versions[version] = store }
}
},
deriveVersion: (req, ctx) => {
return req.headers['accept']
}
}
const fastify = require('fastify')({
constraints: {
version: customVersionStrategy
}
})
```
### `return503OnClosing`
<a id="factory-return-503-on-closing"></a>
Returns 503 after calling `close` server method. If `false`, the server routes
the incoming request as usual.
+ Default: `true`
### `ajv`
<a id="factory-ajv"></a>
Configure the Ajv v8 instance used by Fastify without providing a custom one.
The default configuration is explained in the
[#schema-validator](./Validation-and-Serialization.md#schema-validator) section.
```js
const fastify = require('fastify')({
ajv: {
customOptions: {
removeAdditional: 'all' // Refer to [ajv options](https://ajv.js.org/options.html#removeadditional)
},
plugins: [
require('ajv-merge-patch'),
[require('ajv-keywords'), 'instanceof']
// Usage: [plugin, pluginOptions] - Plugin with options
// Usage: plugin - Plugin without options
]
}
})
```
### `serializerOpts`
<a id="serializer-opts"></a>
Customize the options of the default
[`fast-json-stringify`](https://github.com/fastify/fast-json-stringify#options)
instance that serialize the response's payload:
```js
const fastify = require('fastify')({
serializerOpts: {
rounding: 'ceil'
}
})
```
### `http2SessionTimeout`
<a id="http2-session-timeout"></a>
Set a default
[timeout](https://nodejs.org/api/http2.html#http2_http2session_settimeout_msecs_callback)
to every incoming HTTP/2 session. The session will be closed on the timeout.
Default: `72000` ms.
Note that this is needed to offer the graceful "close" experience when using
HTTP/2. The low default has been chosen to mitigate denial of service attacks.
When the server is behind a load balancer or can scale automatically this value
can be increased to fit the use case. Node core defaults this to `0`. `
### `frameworkErrors`
<a id="framework-errors"></a>
+ Default: `null`
Fastify provides default error handlers for the most common use cases. It is
possible to override one or more of those handlers with custom code using this
option.
*Note: Only `FST_ERR_BAD_URL` is implemented at the moment.*
```js
const fastify = require('fastify')({
frameworkErrors: function (error, req, res) {
if (error instanceof FST_ERR_BAD_URL) {
res.code(400)
return res.send("Provided url is not valid")
} else if(error instanceof FST_ERR_ASYNC_CONSTRAINT) {
res.code(400)
return res.send("Provided header is not valid")
} else {
res.send(err)
}
}
})
```
### `clientErrorHandler`
<a id="client-error-handler"></a>
Set a
[clientErrorHandler](https://nodejs.org/api/http.html#http_event_clienterror)
that listens to `error` events emitted by client connections and responds with a
`400`.
It is possible to override the default `clientErrorHandler` using this option.
+ Default:
```js
function defaultClientErrorHandler (err, socket) {
if (err.code === 'ECONNRESET') {
return
}
const body = JSON.stringify({
error: http.STATUS_CODES['400'],
message: 'Client Error',
statusCode: 400
})
this.log.trace({ err }, 'client error')
if (socket.writable) {
socket.end([
'HTTP/1.1 400 Bad Request',
`Content-Length: ${body.length}`,
`Content-Type: application/json\r\n\r\n${body}`
].join('\r\n'))
}
}
```
*Note: `clientErrorHandler` operates with raw socket. The handler is expected to
return a properly formed HTTP response that includes a status line, HTTP headers
and a message body. Before attempting to write the socket, the handler should
check if the socket is still writable as it may have already been destroyed.*
```js
const fastify = require('fastify')({
clientErrorHandler: function (err, socket) {
const body = JSON.stringify({
error: {
message: 'Client error',
code: '400'
}
})
// `this` is bound to fastify instance
this.log.trace({ err }, 'client error')
// the handler is responsible for generating a valid HTTP response
socket.end([
'HTTP/1.1 400 Bad Request',
`Content-Length: ${body.length}`,
`Content-Type: application/json\r\n\r\n${body}`
].join('\r\n'))
}
})
```
### `rewriteUrl`
<a id="rewrite-url"></a>
Set a sync callback function that must return a string that allows rewriting
URLs.
> Rewriting a URL will modify the `url` property of the `req` object
```js
function rewriteUrl (req) { // req is the Node.js HTTP request
return req.url === '/hi' ? '/hello' : req.url;
}
```
Note that `rewriteUrl` is called _before_ routing, it is not encapsulated and it
is an instance-wide configuration.
## Instance
### Server Methods
#### server
<a id="server"></a>
`fastify.server`: The Node core
[server](https://nodejs.org/api/http.html#http_class_http_server) object as
returned by the [**`Fastify factory function`**](#factory).
#### after
<a id="after"></a>
Invoked when the current plugin and all the plugins that have been registered
within it have finished loading. It is always executed before the method
`fastify.ready`.
```js
fastify
.register((instance, opts, done) => {
console.log('Current plugin')
done()
})
.after(err => {
console.log('After current plugin')
})
.register((instance, opts, done) => {
console.log('Next plugin')
done()
})
.ready(err => {
console.log('Everything has been loaded')
})
```
In case `after()` is called without a function, it returns a `Promise`:
```js
fastify.register(async (instance, opts) => {
console.log('Current plugin')
})
await fastify.after()
console.log('After current plugin')
fastify.register(async (instance, opts) => {
console.log('Next plugin')
})
await fastify.ready()
console.log('Everything has been loaded')
```
#### ready
<a id="ready"></a>
Function called when all the plugins have been loaded. It takes an error
parameter if something went wrong.
```js
fastify.ready(err => {
if (err) throw err
})
```
If it is called without any arguments, it will return a `Promise`:
```js
fastify.ready().then(() => {
console.log('successfully booted!')
}, (err) => {
console.log('an error happened', err)
})
```
#### listen
<a id="listen"></a>
Starts the server and internally waits for the `.ready()` event. The signature
is `.listen([options][, callback])`. Both the `options` object and the
`callback` parameters follow the [Node.js
core](https://nodejs.org/api/net.html#serverlistenoptions-callback) parameter
definitions.
By default, the server will listen on the address(es) resolved by `localhost`
when no specific host is provided. If listening on any available interface is
desired, then specifying `0.0.0.0` for the address will listen on all IPv4
addresses. The following table details the possible values for `host` when
targeting `localhost`, and what the result of those values for `host` will be.
Host | IPv4 | IPv6
--------------|------|-------
`::` | ✅<sup>*</sup> | ✅
`::` + [`ipv6Only`](https://nodejs.org/api/net.html#serverlistenoptions-callback) | 🚫 | ✅
`0.0.0.0` | ✅ | 🚫
`localhost` | ✅ | ✅
`127.0.0.1` | ✅ | 🚫
`::1` | 🚫 | ✅
<sup>*</sup> Using `::` for the address will listen on all IPv6 addresses and,
depending on OS, may also listen on [all IPv4
addresses](https://nodejs.org/api/net.html#serverlistenport-host-backlog-callback).
Be careful when deciding to listen on all interfaces; it comes with inherent
[security
risks](https://web.archive.org/web/20170831174611/https://snyk.io/blog/mongodb-hack-and-secure-defaults/).
The default is to listen on `port: 0` (which picks the first available open
port) and `host: 'localhost'`:
```js
fastify.listen((err, address) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
```
Specifying an address is also supported:
```js
fastify.listen({ port: 3000, host: '127.0.0.1' }, (err, address) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
```
If no callback is provided a Promise is returned:
```js
fastify.listen({ port: 3000 })
.then((address) => console.log(`server listening on ${address}`))
.catch(err => {
console.log('Error starting server:', err)
process.exit(1)
})
```
When deploying to a Docker, and potentially other, containers, it is advisable
to listen on `0.0.0.0` because they do not default to exposing mapped ports to
`localhost`:
```js
fastify.listen({ port: 3000, host: '0.0.0.0' }, (err, address) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
```
If the `port` is omitted (or is set to zero), a random available port is
automatically chosen (available via `fastify.server.address().port`).
The default options of listen are:
```js
fastify.listen({
port: 0,
host: 'localhost',
exclusive: false,
readableAll: false,
writableAll: false,
ipv6Only: false
}, (err) => {})
```
#### addresses
<a id="addresses"></a>
This method returns an array of addresses that the server is listening on. If
you call it before `listen()` is called or after the `close()` function, it will
return an empty array.
```js