UNPKG

30.1 kBMarkdownView Raw
1<h1 align="center">Fastify</h1>
2
3<a name="factory"></a>
4## Factory
5
6The Fastify module exports a factory function that is used to create new
7<a href="https://github.com/fastify/fastify/blob/master/docs/Server.md"><code><b>Fastify server</b></code></a>
8instances. This factory function accepts an options object which is used to
9customize the resulting instance. This document describes the properties
10available in that options object.
11
12<a name="factory-http2"></a>
13### `http2`
14
15If `true` Node.js core's [HTTP/2](https://nodejs.org/dist/latest-v8.x/docs/api/http2.html) module is used for binding the socket.
16
17+ Default: `false`
18
19<a name="factory-https"></a>
20### `https`
21
22An object used to configure the server's listening socket for TLS. The options
23are the same as the Node.js core
24[`createServer` method](https://nodejs.org/dist/latest-v8.x/docs/api/https.html#https_https_createserver_options_requestlistener).
25When this property is `null`, the socket will not be configured for TLS.
26
27This option also applies when the
28<a href="https://github.com/fastify/fastify/blob/master/docs/Server.md#factory-http2">
29<code><b>http2</b></code>
30</a> option is set.
31
32+ Default: `null`
33
34<a name="factory-ignore-slash"></a>
35### `ignoreTrailingSlash`
36
37Fastify uses [find-my-way](https://github.com/delvedor/find-my-way) to handle
38routing. This option may be set to `true` to ignore trailing slashes in routes.
39This option applies to *all* route registrations for the resulting server
40instance.
41
42+ Default: `false`
43
44```js
45const fastify = require('fastify')({
46 ignoreTrailingSlash: true
47})
48
49// registers both "/foo" and "/foo/"
50fastify.get('/foo/', function (req, reply) {
51 reply.send('foo')
52})
53
54// registers both "/bar" and "/bar/"
55fastify.get('/bar', function (req, reply) {
56 reply.send('bar')
57})
58```
59
60<a name="factory-max-param-length"></a>
61### `maxParamLength`
62You can set a custom length for parameters in parametric (standard, regex and multi) routes by using `maxParamLength` option, the default value is 100 characters.<br>
63This can be useful especially if you have some regex based route, protecting you against [DoS attacks](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS).<br>
64*If the maximum length limit is reached, the not found route will be invoked.*
65
66<a name="factory-body-limit"></a>
67### `bodyLimit`
68
69Defines the maximum payload, in bytes, the server is allowed to accept.
70
71+ Default: `1048576` (1MiB)
72
73<a name="factory-on-proto-poisoning"></a>
74### `onProtoPoisoning`
75
76Defines what action the framework must take when parsing a JSON object
77with `__proto__`. This functionality is provided by
78[secure-json-parse](https://github.com/fastify/secure-json-parse).
79See https://hueniverse.com/a-tale-of-prototype-poisoning-2610fa170061
80for more details about prototype poisoning attacks.
81
82Possible values are `'error'`, `'remove'` and `'ignore'`.
83
84+ Default: `'error'`
85
86<a name="factory-on-constructor-poisoning"></a>
87### `onConstructorPoisoning`
88
89Defines what action the framework must take when parsing a JSON object
90with `constructor`. This functionality is provided by
91[secure-json-parse](https://github.com/fastify/secure-json-parse).
92See https://hueniverse.com/a-tale-of-prototype-poisoning-2610fa170061
93for more details about prototype poisoning attacks.
94
95Possible values are `'error'`, `'remove'` and `'ignore'`.
96
97+ Default: `'ignore'`
98
99<a name="factory-logger"></a>
100### `logger`
101
102Fastify includes built-in logging via the [Pino](https://getpino.io/) logger.
103This property is used to configure the internal logger instance.
104
105The possible values this property may have are:
106
107+ Default: `false`. The logger is disabled. All logging methods will point to a
108null logger [abstract-logging](https://npm.im/abstract-logging) instance.
109
110+ `pinoInstance`: a previously instantiated instance of Pino. The internal
111logger will point to this instance.
112
113+ `object`: a standard Pino [options object](https://github.com/pinojs/pino/blob/c77d8ec5ce/docs/API.md#constructor).
114This will be passed directly to the Pino constructor. If the following properties
115are not present on the object, they will be added accordingly:
116 * `genReqId`: a synchronous function that will be used to generate identifiers
117 for incoming requests. The default function generates sequential identifiers.
118 * `level`: the minimum logging level. If not set, it will be set to `'info'`.
119 * `serializers`: a hash of serialization functions. By default, serializers
120 are added for `req` (incoming request objects), `res` (outgoing response
121 objets), and `err` (standard `Error` objects). When a log method receives
122 an object with any of these properties then the respective serializer will
123 be used for that property. For example:
124 ```js
125 fastify.get('/foo', function (req, res) {
126 req.log.info({req}) // log the serialized request object
127 res.send('foo')
128 })
129 ```
130 Any user supplied serializer will override the default serializer of the
131 corresponding property.
132+ `loggerInstance`: a custom logger instance. The logger must conform to the Pino
133interface by having the following methods: `info`, `error`, `debug`, `fatal`, `warn`, `trace`, `child`. For example:
134 ```js
135 const pino = require('pino')();
136
137 const customLogger = {
138 info: function (o, ...n) {},
139 warn: function (o, ...n) {},
140 error: function (o, ...n) {},
141 fatal: function (o, ...n) {},
142 trace: function (o, ...n) {},
143 debug: function (o, ...n) {},
144 child: function() {
145 const child = Object.create(this);
146 child.pino = pino.child(...arguments);
147 return child;
148 },
149 };
150
151 const fastify = require('fastify')({logger: customLogger});
152 ```
153
154<a name="factory-disable-request-logging"></a>
155### `disableRequestLogging`
156By default, when logging is enabled, Fastify will issue an `info` level log
157message when a request is received and when the response for that request has
158been sent. By setting this option to `true`, these log messages will be disabled.
159This allows for more flexible request start and end logging by attaching
160custom `onRequest` and `onResponse` hooks.
161
162+ Default: `false`
163
164```js
165// Examples of hooks to replicate the disabled functionality.
166fastify.addHook('onRequest', (req, reply, done) => {
167 req.log.info({ url: req.req.url, id: req.id }, 'received request')
168 done()
169})
170
171fastify.addHook('onResponse', (req, reply, done) => {
172 req.log.info({ url: req.req.originalUrl, statusCode: reply.res.statusCode }, 'request completed')
173 done()
174})
175```
176
177<a name="custom-http-server"></a>
178### `serverFactory`
179You can pass a custom http server to Fastify by using the `serverFactory` option.<br/>
180`serverFactory` is a function that takes an `handler` parameter, which takes the `request` and `response` objects as parameters, and an options object, which is the same you have passed to Fastify.
181
182```js
183const serverFactory = (handler, opts) => {
184 const server = http.createServer((req, res) => {
185 handler(req, res)
186 })
187
188 return server
189}
190
191const fastify = Fastify({ serverFactory, modifyCoreObjects: false })
192
193fastify.get('/', (req, reply) => {
194 reply.send({ hello: 'world' })
195})
196
197fastify.listen(3000)
198```
199
200Internally 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.<br/>
201*Note that we have also added `modifyCoreObjects: false` because in some serverless environments such as Google Cloud Functions, some Node.js core properties are not writable.*
202
203<a name="factory-case-sensitive"></a>
204### `caseSensitive`
205
206By 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`.
207
208By setting `caseSensitive` to `false`, all paths will be matched as lowercase, but the route parameters or wildcards will maintain their original letter casing.
209
210```js
211fastify.get('/user/:username', (request, reply) => {
212 // Given the URL: /USER/NodeJS
213 console.log(request.params.username) // -> 'NodeJS'
214})
215```
216
217Please note this setting this option to `false` goes against
218[RFC3986](https://tools.ietf.org/html/rfc3986#section-6.2.2.1).
219
220<a name="factory-request-id-header"></a>
221### `requestIdHeader`
222
223The header name used to know the request id. See [the request id](https://github.com/fastify/fastify/blob/master/docs/Logging.md#logging-request-id) section.
224
225+ Default: `'request-id'`
226
227<a name="factory-request-id-log-label"></a>
228### `requestIdLogLabel`
229
230Defines the label used for the request identifier when logging the request.
231
232+ Default: `'reqId'`
233
234<a name="factory-gen-request-id"></a>
235### `genReqId`
236
237Function for generating the request id. It will receive the incoming request as a parameter.
238
239+ Default: `value of 'request-id' header if provided or monotonically increasing integers`
240
241Especially in distributed systems, you may want to override the default id generation behaviour as shown below. For generating `UUID`s you may want to checkout [hyperid](https://github.com/mcollina/hyperid)
242
243```js
244let i = 0
245const fastify = require('fastify')({
246 genReqId: function (req) { return i++ }
247})
248```
249
250**Note: genReqId will _not_ be called if the header set in <code>[requestIdHeader](#requestidheader)</code> is available (defaults to 'request-id').**
251
252<a name="factory-trust-proxy"></a>
253### `trustProxy`
254
255By enabling the `trustProxy` option, Fastify will have knowledge that it's sitting behind a proxy and that the `X-Forwarded-*` header fields may be trusted, which otherwise may be easily spoofed.
256
257```js
258const fastify = Fastify({ trustProxy: true })
259```
260
261+ Default: `false`
262+ `true/false`: Trust all proxies (`true`) or do not trust any proxies (`false`).
263+ `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'`).
264+ `Array<string>`: Trust only given IP/CIDR list (e.g. `['127.0.0.1']`).
265+ `number`: Trust the nth hop from the front-facing proxy server as the client.
266+ `Function`: Custom trust function that takes `address` as first arg
267 ```js
268 function myTrustFn(address, hop) {
269 return address === '1.2.3.4' || hop === 1
270 }
271 ```
272
273For more examples refer to [proxy-addr](https://www.npmjs.com/package/proxy-addr) package.
274
275You may access the `ip`, `ips`, and `hostname` values on the [`request`](https://github.com/fastify/fastify/blob/master/docs/Request.md) object.
276
277```js
278fastify.get('/', (request, reply) => {
279 console.log(request.ip)
280 console.log(request.ips)
281 console.log(request.hostname)
282})
283```
284
285<a name="plugin-timeout"></a>
286### `pluginTimeout`
287
288The maximum amount of time in *milliseconds* in which a plugin can load.
289If not, [`ready`](https://github.com/fastify/fastify/blob/master/docs/Server.md#ready)
290will complete with an `Error` with code `'ERR_AVVIO_PLUGIN_TIMEOUT'`.
291
292+ Default: `10000`
293
294<a name="factory-querystring-parser"></a>
295### `querystringParser`
296
297The default query string parser that Fastify uses is the Node.js's core `querystring` module.<br/>
298You can change this default setting by passing the option `querystringParser` and use a custom one, such as [`qs`](https://www.npmjs.com/package/qs).
299
300```js
301const qs = require('qs')
302const fastify = require('fastify')({
303 querystringParser: str => qs.parse(str)
304})
305```
306
307<a name="versioning"></a>
308### `versioning`
309
310By default you can version your routes with [semver versioning](https://github.com/fastify/fastify/blob/master/docs/Routes.md#version), which is provided by `find-my-way`. There is still an option to provide custom versioning strategy. You can find more information in the [find-my-way](https://github.com/delvedor/find-my-way#versioned-routes) documentation.
311
312```js
313const versioning = {
314 storage: function () {
315 let versions = {}
316 return {
317 get: (version) => { return versions[version] || null },
318 set: (version, store) => { versions[version] = store },
319 del: (version) => { delete versions[version] },
320 empty: () => { versions = {} }
321 }
322 },
323 deriveVersion: (req, ctx) => {
324 return req.headers['accept']
325 }
326}
327
328const fastify = require('fastify')({
329 versioning
330})
331```
332
333<a name="factory-modify-core-objects"></a>
334### `modifyCoreObjects`
335
336+ Default: `true`
337
338By default, Fastify will add the `ip`, `ips`, `hostname`, and `log` properties to Node's raw request object (see [`Request`](https://github.com/fastify/fastify/blob/master/docs/Request.md)) and the `log` property to Node's raw response object. Set to `false` to prevent these properties from being added to the Node core objects.
339
340```js
341const fastify = Fastify({ modifyCoreObjects: true }) // the default
342
343fastify.get('/', (request, reply) => {
344 console.log(request.raw.ip)
345 console.log(request.raw.ips)
346 console.log(request.raw.hostname)
347 request.raw.log('Hello')
348 reply.res.log('World')
349})
350```
351
352Disable this option could help in serverless environments such as Google Cloud Functions, where `ip` and `ips` are not writable properties.
353
354**Note that these properties are deprecated and will be removed in the next major version of Fastify along with this option.** It is recommended to use the same properties on Fastify's [`Request`](https://github.com/fastify/fastify/blob/master/docs/Request.md) and [`Reply`](https://github.com/fastify/fastify/blob/master/docs/Reply.md) objects instead.
355
356```js
357const fastify = Fastify({ modifyCoreObjects: false })
358
359fastify.get('/', (request, reply) => {
360 console.log(request.ip)
361 console.log(request.ips)
362 console.log(request.hostname)
363 request.log('Hello')
364 reply.log('World')
365})
366```
367
368<a name="factory-return-503-on-closing"></a>
369### `return503OnClosing`
370
371Returns 503 after calling `close` server method.
372If `false`, the server routes the incoming request as usual.
373
374+ Default: `true`
375
376<a name="factory-ajv"></a>
377### `ajv`
378
379Configure the ajv instance used by Fastify without providing a custom one.
380
381+ Default:
382
383```js
384{
385 customOptions: {
386 removeAdditional: true,
387 useDefaults: true,
388 coerceTypes: true,
389 allErrors: true,
390 nullable: true
391 },
392 plugins: []
393}
394```
395
396```js
397const fastify = require('fastify')({
398 ajv: {
399 customOptions: {
400 nullable: false // Refer to [ajv options](https://ajv.js.org/#options)
401 },
402 plugins: [
403 require('ajv-merge-patch')
404 [require('ajv-keywords'), 'instanceof'];
405 // Usage: [plugin, pluginOptions] - Plugin with options
406 // Usage: plugin - Plugin without options
407 ]
408 }
409})
410```
411
412<a name="http2-session-timeout"></a>
413### `http2SessionTimeout`
414
415Set a default
416[timeout](https://nodejs.org/api/http2.html#http2_http2session_settimeout_msecs_callback) to every incoming http2 session. The session will be closed on the timeout. Default: `5000` ms.
417
418Note that this is needed to offer the graceful "close" experience when
419using http2. Node core defaults this to `0`.
420
421<a name="framework-errors"></a>
422### `frameworkErrors`
423
424+ Default: `null`
425
426Fastify provides default error handlers for the most common use cases.
427Using this option it is possible to override one or more of those handlers with custom code.
428
429*Note: Only `FST_ERR_BAD_URL` is implemented at the moment.*
430
431```js
432const fastify = require('fastify')({
433 frameworkErrors: function (error, req, res) {
434 if (error instanceof FST_ERR_BAD_URL) {
435 res.code(400)
436 return res.send("Provided url is not valid")
437 } else {
438 res.send(err)
439 }
440 }
441})
442```
443
444
445## Instance
446
447### Server Methods
448
449<a name="server"></a>
450#### server
451`fastify.server`: The Node core [server](https://nodejs.org/api/http.html#http_class_http_server) object as returned by the [**`Fastify factory function`**](https://github.com/fastify/fastify/blob/master/docs/Server.md).
452
453<a name="after"></a>
454#### after
455Invoked when the current plugin and all the plugins
456that have been registered within it have finished loading.
457It is always executed before the method `fastify.ready`.
458
459```js
460fastify
461 .register((instance, opts, done) => {
462 console.log('Current plugin')
463 done()
464 })
465 .after(err => {
466 console.log('After current plugin')
467 })
468 .register((instance, opts, done) => {
469 console.log('Next plugin')
470 done()
471 })
472 .ready(err => {
473 console.log('Everything has been loaded')
474 })
475```
476
477<a name="ready"></a>
478#### ready
479Function called when all the plugins have been loaded.
480It takes an error parameter if something went wrong.
481```js
482fastify.ready(err => {
483 if (err) throw err
484})
485```
486If it is called without any arguments, it will return a `Promise`:
487
488```js
489fastify.ready().then(() => {
490 console.log('successfully booted!')
491}, (err) => {
492 console.log('an error happened', err)
493})
494```
495
496<a name="listen"></a>
497#### listen
498Starts the server on the given port after all the plugins are loaded, internally waits for the `.ready()` event. The callback is the same as the Node core. By default, the server will listen on the address resolved by `localhost` when no specific address is provided (`127.0.0.1` or `::1` depending on the operating system). If listening on any available interface is desired, then specifying `0.0.0.0` for the address will listen on all IPv4 address. Using `::` for the address will listen on all IPv6 addresses, and, depending on OS, may also listen on all IPv4 addresses. 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/).
499
500```js
501fastify.listen(3000, (err, address) => {
502 if (err) {
503 fastify.log.error(err)
504 process.exit(1)
505 }
506})
507```
508
509Specifying an address is also supported:
510
511```js
512fastify.listen(3000, '127.0.0.1', (err, address) => {
513 if (err) {
514 fastify.log.error(err)
515 process.exit(1)
516 }
517})
518```
519
520Specifying a backlog queue size is also supported:
521
522```js
523fastify.listen(3000, '127.0.0.1', 511, (err, address) => {
524 if (err) {
525 fastify.log.error(err)
526 process.exit(1)
527 }
528})
529```
530
531Specifying options is also supported, the object is same as [options](https://nodejs.org/api/net.html#net_server_listen_options_callback) in the Node.js server listen:
532
533```js
534fastify.listen({ port: 3000, host: '127.0.0.1', backlog: 511 }, (err) => {
535 if (err) {
536 fastify.log.error(err)
537 process.exit(1)
538 }
539})
540```
541
542If no callback is provided a Promise is returned:
543
544```js
545fastify.listen(3000)
546 .then((address) => console.log(`server listening on ${address}`))
547 .catch(err => {
548 console.log('Error starting server:', err)
549 process.exit(1)
550 })
551```
552
553Specifying an address without a callback is also supported:
554
555```js
556fastify.listen(3000, '127.0.0.1')
557 .then((address) => console.log(`server listening on ${address}`))
558 .catch(err => {
559 console.log('Error starting server:', err)
560 process.exit(1)
561 })
562```
563
564Specifying options without a callback is also supported:
565
566```js
567fastify.listen({ port: 3000, host: '127.0.0.1', backlog: 511 })
568 .then((address) => console.log(`server listening on ${address}`))
569 .catch(err => {
570 console.log('Error starting server:', err)
571 process.exit(1)
572 })
573```
574
575When 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`:
576
577```js
578fastify.listen(3000, '0.0.0.0', (err, address) => {
579 if (err) {
580 fastify.log.error(err)
581 process.exit(1)
582 }
583})
584```
585
586If the `port` is omitted (or is set to zero), a random available port is automatically chosen (later available via `fastify.server.address().port`).
587
588The default options of listen are:
589
590```js
591fastify.listen({
592 port: 0,
593 host: 'localhost',
594 exclusive: false,
595 readableAll: false,
596 writableAll: false,
597 ipv6Only: false
598}, (err) => {})
599```
600
601<a name="route"></a>
602#### route
603Method to add routes to the server, it also has shorthand functions, check [here](https://github.com/fastify/fastify/blob/master/docs/Routes.md).
604
605<a name="close"></a>
606#### close
607`fastify.close(callback)`: call this function to close the server instance and run the [`'onClose'`](https://github.com/fastify/fastify/blob/master/docs/Hooks.md#on-close) hook.<br>
608Calling `close` will also cause the server to respond to every new incoming request with a `503` error and destroy that request.
609See [`return503OnClosing` flags](https://github.com/fastify/fastify/blob/master/docs/Server.md#factory-return-503-on-closing) for changing this behaviour.
610
611If it is called without any arguments, it will return a Promise:
612
613```js
614fastify.close().then(() => {
615 console.log('successfully closed!')
616}, (err) => {
617 console.log('an error happened', err)
618})
619```
620
621<a name="decorate"></a>
622#### decorate*
623Function useful if you need to decorate the fastify instance, Reply or Request, check [here](https://github.com/fastify/fastify/blob/master/docs/Decorators.md).
624
625<a name="register"></a>
626#### register
627Fastify allows the user to extend its functionality with plugins.
628A plugin can be a set of routes, a server decorator or whatever, check [here](https://github.com/fastify/fastify/blob/master/docs/Plugins.md).
629
630<a name="use"></a>
631#### use
632Function to add middlewares to Fastify, check [here](https://github.com/fastify/fastify/blob/master/docs/Middleware.md).
633
634<a name="addHook"></a>
635#### addHook
636Function to add a specific hook in the lifecycle of Fastify, check [here](https://github.com/fastify/fastify/blob/master/docs/Hooks.md).
637
638<a name="prefix"></a>
639#### prefix
640The full path that will be prefixed to a route.
641
642Example:
643
644```js
645fastify.register(function (instance, opts, done) {
646 instance.get('/foo', function (request, reply) {
647 // Will log "prefix: /v1"
648 request.log.info('prefix: %s', instance.prefix)
649 reply.send({ prefix: instance.prefix })
650 })
651
652 instance.register(function (instance, opts, done) {
653 instance.get('/bar', function (request, reply) {
654 // Will log "prefix: /v1/v2"
655 request.log.info('prefix: %s', instance.prefix)
656 reply.send({ prefix: instance.prefix })
657 })
658
659 done()
660 }, { prefix: '/v2' })
661
662 done()
663}, { prefix: '/v1' })
664```
665
666<a name="pluginName"></a>
667#### pluginName
668Name of the current plugin. There are three ways to define a name (in order).
669
6701. If you use [fastify-plugin](https://github.com/fastify/fastify-plugin) the metadata `name` is used.
6712. If you `module.exports` a plugin the filename is used.
6723. If you use a regular [function declaration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Defining_functions) the function name is used.
673
674*Fallback*: The first two lines of your plugin will represent the plugin name. Newlines are replaced by ` -- `. This will help to indentify the root cause when you deal with many plugins.
675
676Important: If you have to deal with nested plugins the name differs with the usage of the [fastify-plugin](https://github.com/fastify/fastify-plugin) because no new scope is created and therefore we have no place to attach contextual data. In that case the plugin name will represent the boot order of all involved plugins in the format of `plugin-A -> plugin-B`.
677
678<a name="log"></a>
679#### log
680The logger instance, check [here](https://github.com/fastify/fastify/blob/master/docs/Logging.md).
681
682<a name="inject"></a>
683#### inject
684Fake http injection (for testing purposes) [here](https://github.com/fastify/fastify/blob/master/docs/Testing.md#inject).
685
686<a name="add-schema"></a>
687#### addSchema
688`fastify.addSchema(schemaObj)`, adds a shared schema to the Fastify instance. This allows you to reuse it everywhere in your application just by writing the schema id that you need.<br/>
689To learn more, see [shared schema example](https://github.com/fastify/fastify/blob/master/docs/Validation-and-Serialization.md#shared-schema) in the [Validation and Serialization](https://github.com/fastify/fastify/blob/master/docs/Validation-and-Serialization.md) documentation.
690
691<a name="set-reply-serializer"></a>
692#### setReplySerializer
693Set the reply serializer for all the routes. This will used as default if a [Reply.serializer(func)](https://github.com/fastify/fastify/blob/master/docs/Reply.md#serializerfunc) has not been set. The handler is fully encapsulated, so different plugins can set different error handlers.
694Note: the function parameter is called only for status `2xx`. Checkout the [`setErrorHandler`](https://github.com/fastify/fastify/blob/master/docs/Server.md#seterrorhandler) for errors.
695
696```js
697fastify.setReplySerializer(function (payload, statusCode){
698 // serialize the payload with a sync function
699 return `my serialized ${statusCode} content: ${payload}`
700})
701```
702
703<a name="set-schema-compiler"></a>
704#### setSchemaCompiler
705Set the schema compiler for all routes [here](https://github.com/fastify/fastify/blob/master/docs/Validation-and-Serialization.md#schema-compiler).
706
707<a name="set-schema-resolver"></a>
708#### setSchemaResolver
709Set the schema `$ref` resolver for all routes [here](https://github.com/fastify/fastify/blob/master/docs/Validation-and-Serialization.md#schema-resolver).
710
711
712<a name="schema-compiler"></a>
713#### schemaCompiler
714This property can be used to set the schema compiler, it is a shortcut for the `setSchemaCompiler` method, and get the schema compiler back for all routes.
715
716<a name="set-not-found-handler"></a>
717#### setNotFoundHandler
718
719`fastify.setNotFoundHandler(handler(request, reply))`: set the 404 handler. This call is encapsulated by prefix, so different plugins can set different not found handlers if a different [`prefix` option](https://github.com/fastify/fastify/blob/master/docs/Plugins.md#route-prefixing-option) is passed to `fastify.register()`. The handler is treated like a regular route handler so requests will go through the full [Fastify lifecycle](https://github.com/fastify/fastify/blob/master/docs/Lifecycle.md#lifecycle).
720
721You can also register a [`preValidation`](https://www.fastify.io/docs/latest/Hooks/#route-hooks) and [preHandler](https://www.fastify.io/docs/latest/Hooks/#route-hooks) hook for the 404 handler.
722
723_Note: The `preValidation` hook registered using this method will run for a route that Fastify does not recognize and **not** when a route handler manually calls [`reply.callNotFound`](https://github.com/fastify/fastify/blob/master/docs/Reply.md#call-not-found)_. In which case only preHandler will be run.
724
725```js
726fastify.setNotFoundHandler({
727 preValidation: (req, reply, done) => {
728 // your code
729 done()
730 },
731 preHandler: (req, reply, done) => {
732 // your code
733 done()
734 }
735}, function (request, reply) {
736 // Default not found handler with preValidation and preHandler hooks
737})
738
739fastify.register(function (instance, options, done) {
740 instance.setNotFoundHandler(function (request, reply) {
741 // Handle not found request without preValidation and preHandler hooks
742 // to URLs that begin with '/v1'
743 })
744 done()
745}, { prefix: '/v1' })
746```
747
748<a name="set-error-handler"></a>
749#### setErrorHandler
750
751`fastify.setErrorHandler(handler(error, request, reply))`: Set a function that will be called whenever an error happens. The handler is bound to the Fastify instance, and is fully encapsulated, so different plugins can set different error handlers. *async-await* is supported as well.<br>
752*Note: If the error `statusCode` is less than 400, Fastify will automatically set it at 500 before calling the error handler.*
753
754```js
755fastify.setErrorHandler(function (error, request, reply) {
756 // Log error
757 this.log.error(error)
758 // Send error response
759 reply.status(409).send({ ok: false })
760})
761```
762
763Fastify is provided with a default function that is called if no error handler is set and that logs the error with respect to its `statusCode`:
764
765```js
766var statusCode = error.statusCode
767if (statusCode >= 500) {
768 log.error(error)
769} else if (statusCode >= 400) {
770 log.info(error)
771} else {
772 log.error(error)
773}
774```
775
776<a name="print-routes"></a>
777#### printRoutes
778
779`fastify.printRoutes()`: Prints the representation of the internal radix tree used by the router, useful for debugging.<br/>
780*Remember to call it inside or after a `ready` call.*
781
782```js
783fastify.get('/test', () => {})
784fastify.get('/test/hello', () => {})
785fastify.get('/hello/world', () => {})
786
787fastify.ready(() => {
788 console.log(fastify.printRoutes())
789 // └── /
790 // ├── test (GET)
791 // │ └── /hello (GET)
792 // └── hello/world (GET)
793})
794```
795
796<a name="initial-config"></a>
797#### initialConfig
798
799`fastify.initialConfig`: Exposes a frozen read-only object registering the initial
800options passed down by the user to the fastify instance.
801
802Currently the properties that can be exposed are:
803- bodyLimit
804- caseSensitive
805- http2
806- https (it will return `false`/`true` or `{ allowHTTP1: true/false }` if explicitly passed)
807- ignoreTrailingSlash
808- maxParamLength
809- onProtoPoisoning
810- pluginTimeout
811- requestIdHeader
812
813```js
814const { readFileSync } = require('fs')
815const Fastify = require('fastify')
816
817const fastify = Fastify({
818 https: {
819 allowHTTP1: true,
820 key: readFileSync('./fastify.key'),
821 cert: readFileSync('./fastify.cert')
822 },
823 logger: { level: 'trace'},
824 ignoreTrailingSlash: true,
825 maxParamLength: 200,
826 caseSensitive: true,
827 trustProxy: '127.0.0.1,192.168.1.1/24',
828})
829
830console.log(fastify.initialConfig)
831/*
832will log :
833{
834 caseSensitive: true,
835 https: { allowHTTP1: true },
836 ignoreTrailingSlash: true,
837 maxParamLength: 200
838}
839*/
840
841fastify.register(async (instance, opts) => {
842 instance.get('/', async (request, reply) => {
843 return instance.initialConfig
844 /*
845 will return :
846 {
847 caseSensitive: true,
848 https: { allowHTTP1: true },
849 ignoreTrailingSlash: true,
850 maxParamLength: 200
851 }
852 */
853 })
854
855 instance.get('/error', async (request, reply) => {
856 // will throw an error because initialConfig is read-only
857 // and can not be modified
858 instance.initialConfig.https.allowHTTP1 = false
859
860 return instance.initialConfig
861 })
862})
863
864// Start listening.
865fastify.listen(3000, (err) => {
866 if (err) {
867 fastify.log.error(err)
868 process.exit(1)
869 }
870})
871```