diff --git a/docs/Reference/Server.md b/docs/Reference/Server.md index e41670cd55..e2ac4dd85c 100644 --- a/docs/Reference/Server.md +++ b/docs/Reference/Server.md @@ -98,6 +98,8 @@ describes the properties available in that options object. ### `http` ++ Default: `null` + An object used to configure the server's listening socket. The options are the same as the Node.js core [`createServer` method](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_http_createserver_options_requestlistener). @@ -105,20 +107,20 @@ method](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_http_create This option is ignored if options [`http2`](#factory-http2) or [`https`](#factory-https) are set. -+ Default: `null` - ### `http2` ++ Default: `false` + 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` ++ Default: `null` + 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). @@ -126,96 +128,100 @@ 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` ++ Default: `0` (no timeout) + 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. +the effect of this option. -+ Default: `0` (no timeout) +When `serverFactory` option is specified this option is ignored. ### `keepAliveTimeout` ++ Default: `72000` (72 seconds) + 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. +use. -+ Default: `72000` (72 seconds) +When `serverFactory` option is specified this option is ignored. ### `forceCloseConnections` ++ Default: `"idle"` if the HTTP server allows it, `false` otherwise + 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. +> **Warning** +> 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. +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 +and destroy their sockets. The value is only supported 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` -Defines the maximum number of requests socket can handle before closing keep -alive connection. See documentation for [`server.maxRequestsPerSocket` ++ Default: `0` (no limit) + +Defines the maximum number of requests a socket can handle before closing keep +alive connection. See [`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) +> **Note** +> At the time of writing, only node >= v16.10.0 supports this option. ### `requestTimeout` ++ Default: `0` (no limit) + Defines the maximum number of milliseconds for receiving the entire request from -the client. [`server.requestTimeout` +the client. See [`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. +to understand the effect of this option. -+ Default: `0` (no limit) +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. + +> **Note** +> At the time of writing, only node >= v14.11.0 supports this option ### `ignoreTrailingSlash` ++ Default: `false` + 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 +routing. By default, Fastify will take into account the trailing slashes. +Paths like `/foo` and `/foo/` are 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 @@ -235,17 +241,17 @@ fastify.get('/bar', function (req, reply) { ### `ignoreDuplicateSlashes` ++ Default: `false` + 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 +from the path. It removes duplicate slashes in the route path and 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` +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`. ```js const fastify = require('fastify')({ @@ -263,46 +269,45 @@ fastify.get('///foo//bar//', function (req, reply) { 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. +characters. If the maximum length limit is reached, the not found route will +be invoked. This can be useful especially if you have a regex-based route, protecting you -against [DoS +against [ReDoS 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` -Defines the maximum payload, in bytes, the server is allowed to accept. - + Default: `1048576` (1MiB) +Defines the maximum payload, in bytes, the server is allowed to accept. + ### `onProtoPoisoning` ++ Default: `'error'` + 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'` +Possible values are `'error'`, `'remove'`, or `'ignore'`. ### `onConstructorPoisoning` ++ Default: `'error'` + 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'` +Possible values are `'error'`, `'remove'`, or `'ignore'`. ### `logger` @@ -363,13 +368,18 @@ The possible values this property may have are: ### `disableRequestLogging` -By default, when logging is enabled, Fastify will issue an `info` level log ++ Default: `false` + +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` +Please note that this option will also disable an error log written by the +default `onResponse` hook on reply callback errors. Other log messages +emitted by Fastify will stay enabled, like deprecation warnings and messages +emitted when requests are received while the server is closing. ```js // Examples of hooks to replicate the disabled functionality. @@ -384,11 +394,6 @@ fastify.addHook('onResponse', (req, reply, done) => { }) ``` -Please note that this setting will also disable an error log written by the -default `onResponse` hook on reply callback errors. Other log messages -emitted by Fastify will stay enabled, like deprecation warnings and messages -emitted when requests are received while the server is closing. - ### `serverFactory` @@ -428,13 +433,17 @@ enhance the server instance inside the `serverFactory` function before the + Default: `true` -Internally, and by default, Fastify will automatically infer the root properties +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 +Schema spec. If you wish to implement your own schema validation compiler, to +parse schemas as JTD instead of JSON Schema for example, 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. +Fastify does not throw on invalid schemas so if this option is set to `false` +in an existing project, check that none of your existing schemas become +invalid as a result, as they will be treated as catch-alls. + ```js const AjvJTD = require('ajv/dist/jtd'/* only valid for AJV v7+ */) const ajv = new AjvJTD({ @@ -457,21 +466,23 @@ fastify.post('/', { }) ``` -**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` -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`. ++ Default: `true` + +When `true` routes are registered as case-sensitive. That is, `/foo` +is not equal to `/Foo`. +When `false` then routes are case-insensitive. + +Please note that setting this option to `false` goes against +[RFC3986](https://tools.ietf.org/html/rfc3986#section-6.2.2.1). By setting `caseSensitive` to `false`, all paths will be matched as lowercase, but the route parameters or wildcards will maintain their original letter -casing. +casing. +This option does not affect query strings, please refer to +[`querystringParser`](#querystringparser) to change their handling. ```js fastify.get('/user/:username', (request, reply) => { @@ -480,19 +491,13 @@ fastify.get('/user/:username', (request, reply) => { }) ``` -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` -The allowUnsafeRegex setting is false by default, so routes only allow safe -regular expressions. To use unsafe expressions, set allowUnsafeRegex to true. ++ Default `false` + +Disabled 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) => { @@ -500,18 +505,14 @@ fastify.get('/user/:id(^([0-9]+){4}$)', (request, reply) => { }) ``` -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` ++ Default: `'request-id'` + 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'` +Setting `requestIdHeader` to `false` will always use [genReqId](#genreqid). ```js const fastify = require('fastify')({ @@ -519,25 +520,31 @@ const fastify = require('fastify')({ //requestIdHeader: false, // -> always use genReqId }) ``` + ### `requestIdLogLabel` -Defines the label used for the request identifier when logging the request. - + Default: `'reqId'` +Defines the label used for the request identifier when logging the request. + ### `genReqId` -Function for generating the request-id. It will receive the _raw_ 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` +Function for generating the request-id. It will receive the _raw_ incoming +request as a parameter. This function is expected to be error-free. + 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) +out [hyperid](https://github.com/mcollina/hyperid). + +> **Note** +> `genReqId` will be not called if the header set in +> [requestIdHeader](#requestidheader) is available (defaults to +> 'request-id'). ```js let i = 0 @@ -546,21 +553,9 @@ const fastify = require('fastify')({ }) ``` -**Note: genReqId will _not_ be called if the header set in -[requestIdHeader](#requestidheader) is available (defaults to -'request-id').** - ### `trustProxy` -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`). @@ -575,6 +570,14 @@ const fastify = Fastify({ trustProxy: true }) } ``` +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 }) +``` + For more examples, refer to the [`proxy-addr`](https://www.npmjs.com/package/proxy-addr) package. @@ -590,28 +593,32 @@ fastify.get('/', (request, reply) => { }) ``` -**Note: if a request contains multiple x-forwarded-host or -x-forwarded-proto headers, it is only the last one that is used to -derive request.hostname and request.protocol** +> **Note** +> If a request contains multiple `x-forwarded-host` or `x-forwarded-proto` +> headers, it is only the last one that is used to derive `request.hostname` +> and `request.protocol`. ### `pluginTimeout` ++ Default: `10000` + 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` 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). +You can use this option to use a custom parser, such as +[`qs`](https://www.npmjs.com/package/qs). + +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. ```js const qs = require('qs') @@ -620,7 +627,7 @@ const fastify = require('fastify')({ }) ``` -You can also use Fastify's default parser but change some handling behaviour, +You can also use Fastify's default parser but change some handling behavior, like the example below for case insensitive keys and values: ```js @@ -630,24 +637,21 @@ const fastify = require('fastify')({ }) ``` -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` ++ Default: `true` + 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` -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` +Fastify's built-in route constraints are provided by `find-my-way`, which +allows constraining routes by `version` or `host`. You can 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. @@ -676,11 +680,11 @@ const fastify = require('fastify')({ ### `return503OnClosing` ++ Default: `true` + Returns 503 after calling `close` server method. If `false`, the server routes the incoming request as usual. -+ Default: `true` - ### `ajv` @@ -709,7 +713,7 @@ const fastify = require('fastify')({ Customize the options of the default [`fast-json-stringify`](https://github.com/fastify/fast-json-stringify#options) -instance that serialize the response's payload: +instance that serializes the response's payload: ```js const fastify = require('fastify')({ @@ -722,15 +726,17 @@ const fastify = require('fastify')({ ### `http2SessionTimeout` ++ Default: `72000` + 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. +[timeout](https://nodejs.org/api/http2.html#http2sessionsettimeoutmsecs-callback) +to every incoming HTTP/2 session in milliseconds. The session will be closed on +the timeout. -Note that this is needed to offer the graceful "close" experience when using +This option is needed to offer a 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`. ` +can be increased to fit the use case. Node core defaults this to `0`. ### `frameworkErrors` @@ -741,8 +747,8 @@ 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` and `FST_ERR_ASYNC_CONSTRAINT` are implemented at -the moment.* +> **Note** +> Only `FST_ERR_BAD_URL` and `FST_ERR_ASYNC_CONSTRAINT` are implemented at present. ```js const fastify = require('fastify')({ @@ -794,10 +800,11 @@ function defaultClientErrorHandler (err, socket) { } ``` -*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.* +> **Note** +> `clientErrorHandler` operates with raw sockets. 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')({ @@ -826,9 +833,11 @@ const fastify = require('fastify')({ Set a sync callback function that must return a string that allows rewriting -URLs. +URLs. This is useful when you are behind a proxy that changes the URL. +Rewriting a URL will modify the `url` property of the `req` object. -> Rewriting a URL will modify the `url` property of the `req` object +Note that `rewriteUrl` is called _before_ routing, it is not encapsulated and it +is an instance-wide configuration. ```js // @param {object} req The raw Node.js HTTP request, not the `FastifyRequest` object. @@ -844,9 +853,6 @@ function rewriteUrl (req) { } ``` -Note that `rewriteUrl` is called _before_ routing, it is not encapsulated and it -is an instance-wide configuration. - ## Instance ### Server Methods @@ -858,8 +864,9 @@ is an instance-wide configuration. [server](https://nodejs.org/api/http.html#http_class_http_server) object as returned by the [**`Fastify factory function`**](#factory). ->__Warning__: If utilized improperly, certain Fastify features could be disrupted. ->It is recommended to only use it for attaching listeners. +> **Warning** +> If utilized improperly, certain Fastify features could be disrupted. +> It is recommended to only use it for attaching listeners. #### after @@ -1057,8 +1064,9 @@ Note that the array contains the `fastify.server.address()` too. #### getDefaultRoute -**Notice**: this method is deprecated and should be removed in the next Fastify -major version. +> **Warning** +> This method is deprecated and will be removed in the next Fastify +> major version. The `defaultRoute` handler handles requests that do not match any URL specified by your Fastify application. This defaults to the 404 handler, but can be @@ -1072,9 +1080,10 @@ const defaultRoute = fastify.getDefaultRoute() #### setDefaultRoute -**Notice**: this method is deprecated and should be removed in the next Fastify -major version. Please, consider to use `setNotFoundHandler` or a wildcard -matching route. +> **Warning** +> This method is deprecated and will be removed in the next Fastify +> major version. Please, consider using `setNotFoundHandler` or a wildcard +> matching route. The default 404 handler, or one set using `setNotFoundHandler`, will never trigger if the default route is overridden. This sets the handler for the @@ -1117,9 +1126,9 @@ Method to add routes to the server, it also has shorthand functions, check Method to check if a route is already registered to the internal router. It -expects an object as payload. `url` and `method` are mandatory fields. It is -possible to also specify `constraints`. The method returns true if the route is -registered, and false if it is not registered. +expects an object as the payload. `url` and `method` are mandatory fields. It +is possible to also specify `constraints`. The method returns `true` if the +route is registered or `false` if not. ```js const routeExists = fastify.hasRoute({ @@ -1220,11 +1229,12 @@ different ways to define a name (in order). Newlines are replaced by ` -- `. This will help to identify the root cause when you deal with many plugins. -Important: 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 `fastify -> plugin-A -> plugin-B`. +> **Warning** +> 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 `fastify -> plugin-A -> plugin-B`. #### hasPlugin @@ -1327,7 +1337,9 @@ Set the schema error formatter for all routes. See Set the schema serializer compiler for all routes. See [#schema-serializer](./Validation-and-Serialization.md#schema-serializer). -**Note:** [`setReplySerializer`](#set-reply-serializer) has priority if set! + +> **Note** +> [`setReplySerializer`](#set-reply-serializer) has priority if set! #### validatorCompiler @@ -1362,9 +1374,7 @@ This property can be used to fully manage: - `compilersFactory`: what module must compile the JSON schemas It can be useful when your schemas are stored in another data structure that is -unknown to Fastify. See [issue -#2446](https://github.com/fastify/fastify/issues/2446) for an example of what -this property helps to resolve. +unknown to Fastify. Another use case is to tweak all the schemas processing. Doing so it is possible to use Ajv v8 JTD or Standalone feature. To use such as JTD or the Standalone @@ -1404,7 +1414,7 @@ const fastify = Fastify({ }, /** - * The compilers factory let you fully control the validator and serializer + * The compilers factory lets you fully control the validator and serializer * in the Fastify's lifecycle, providing the encapsulation to your compilers. */ compilersFactory: { @@ -1461,10 +1471,12 @@ lifecycle](./Lifecycle.md#lifecycle). *async-await* is supported as well. You can also register [`preValidation`](./Hooks.md#route-hooks) and [`preHandler`](./Hooks.md#route-hooks) hooks for the 404 handler. -_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`](./Reply.md#call-not-found)_. In which case, only -preHandler will be run. +> **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`](./Reply.md#call-not-found). In which case, only +> preHandler will be run. + ```js fastify.setNotFoundHandler({ @@ -1495,8 +1507,9 @@ plugins are registered. If you would like to augment the behavior of the default arguments `fastify.setNotFoundHandler()` within the context of these registered plugins. -> Note: Some config properties from the request object will be -> undefined inside the custom not found handler. E.g: +> **Note** +> Some config properties from the request object will be +> undefined inside the custom not found handler. E.g.: > `request.routerPath`, `routerMethod` and `context.config`. > This method design goal is to allow calling the common not found route. > To return a per-route customized 404 response, you can do it in @@ -1510,11 +1523,12 @@ 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. -*Note: If the error `statusCode` is less than 400, Fastify will automatically -set it at 500 before calling the error handler.* +If the error `statusCode` is less than 400, Fastify will automatically +set it to 500 before calling the error handler. -*Also note* that `setErrorHandler` will ***not*** catch any error inside -an `onResponse` hook because the response has already been sent to the client. +> **Note** +> `setErrorHandler` will ***not*** catch any error inside +> an `onResponse` hook because the response has already been sent to the client. ```js fastify.setErrorHandler(function (error, request, reply) { @@ -1545,10 +1559,10 @@ if (statusCode >= 500) { `fastify.setChildLoggerFactory(factory(logger, bindings, opts, rawReq))`: Set a function that will be called when creating a child logger instance for each request which allows for modifying or adding child logger bindings and logger options, or -returning a completely custom child logger implementation. +returning a custom child logger implementation. -Child logger bindings have a performance advantage over per-log bindings, because -they are pre-serialised by Pino when the child logger is created. +Child logger bindings have a performance advantage over per-log bindings because +they are pre-serialized by Pino when the child logger is created. The first parameter is the parent logger instance, followed by the default bindings and logger options which should be passed to the child logger, and finally @@ -1616,7 +1630,7 @@ a custom constraint strategy with the same name. `fastify.printRoutes()`: Fastify router builds a tree of routes for each HTTP method. If you call the prettyPrint without specifying an HTTP method, it will merge all the trees into one and print it. The merged tree doesn't represent the -internal router structure. **Don't use it for debugging.** +internal router structure. **Do not use it for debugging.** *Remember to call it inside or after a `ready` call.* @@ -1658,8 +1672,8 @@ param. Printed tree will represent the internal router structure. ``` `fastify.printRoutes({ commonPrefix: false })` will print compressed trees. This -might useful when you have a large number of routes with common prefixes. -It doesn't represent the internal router structure. **Don't use it for debugging.** +may be useful when you have a large number of routes with common prefixes. +It doesn't represent the internal router structure. **Do not use it for debugging.** ```js console.log(fastify.printRoutes({ commonPrefix: false })) @@ -1752,7 +1766,7 @@ fastify.ready(() => { `fastify.addContentTypeParser(content-type, options, parser)` is used to pass -custom parser for a given content type. Useful for adding parsers for custom +a custom parser for a given content type. Useful for adding parsers for custom content types, e.g. `text/json, application/vnd.oasis.opendocument.text`. `content-type` can be a string, string array or RegExp. @@ -1854,7 +1868,7 @@ for more info. `fastify.initialConfig`: Exposes a frozen read-only object registering the initial options passed down by the user to the Fastify instance. -Currently the properties that can be exposed are: +The properties that can currently be exposed are: - connectionTimeout - keepAliveTimeout - bodyLimit