fastify 5.9.0 → 5.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/PROJECT_CHARTER.md +1 -1
  2. package/README.md +7 -10
  3. package/build/build-validation.js +2 -2
  4. package/docs/Guides/Delay-Accepting-Requests.md +1 -1
  5. package/docs/Guides/Ecosystem.md +10 -7
  6. package/docs/Guides/Getting-Started.md +2 -2
  7. package/docs/Guides/Migration-Guide-V4.md +2 -2
  8. package/docs/Guides/Migration-Guide-V5.md +1 -1
  9. package/docs/Guides/Plugins-Guide.md +1 -1
  10. package/docs/Guides/Prototype-Poisoning.md +3 -3
  11. package/docs/Guides/Serverless.md +6 -13
  12. package/docs/Guides/Style-Guide.md +1 -1
  13. package/docs/Reference/Errors.md +2 -0
  14. package/docs/Reference/Hooks.md +1 -1
  15. package/docs/Reference/Logging.md +3 -0
  16. package/docs/Reference/Request.md +2 -2
  17. package/docs/Reference/Server.md +107 -8
  18. package/docs/Reference/Type-Providers.md +24 -4
  19. package/docs/Reference/TypeScript.md +3 -3
  20. package/docs/Reference/Warnings.md +4 -0
  21. package/fastify.d.ts +5 -0
  22. package/fastify.js +22 -22
  23. package/lib/content-type-parser.js +1 -11
  24. package/lib/content-type.js +34 -1
  25. package/lib/context.js +0 -3
  26. package/lib/error-handler.js +7 -26
  27. package/lib/errors.js +7 -0
  28. package/lib/four-oh-four.js +8 -10
  29. package/lib/handle-request.js +2 -1
  30. package/lib/log-controller.js +169 -0
  31. package/lib/logger-factory.js +25 -4
  32. package/lib/reply.js +35 -44
  33. package/lib/req-id-gen-factory.js +4 -1
  34. package/lib/request.js +3 -3
  35. package/lib/route.js +27 -35
  36. package/lib/symbols.js +1 -1
  37. package/lib/validation.js +9 -0
  38. package/lib/warnings.js +19 -1
  39. package/package.json +3 -3
  40. package/test/content-type.test.js +20 -0
  41. package/test/genReqId.test.js +24 -0
  42. package/test/hooks.test.js +71 -0
  43. package/test/internals/errors.test.js +1 -1
  44. package/test/internals/logger.test.js +322 -0
  45. package/test/internals/reply.test.js +35 -4
  46. package/test/internals/request.test.js +10 -7
  47. package/test/logger/logging.test.js +40 -1
  48. package/test/stream.4.test.js +2 -2
  49. package/test/trust-proxy.test.js +49 -30
  50. package/types/errors.d.ts +1 -0
  51. package/types/instance.d.ts +2 -0
  52. package/types/logger.d.ts +22 -0
@@ -50,7 +50,7 @@ experience with the least overhead and a plugin architecture.
50
50
 
51
51
  Technical leadership for the projects within the [OpenJS Foundation][openjs
52
52
  foundation] is delegated to the projects through their project charters by the
53
- [OpenJS Foundation Cross-Project Council](https://openjsf.org/about/governance/)
53
+ [OpenJS Foundation Cross-Project Council](https://openjsf.org/governance)
54
54
  (CPC). In the case of the Fastify project, it is delegated to the [Fastify
55
55
  Collaborators](README.md#team). The OpenJS Foundation's business leadership is
56
56
  the Board of Directors (the "Board").
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  <div align="center"> <a href="https://fastify.dev/">
2
2
  <img
3
- src="https://github.com/fastify/graphics/raw/HEAD/fastify-landscape-outlined.svg"
3
+ src="https://raw.githubusercontent.com/fastify/graphics/HEAD/fastify-landscape-outlined.svg"
4
4
  width="650"
5
5
  height="auto"
6
6
  />
@@ -15,7 +15,7 @@ CI](https://github.com/fastify/fastify/actions/workflows/package-manager-ci.yml/
15
15
  [![Web
16
16
  site](https://github.com/fastify/fastify/actions/workflows/website.yml/badge.svg?branch=main)](https://github.com/fastify/fastify/actions/workflows/website.yml)
17
17
  [![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)
18
- [![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/7585/badge)](https://bestpractices.coreinfrastructure.org/projects/7585)
18
+ [![CII Best Practices](https://www.bestpractices.dev/projects/7585/badge)](https://www.bestpractices.dev/en/projects/7585/passing)
19
19
 
20
20
  </div>
21
21
 
@@ -27,7 +27,7 @@ version](https://img.shields.io/npm/v/fastify.svg?style=flat)](https://www.npmjs
27
27
  downloads](https://img.shields.io/npm/dm/fastify.svg?style=flat)](https://www.npmjs.com/package/fastify)
28
28
  [![Security Responsible
29
29
  Disclosure](https://img.shields.io/badge/Security-Responsible%20Disclosure-yellow.svg)](https://github.com/fastify/fastify/blob/main/SECURITY.md)
30
- [![Discord](https://img.shields.io/discord/725613461949906985)](https://discord.gg/fastify)
30
+ [![Discord](https://img.shields.io/discord/725613461949906985)](https://discord.com/invite/fastify)
31
31
  [![Contribute with Gitpod](https://img.shields.io/badge/Contribute%20with-Gitpod-908a85?logo=gitpod&color=blue)](https://gitpod.io/#https://github.com/fastify/fastify)
32
32
  [![Open Collective backers and sponsors](https://img.shields.io/opencollective/all/fastify)](https://github.com/sponsors/fastify#sponsors)
33
33
 
@@ -253,8 +253,8 @@ application. You should __always__ benchmark if performance matters to you.
253
253
  plugins.
254
254
  - [Live Examples](https://github.com/fastify/example) - Multirepo with a broad
255
255
  set of real working examples.
256
- - [Discord](https://discord.gg/D3FZYPy) - Join our discord server and chat with
257
- the maintainers.
256
+ - [Discord](https://discord.com/invite/D3FZYPy) - Join our discord server and
257
+ chat with the maintainers.
258
258
 
259
259
  ## Support
260
260
  Please visit [Fastify help](https://github.com/fastify/help) to view prior
@@ -312,7 +312,7 @@ listed in alphabetical order.
312
312
  * [__KaKa Ng__](https://github.com/climba03003),
313
313
  <https://www.npmjs.com/~climba03003>
314
314
  * [__Luis Orbaiceta__](https://github.com/luisorbaiceta),
315
- <https://x.com/luisorbai>, <https://www.npmjs.com/~luisorbaiceta>
315
+ <https://www.npmjs.com/~luisorbaiceta>
316
316
  * [__Maksim Sinik__](https://github.com/fox1t),
317
317
  <https://x.com/maksimsinik>, <https://www.npmjs.com/~fox1t>
318
318
  * [__Manuel Spigolon__](https://github.com/eomm),
@@ -383,7 +383,7 @@ active contributor's group.
383
383
  ## Hosted by
384
384
 
385
385
  [<img
386
- src="https://github.com/openjs-foundation/artwork/blob/main/openjs_foundation/openjs_foundation-logo-horizontal-color.png?raw=true"
386
+ src="https://raw.githubusercontent.com/openjs-foundation/artwork/main/openjs_foundation/openjs_foundation-logo-horizontal-color.png"
387
387
  width="250px;"/>](https://openjsf.org/projects)
388
388
 
389
389
  We are an [At-Large
@@ -402,9 +402,6 @@ This project is kindly sponsored by:
402
402
  - [NearForm](https://nearform.com)
403
403
  - [Platformatic](https://platformatic.dev)
404
404
 
405
- Past Sponsors:
406
- - [LetzDoIt](https://www.letzdoitapp.com/)
407
-
408
405
  This list includes all companies that support one or more team members
409
406
  in maintaining this project.
410
407
 
@@ -32,7 +32,7 @@ const defaultInitOptions = {
32
32
  bodyLimit: 1024 * 1024, // 1 MiB
33
33
  caseSensitive: true,
34
34
  allowUnsafeRegex: false,
35
- disableRequestLogging: false,
35
+ disableRequestLogging: false, // TODO: remove it in v6
36
36
  ignoreTrailingSlash: false,
37
37
  ignoreDuplicateSlashes: false,
38
38
  maxParamLength: 100,
@@ -40,7 +40,7 @@ const defaultInitOptions = {
40
40
  onConstructorPoisoning: 'error',
41
41
  pluginTimeout: 10000,
42
42
  requestIdHeader: false,
43
- requestIdLogLabel: 'reqId',
43
+ requestIdLogLabel: 'reqId', // TODO: remove it in v6
44
44
  http2SessionTimeout: 72000, // 72 seconds
45
45
  exposeHeadRoutes: true,
46
46
  useSemicolonDelimiter: false,
@@ -447,7 +447,7 @@ served until we have everything ready. And there's more: we fail **FAST** and
447
447
  have the possibility of giving the customer meaningful information, like how
448
448
  long they should wait before retrying the request. Going even further, by
449
449
  issuing a [`503` status
450
- code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503) we're
450
+ code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/503) we're
451
451
  signaling to our infrastructure components (namely load balancers) that we're
452
452
  still not ready to take incoming requests and they should redirect traffic to
453
453
  other instances, if available. Additionally, we are providing a `Retry-After`
@@ -144,7 +144,7 @@ section.
144
144
  - [`@fastify/view`](https://github.com/fastify/point-of-view) Templates
145
145
  rendering (_ejs, pug, handlebars, marko_) plugin support for Fastify.
146
146
  - [`@fastify/vite`](https://github.com/fastify/fastify-vite) Integration with
147
- [Vite](https://vitejs.dev/), allows for serving SPA/MPA/SSR Vite applications.
147
+ [Vite](https://vite.dev/), allows for serving SPA/MPA/SSR Vite applications.
148
148
  - [`@fastify/websocket`](https://github.com/fastify/fastify-websocket) WebSocket
149
149
  support for Fastify. Built upon [ws](https://github.com/websockets/ws).
150
150
  - [`@fastify/zipkin`](https://github.com/fastify/fastify-zipkin) Plugin
@@ -196,7 +196,7 @@ section.
196
196
  Run REST APIs and other web applications using your existing Node.js
197
197
  application framework (Express, Koa, Hapi and Fastify), on top of AWS Lambda,
198
198
  Huawei and many other clouds.
199
- - [`@hey-api/openapi-ts`](https://heyapi.dev/openapi-ts/plugins/fastify)
199
+ - [`@hey-api/openapi-ts`](https://heyapi.dev/docs/openapi/typescript/plugins/fastify)
200
200
  The OpenAPI to TypeScript codegen. Generate clients, SDKs, validators, and more.
201
201
  - [`@immobiliarelabs/fastify-metrics`](https://github.com/immobiliare/fastify-metrics)
202
202
  Minimalistic and opinionated plugin that collects usage/process metrics and
@@ -232,6 +232,9 @@ section.
232
232
  Plugin to generate routes automatically with valid json content
233
233
  - [`@scalar/fastify-api-reference`](https://github.com/scalar/scalar/tree/main/integrations/fastify)
234
234
  Beautiful OpenAPI/Swagger API references for Fastify
235
+ - [`@stitchapi/fastify`](https://github.com/rejifald/StitchAPI/tree/main/packages/fastify)
236
+ Decorate the app/request with a StitchAPI seam — request-scoped principal, SSE
237
+ streaming, error mapping, and a Pino-logger bridge.
235
238
  - [`@thecodepace/fastify-http-query`](https://github.com/TheCodePace/fastify-http-query)
236
239
  Fastify plugin enabling the HTTP `QUERY` method (a safe, idempotent, cacheable
237
240
  method with a body).
@@ -289,8 +292,8 @@ section.
289
292
  validator, keeping Fastify's default error shape.
290
293
  - [`fastify-auth0-verify`](https://github.com/nearform/fastify-auth0-verify):
291
294
  Auth0 verification plugin for Fastify, internally uses
292
- [fastify-jwt](https://npm.im/fastify-jwt) and
293
- [jsonwebtoken](https://npm.im/jsonwebtoken).
295
+ [fastify-jwt](https://www.npmjs.com/package/fastify-jwt) and
296
+ [jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken).
294
297
  - [`fastify-autoroutes`](https://github.com/GiovanniCardamone/fastify-autoroutes)
295
298
  Plugin to scan and load routes based on filesystem path from a custom
296
299
  directory.
@@ -390,7 +393,7 @@ section.
390
393
  - [`fastify-formidable`](https://github.com/climba03003/fastify-formidable)
391
394
  Handy plugin to provide multipart support and fastify-swagger integration.
392
395
  - [`fastify-gcloud-trace`](https://github.com/mkinoshi/fastify-gcloud-trace)
393
- [Google Cloud Trace API](https://cloud.google.com/trace/docs/reference)
396
+ [Google Cloud Trace API](https://docs.cloud.google.com/trace/docs/reference)
394
397
  Connector for Fastify.
395
398
  - [`fastify-get-head`](https://github.com/MetCoder95/fastify-get-head) Small
396
399
  plugin to set a new HEAD route handler for each GET route previously
@@ -561,7 +564,7 @@ middlewares into Fastify plugins
561
564
  to handle i18n using
562
565
  [node-polyglot](https://www.npmjs.com/package/node-polyglot).
563
566
  - [`fastify-postgraphile`](https://github.com/alemagio/fastify-postgraphile)
564
- Plugin to integrate [PostGraphile](https://www.graphile.org/postgraphile/) in
567
+ Plugin to integrate [PostGraphile](https://postgraphile.org/postgraphile/4/) in
565
568
  a Fastify project.
566
569
  - [`fastify-postgres-dot-js`](https://github.com/kylerush/fastify-postgresjs) Fastify
567
570
  PostgreSQL connection plugin that uses [Postgres.js](https://github.com/porsager/postgres).
@@ -679,7 +682,7 @@ middlewares into Fastify plugins
679
682
  multiple subdomains to the same IP address, while running different servers on
680
683
  the same machine).
681
684
  - [`fastify-vue-plugin`](https://github.com/TheNoim/fastify-vue)
682
- [Nuxt.js](https://nuxtjs.org) plugin for Fastify. Control the routes nuxt
685
+ [Nuxt.js](https://nuxt.com) plugin for Fastify. Control the routes nuxt
683
686
  should use.
684
687
  - [`fastify-wamp-router`](https://github.com/lependu/fastify-wamp-router) Web
685
688
  Application Messaging Protocol router for Fastify.
@@ -605,10 +605,10 @@ npm start
605
605
 
606
606
  - Slides
607
607
  - [Take your HTTP server to ludicrous
608
- speed](https://mcollina.github.io/take-your-http-server-to-ludicrous-speed)
608
+ speed](https://mcollina.github.io/take-your-http-server-to-ludicrous-speed/)
609
609
  by [@mcollina](https://github.com/mcollina)
610
610
  - [What if I told you that HTTP can be
611
- fast](https://delvedor.github.io/What-if-I-told-you-that-HTTP-can-be-fast)
611
+ fast](https://delvedor.dev/What-if-I-told-you-that-HTTP-can-be-fast/)
612
612
  by [@delvedor](https://github.com/delvedor)
613
613
 
614
614
  - Videos
@@ -10,7 +10,7 @@ work after upgrading.
10
10
  ### Fastify v4 Codemods
11
11
 
12
12
  To help with the upgrade, we’ve worked with the team at
13
- [Codemod](https://github.com/codemod-com/codemod) to
13
+ [Codemod](https://github.com/codemod/codemod) to
14
14
  publish codemods that will automatically update your code to many of
15
15
  the new APIs and patterns in Fastify v4.
16
16
 
@@ -264,4 +264,4 @@ Into:
264
264
  Fastify now supports the [HTTP Trailer] response headers.
265
265
 
266
266
 
267
- [HTTP Trailer]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Trailer
267
+ [HTTP Trailer]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Trailer
@@ -105,7 +105,7 @@ const fastify = require('fastify')({
105
105
  Starting with v5, Fastify instances will no longer default to supporting the use
106
106
  of semicolon delimiters in the query string as they did in v4.
107
107
  This is due to it being non-standard
108
- behavior and not adhering to [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.4).
108
+ behavior and not adhering to [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986#section-3.4).
109
109
 
110
110
  If you still wish to use semicolons as delimiters, you can do so by
111
111
  setting `useSemicolonDelimiter: true` in the server configuration.
@@ -507,7 +507,7 @@ section of our documentation!
507
507
 
508
508
  If you want to see some real-world examples, check out:
509
509
  - [`@fastify/view`](https://github.com/fastify/point-of-view) Templates
510
- rendering (*ejs, pug, handlebars, marko*) plugin support for Fastify.
510
+ rendering (*ejs, pug, handlebars*) plugin support for Fastify.
511
511
  - [`@fastify/mongodb`](https://github.com/fastify/fastify-mongodb) Fastify
512
512
  MongoDB connection plugin, with this you can share the same MongoDB connection
513
513
  pool in every part of your server.
@@ -232,7 +232,7 @@ itself), it is much harder getting it fixed.
232
232
 
233
233
  The first question people ask once a security issue is found is if there is
234
234
  going to be a CVE published. A CVE — Common Vulnerabilities and Exposures — is a
235
- [database](https://cve.mitre.org/) of known security issues. It is a critical
235
+ [database](https://www.cve.org/) of known security issues. It is a critical
236
236
  component of web security. The benefit of publishing a CVE is that it
237
237
  immediately triggers alarms and informs and often breaks automated builds until
238
238
  the issue is resolved.
@@ -376,8 +376,8 @@ source maintainers.
376
376
  Because this work is important, I decided to try and make it not just
377
377
  financially sustainable but to grow and expand it. There is so much to improve.
378
378
  This is exactly what motivates me to implement the new [commercial licensing
379
- plan](https://web.archive.org/web/20190201220503/https://hueniverse.com/on-hapi-licensing-a-preview-f982662ee898)
379
+ plan](https://web.archive.org/web/20190201220503/https://hueniverse.com/on-hapi-licensing-a-preview-f982662ee898?gi=b54e9a75bac6)
380
380
  coming in March. You can read more about it
381
- [here](https://web.archive.org/web/20190201220503/https://hueniverse.com/on-hapi-licensing-a-preview-f982662ee898).
381
+ [here](https://web.archive.org/web/20190201220503/https://hueniverse.com/on-hapi-licensing-a-preview-f982662ee898?gi=b54e9a75bac6).
382
382
 
383
383
 
@@ -109,13 +109,6 @@ signature to be used as a lambda `handler` function. This way all the incoming
109
109
  events (API Gateway requests) are passed to the `proxy` function of
110
110
  [@fastify/aws-lambda](https://github.com/fastify/aws-lambda-fastify).
111
111
 
112
- #### Example
113
-
114
- An example deployable with
115
- [claudia.js](https://claudiajs.com/tutorials/serverless-express.html) can be
116
- found
117
- [here](https://github.com/claudiajs/example-projects/tree/master/fastify-app-lambda).
118
-
119
112
  ### Considerations
120
113
 
121
114
  - API Gateway does not support streams yet, so you are not able to handle
@@ -126,7 +119,7 @@ found
126
119
  #### Beyond API Gateway
127
120
 
128
121
  If you need to integrate with more AWS services, take a look at
129
- [@h4ad/serverless-adapter](https://viniciusl.com.br/serverless-adapter/docs/main/frameworks/fastify)
122
+ [@h4ad/serverless-adapter](https://serverless-adapter.viniciusl.com.br/docs/main/frameworks/fastify)
130
123
  on Fastify to find out how to integrate.
131
124
 
132
125
  ## Genezio
@@ -134,7 +127,7 @@ on Fastify to find out how to integrate.
134
127
  [Genezio](https://genezio.com/) is a platform designed to simplify the deployment
135
128
  of serverless applications to the cloud.
136
129
 
137
- [Genezio has a dedicated guide for deploying a Fastify application.](https://genezio.com/docs/frameworks/fastify/)
130
+ [Genezio has a dedicated guide for deploying a Fastify application.](https://deployapps.dev/docs/frameworks/fastify/)
138
131
 
139
132
  ## Google Cloud Functions
140
133
 
@@ -265,7 +258,7 @@ curl -X POST https://$GOOGLE_REGION-$GOOGLE_PROJECT.cloudfunctions.net/me \
265
258
 
266
259
  ### References
267
260
  - [Google Cloud Functions - Node.js Quickstart
268
- ](https://cloud.google.com/functions/docs/quickstart-nodejs)
261
+ ](https://docs.cloud.google.com/run/docs/quickstarts/functions/deploy-functions-gcloud)
269
262
 
270
263
  ## Google Firebase Functions
271
264
 
@@ -403,7 +396,7 @@ the way you would write your Fastify app normally.
403
396
 
404
397
  *Follow the steps below to deploy to Google Cloud Run if you are already
405
398
  familiar with gcloud or just follow their
406
- [quickstart](https://cloud.google.com/run/docs/quickstarts/build-and-deploy)*.
399
+ [quickstart](https://docs.cloud.google.com/run/docs/quickstarts)*.
407
400
 
408
401
  ### Adjust Fastify server
409
402
 
@@ -590,7 +583,7 @@ Then it should work fine.
590
583
 
591
584
  [Vercel](https://vercel.com) fully supports deploying Fastify applications.
592
585
  Additionally, with Vercel's
593
- [Fluid compute](https://vercel.com/docs/functions/fluid-compute), you can combine
586
+ [Fluid compute](https://vercel.com/docs/fluid-compute), you can combine
594
587
  server-like concurrency with the autoscaling properties of traditional
595
588
  serverless functions.
596
589
 
@@ -598,7 +591,7 @@ Get started with the
598
591
  [Fastify template on Vercel](
599
592
  https://vercel.com/templates/backend/fastify-on-vercel).
600
593
 
601
- [Fluid compute](https://vercel.com/docs/functions/fluid-compute) currently
594
+ [Fluid compute](https://vercel.com/docs/fluid-compute) currently
602
595
  requires an explicit opt-in. Learn more about enabling Fluid compute
603
596
  [here](
604
597
  https://vercel.com/docs/fluid-compute#enabling-fluid-compute).
@@ -13,7 +13,7 @@ This guide is for anyone who loves to build with Fastify or wants to contribute
13
13
  to our documentation. You do not need to be an expert in writing technical
14
14
  documentation. This guide is here to help you.
15
15
 
16
- Visit the [contribute](https://fastify.dev/contribute) page on our website or
16
+ Visit the [contribute](https://fastify.dev/contribute/) page on our website or
17
17
  read the
18
18
  [CONTRIBUTING.md](https://github.com/fastify/fastify/blob/main/CONTRIBUTING.md)
19
19
  file on GitHub to join our Open Source folks.
@@ -49,6 +49,7 @@
49
49
  - [FST_ERR_LOG_INVALID_LOGGER_INSTANCE](#fst_err_log_invalid_logger_instance)
50
50
  - [FST_ERR_LOG_INVALID_LOGGER_CONFIG](#fst_err_log_invalid_logger_config)
51
51
  - [FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED](#fst_err_log_logger_and_logger_instance_provided)
52
+ - [FST_ERR_LOG_INVALID_LOG_CONTROLLER](#fst_err_log_invalid_log_controller)
52
53
  - [FST_ERR_REP_INVALID_PAYLOAD_TYPE](#fst_err_rep_invalid_payload_type)
53
54
  - [FST_ERR_REP_RESPONSE_BODY_CONSUMED](#fst_err_rep_response_body_consumed)
54
55
  - [FST_ERR_REP_READABLE_STREAM_LOCKED](#fst_err_rep_readable_stream_locked)
@@ -327,6 +328,7 @@ Below is a table with all the error codes used by Fastify.
327
328
  | <a id="fst_err_log_invalid_logger_instance">FST_ERR_LOG_INVALID_LOGGER_INSTANCE</a> | The `loggerInstance` only accepts a logger instance, not a configuration object. | To pass a configuration object, use `'logger'` instead. | [#5020](https://github.com/fastify/fastify/pull/5020) |
328
329
  | <a id="fst_err_log_invalid_logger_config">FST_ERR_LOG_INVALID_LOGGER_CONFIG</a> | The logger option only accepts a configuration object, not a logger instance. | To pass an instance, use `'loggerInstance'` instead. | [#5020](https://github.com/fastify/fastify/pull/5020) |
329
330
  | <a id="fst_err_log_logger_and_logger_instance_provided">FST_ERR_LOG_LOGGER_AND_LOGGER_INSTANCE_PROVIDED</a> | You cannot provide both `'logger'` and `'loggerInstance'`. | Please provide only one option. | [#5020](https://github.com/fastify/fastify/pull/5020) |
331
+ | <a id="fst_err_log_invalid_log_controller">FST_ERR_LOG_INVALID_LOG_CONTROLLER</a> | The `logController` option must be an instance of `LogController`. | Extend the `LogController` class and pass an instance. | - |
330
332
  | <a id="fst_err_rep_invalid_payload_type">FST_ERR_REP_INVALID_PAYLOAD_TYPE</a> | Reply payload can be either a `string` or a `Buffer`. | Use a `string` or a `Buffer` for the payload. | [#1168](https://github.com/fastify/fastify/pull/1168) |
331
333
  | <a id="fst_err_rep_response_body_consumed">FST_ERR_REP_RESPONSE_BODY_CONSUMED</a> | Using `Response` as reply payload, but the body is being consumed. | Make sure you don't consume the `Response.body` | [#5286](https://github.com/fastify/fastify/pull/5286) |
332
334
  | <a id="fst_err_rep_readable_stream_locked">FST_ERR_REP_READABLE_STREAM_LOCKED</a> | Using `ReadableStream` as reply payload, but locked with another reader. | Make sure you don't call the `Readable.getReader` before sending or release lock with `reader.releaseLock()` before sending. | [#5920](https://github.com/fastify/fastify/pull/5920) |
@@ -51,7 +51,7 @@ It is easy to understand where each hook is executed by looking at the
51
51
  Hooks are affected by Fastify's encapsulation, and can thus be applied to
52
52
  selected routes. See the [Scopes](#scope) section for more information.
53
53
 
54
- There are eight different hooks that you can use in Request/Reply *(in order of
54
+ There are ten different hooks that you can use in Request/Reply *(in order of
55
55
  execution)*:
56
56
 
57
57
  ### onRequest
@@ -13,6 +13,9 @@ As Fastify is focused on performance, it uses
13
13
  [pino](https://github.com/pinojs/pino) as its logger, with the default log
14
14
  level set to `'info'` when enabled.
15
15
 
16
+ The log level can be set per-route. See [the routes
17
+ documentation](./Routes.md#custom-log-level).
18
+
16
19
  #### Basic Logging Setup
17
20
  The following enables the production JSON logger:
18
21
 
@@ -132,14 +132,14 @@ fastify.post('/:params', options, function (request, reply) {
132
132
  console.log(request.url)
133
133
  console.log(request.routeOptions.method)
134
134
  console.log(request.routeOptions.bodyLimit)
135
- console.log(request.routeOptions.method)
135
+ console.log(request.routeOptions.handlerTimeout)
136
136
  console.log(request.routeOptions.url)
137
137
  console.log(request.routeOptions.attachValidation)
138
138
  console.log(request.routeOptions.logLevel)
139
139
  console.log(request.routeOptions.version)
140
140
  console.log(request.routeOptions.exposeHeadRoute)
141
141
  console.log(request.routeOptions.prefixTrailingSlash)
142
- console.log(request.routeOptions.logLevel)
142
+ console.log(request.routeOptions.config)
143
143
  request.log.info('some info')
144
144
  })
145
145
  ```
@@ -23,6 +23,7 @@ describes the properties available in that options object.
23
23
  - [`logger`](#logger)
24
24
  - [`loggerInstance`](#loggerinstance)
25
25
  - [`disableRequestLogging`](#disablerequestlogging)
26
+ - [`logController`](#logcontroller)
26
27
  - [`serverFactory`](#serverfactory)
27
28
  - [`requestIdHeader`](#requestidheader)
28
29
  - [`requestIdLogLabel`](#requestidloglabel)
@@ -389,6 +390,10 @@ Pino interface by having the following methods: `info`, `error`, `debug`,
389
390
  ### `disableRequestLogging`
390
391
  <a id="factory-disable-request-logging"></a>
391
392
 
393
+ > **Deprecated:** Use the [`logController`](#log-controller) option with
394
+ > `disableRequestLogging` or `isLogDisabled` override instead.
395
+ > This top-level option will be removed in `fastify@6`.
396
+
392
397
  + Default: `false`
393
398
 
394
399
  When logging is enabled, Fastify will issue an `info` level log
@@ -402,13 +407,23 @@ and returns a boolean. This allows for conditional request logging based on the
402
407
  request properties (e.g., URL, headers, decorations).
403
408
 
404
409
  ```js
410
+ // Deprecated
405
411
  const fastify = require('fastify')({
406
412
  logger: true,
407
413
  disableRequestLogging: (request) => {
408
- // Disable logging for health check endpoints
409
414
  return request.url === '/health' || request.url === '/ready'
410
415
  }
411
416
  })
417
+
418
+ // Recommended: use logController instead
419
+ const fastify = require('fastify')({
420
+ logger: true,
421
+ logController: {
422
+ disableRequestLogging: (request) => {
423
+ return request.url === '/health' || request.url === '/ready'
424
+ }
425
+ }
426
+ })
412
427
  ```
413
428
 
414
429
  The other log entries that will be disabled are:
@@ -435,6 +450,86 @@ fastify.addHook('onResponse', (req, reply, done) => {
435
450
  })
436
451
  ```
437
452
 
453
+ ### `logController`
454
+ <a id="factory-log-controller"></a>
455
+
456
+ + Default: `undefined`
457
+
458
+ Accepts an instance of `LogController` (or a subclass) to customize Fastify's
459
+ internal log lines. Extend the `LogController` class and override only the
460
+ methods you want to customize; all others keep their default behavior.
461
+
462
+ The `LogController` class is exported from `fastify`:
463
+
464
+ ```js
465
+ const { LogController } = require('fastify')
466
+ ```
467
+
468
+ The constructor accepts an optional options object:
469
+
470
+ | Property | Type | Default | Description |
471
+ |----------|------|---------|-------------|
472
+ | `disableRequestLogging` | `boolean \| (req) => boolean` | `false` | When `true` (or a function returning `true`), per-request log lines are suppressed. |
473
+ | `requestIdLogLabel` | `string` | `'reqId'` | The label used for the request identifier when logging. |
474
+
475
+ ```js
476
+ const { LogController } = require('fastify')
477
+
478
+ class MyLogController extends LogController {
479
+ constructor () {
480
+ super({
481
+ requestIdLogLabel: 'traceId',
482
+ disableRequestLogging: (request) => {
483
+ return request.url === '/health'
484
+ }
485
+ })
486
+ }
487
+
488
+ incomingRequest (request, reply, metadata) {
489
+ // Use debug level instead of info for incoming requests
490
+ request.log.debug({ req: request }, 'incoming request')
491
+ }
492
+
493
+ requestCompleted (error, request, reply, metadata) {
494
+ // Add custom fields to the request completed log
495
+ if (error) {
496
+ reply.log.error({ res: reply, err: error, responseTime: reply.elapsedTime, customField: 'value' }, 'request errored')
497
+ } else {
498
+ reply.log.info({ res: reply, responseTime: reply.elapsedTime, customField: 'value' }, 'request completed')
499
+ }
500
+ }
501
+ }
502
+
503
+ const fastify = require('fastify')({
504
+ logger: true,
505
+ logController: new MyLogController()
506
+ })
507
+ ```
508
+
509
+ The error-related methods share a unified signature:
510
+ `(error, request, reply, metadata)`, where `metadata` carries any extra
511
+ per-method data (for example, the `statusCode` passed to `serializerError`).
512
+ `incomingRequest` and `routeNotFound` omit the `error` argument, since they fire
513
+ at lifecycle points where no error exists. `serviceUnavailable` is a further
514
+ exception, since no route — and therefore no `request`/`reply` — is formed.
515
+
516
+ | Method | Signature | Description |
517
+ |--------|-----------|-------------|
518
+ | `isLogDisabled` | `(request)` | Checks whether request logging is disabled for the given request. It impacts all other log methods. |
519
+ | `incomingRequest` | `(request, reply, metadata)` | Logs an incoming request at `info` level. |
520
+ | `requestCompleted` | `(error, request, reply, metadata)` | Logs the outcome of a completed request. Uses `error` level when an error is present, `info` otherwise. |
521
+ | `defaultErrorLog` | `(error, request, reply, metadata)` | Logs an error handled by the default error handler. Uses `error` for 5xx, `info` for 4xx. |
522
+ | `streamError` | `(error, request, reply, metadata)` | Logs stream-level errors after headers have been sent. |
523
+ | `routeNotFound` | `(request, reply, metadata)` | Logs a "route not found" message at `info` level. |
524
+ | `writeHeadError` | `(error, request, reply, metadata)` | Logs a warning when `writeHead` fails during error handling. |
525
+ | `serializerError` | `(error, request, reply, metadata)` | Logs an error when the serializer for a given status code fails. The triggering status code is available as `metadata.statusCode`. |
526
+ | `serviceUnavailable` | `(logger, server)` | Logs a 503 when the server is closing. Always emitted, not gated by `disableRequestLogging`. |
527
+
528
+ **Note:** When you override a method, you take full control of it — the
529
+ default `disableRequestLogging` check is **not** automatically applied.
530
+ If you need conditional logging, call `this.isLogDisabled(request)` yourself
531
+ or override `isLogDisabled` as well.
532
+
438
533
  ### `serverFactory`
439
534
  <a id="custom-http-server"></a>
440
535
 
@@ -501,6 +596,9 @@ const fastify = require('fastify')({
501
596
  ### `requestIdLogLabel`
502
597
  <a id="factory-request-id-log-label"></a>
503
598
 
599
+ > **Deprecated:** Use the [`logController`](#log-controller) option with
600
+ > `requestIdLogLabel` instead. This top-level option will be removed in `fastify@6`.
601
+
504
602
  + Default: `'reqId'`
505
603
 
506
604
  Defines the label used for the request identifier when logging the request.
@@ -519,9 +617,9 @@ generation behavior as shown below. For generating `UUID`s you may want to check
519
617
  out [hyperid](https://github.com/mcollina/hyperid).
520
618
 
521
619
  > ℹ️ Note:
522
- > `genReqId` will be not called if the header set in
620
+ > `genReqId` will not be called if the header set in
523
621
  > <code>[requestIdHeader](#requestidheader)</code> is available (defaults to
524
- > 'request-id').
622
+ > `false`).
525
623
 
526
624
  ```js
527
625
  let i = 0
@@ -853,7 +951,7 @@ function to sanitize a route's store object to use with the `prettyPrint`
853
951
  functions. This function should accept a single object and return an object.
854
952
 
855
953
  ```js
856
- fastify.get('/user/:username', (request, reply) => {
954
+ const fastify = require('fastify')({
857
955
  routerOptions: {
858
956
  buildPrettyMeta: route => {
859
957
  const cleanMeta = Object.assign({}, route.store)
@@ -864,7 +962,7 @@ fastify.get('/user/:username', (request, reply) => {
864
962
  })
865
963
 
866
964
  return cleanMeta // this will show up in the pretty print output!
867
- })
965
+ }
868
966
  }
869
967
  })
870
968
  ```
@@ -1068,8 +1166,9 @@ objects and do not provide Fastify's decorated helpers.
1068
1166
  ### `querystringParser`
1069
1167
  <a id="querystringparser"></a>
1070
1168
 
1071
- The default query string parser that Fastify uses is the Node.js's core
1072
- `querystring` module.
1169
+ The default query string parser that Fastify uses is a more performant fork
1170
+ of Node.js's core `querystring` module called
1171
+ [`fast-querystring`](https://github.com/anonrig/fast-querystring).
1073
1172
 
1074
1173
  You can use this option to use a custom parser, such as
1075
1174
  [`qs`](https://www.npmjs.com/package/qs).
@@ -1090,7 +1189,7 @@ You can also use Fastify's default parser but change some handling behavior,
1090
1189
  like the example below for case insensitive keys and values:
1091
1190
 
1092
1191
  ```js
1093
- const querystring = require('node:querystring')
1192
+ const querystring = require('fast-querystring')
1094
1193
  const fastify = require('fastify')({
1095
1194
  routerOptions: {
1096
1195
  querystringParser: str => querystring.parse(str.toLowerCase())
@@ -34,10 +34,10 @@ $ npm i @fastify/type-provider-json-schema-to-ts
34
34
  ```
35
35
 
36
36
  ```typescript
37
- import fastify from 'fastify'
37
+ import Fastify from 'fastify'
38
38
  import { JsonSchemaToTsProvider } from '@fastify/type-provider-json-schema-to-ts'
39
39
 
40
- const server = fastify().withTypeProvider<JsonSchemaToTsProvider>()
40
+ const server = Fastify().withTypeProvider<JsonSchemaToTsProvider>()
41
41
 
42
42
  server.get('/route', {
43
43
  schema: {
@@ -57,6 +57,26 @@ server.get('/route', {
57
57
  })
58
58
  ```
59
59
 
60
+ When using raw JSON Schema objects with `JsonSchemaToTsProvider`, TypeScript
61
+ must be able to see the exact literal values in the schema. Inline schemas, like
62
+ the example above, are inferred from the route call. If the schema is moved into
63
+ a separate variable, use `as const`:
64
+
65
+ ```typescript
66
+ const querystringSchema = {
67
+ type: 'object',
68
+ properties: {
69
+ foo: { type: 'number' },
70
+ bar: { type: 'string' },
71
+ },
72
+ required: ['foo', 'bar']
73
+ } as const
74
+ ```
75
+
76
+ Without `as const`, TypeScript may widen schema values such as `type: 'object'`
77
+ to `type: string`, which prevents `json-schema-to-ts` from inferring the route
78
+ types. This assertion has no effect on the schema used by Fastify at runtime.
79
+
60
80
  ### TypeBox
61
81
 
62
82
  The following sets up a TypeBox Type Provider:
@@ -66,11 +86,11 @@ $ npm i typebox @fastify/type-provider-typebox
66
86
  ```
67
87
 
68
88
  ```typescript
69
- import fastify from 'fastify'
89
+ import Fastify from 'fastify'
70
90
  import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox'
71
91
  import { Type } from 'typebox'
72
92
 
73
- const server = fastify().withTypeProvider<TypeBoxTypeProvider>()
93
+ const server = Fastify().withTypeProvider<TypeBoxTypeProvider>()
74
94
 
75
95
  server.get('/route', {
76
96
  schema: {
@@ -658,8 +658,8 @@ unfortunate limitation of using TypeScript and is unavoidable as of right now.
658
658
 
659
659
  However, there are a couple of suggestions to help improve this experience:
660
660
  - Make sure the `no-unused-vars` rule is enabled in
661
- [ESLint](https://eslint.org/docs/rules/no-unused-vars) and any imported plugin
662
- are actually being loaded.
661
+ [ESLint](https://eslint.org/docs/latest/rules/no-unused-vars) and any
662
+ imported plugin are actually being loaded.
663
663
  - Use a module such as [depcheck](https://www.npmjs.com/package/depcheck) or
664
664
  [npm-check](https://www.npmjs.com/package/npm-check) to verify plugin
665
665
  dependencies are being used somewhere in your project.
@@ -828,7 +828,7 @@ fastify.addHook('preHandler', async (req, reply) => {
828
828
  ## Code Completion In Vanilla JavaScript
829
829
 
830
830
  Vanilla JavaScript can use the published types to provide code completion (e.g.
831
- [Intellisense](https://code.visualstudio.com/docs/editor/intellisense)) by
831
+ [Intellisense](https://code.visualstudio.com/docs/editing/intellisense)) by
832
832
  following the [TypeScript JSDoc
833
833
  Reference](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html).
834
834