diff --git a/.gitattributes b/.gitattributes
index cad1c32e3d..a0e7df931f 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,5 +1,2 @@
-# Set the default behavior, in case people don't have core.autocrlf set
-* text=auto
-
-# Require Unix line endings
-* text eol=lf
+# Set default behavior to automatically convert line endings
+* text=auto eol=lf
diff --git a/.github/workflows/benchmark-parser.yml b/.github/workflows/benchmark-parser.yml
index e4e9414279..886c069c7c 100644
--- a/.github/workflows/benchmark-parser.yml
+++ b/.github/workflows/benchmark-parser.yml
@@ -77,9 +77,9 @@ jobs:
**Node**: 20
**PR**: ${{ needs.benchmark.outputs.PR-BENCH-20 }}
**MAIN**: ${{ needs.benchmark.outputs.MAIN-BENCH-20 }}
-
+
---
-
+
**Node**: 22
**PR**: ${{ needs.benchmark.outputs.PR-BENCH-22 }}
**MAIN**: ${{ needs.benchmark.outputs.MAIN-BENCH-22 }}
diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml
index 82ebbe61b2..108988f050 100644
--- a/.github/workflows/benchmark.yml
+++ b/.github/workflows/benchmark.yml
@@ -77,9 +77,9 @@ jobs:
**Node**: 20
**PR**: ${{ needs.benchmark.outputs.PR-BENCH-20 }}
**MAIN**: ${{ needs.benchmark.outputs.MAIN-BENCH-20 }}
-
+
---
-
+
**Node**: 22
**PR**: ${{ needs.benchmark.outputs.PR-BENCH-22 }}
**MAIN**: ${{ needs.benchmark.outputs.MAIN-BENCH-22 }}
diff --git a/.github/workflows/md-lint.yml b/.github/workflows/md-lint.yml
index 95862f259f..97e5facc1c 100644
--- a/.github/workflows/md-lint.yml
+++ b/.github/workflows/md-lint.yml
@@ -27,7 +27,7 @@ jobs:
uses: actions/checkout@v4
with:
persist-credentials: false
-
+
- name: Setup Node
uses: actions/setup-node@v4
with:
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e246e21b67..387760a75a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -107,7 +107,7 @@ the following tasks:
5. The person that does the onboarding must add you to the [npm
org](https://www.npmjs.com/org/fastify), so that you can help maintaining the
official plugins.
-6. Optionally, the person can be added as an Open Collective member
+6. Optionally, the person can be added as an Open Collective member
by the lead team.
### Offboarding Collaborators
diff --git a/EXPENSE_POLICY.md b/EXPENSE_POLICY.md
index 5e5bb7867f..3baa688426 100644
--- a/EXPENSE_POLICY.md
+++ b/EXPENSE_POLICY.md
@@ -98,7 +98,7 @@ To claim a bounty:
- The expense will be validated by a lead maintainer and then the payment will be
processed by Open Collective
-If the Open Collective budget is insufficient, the expense will be rejected.
+If the Open Collective budget is insufficient, the expense will be rejected.
Unclaimed bounties are available for other issues.
[submit]: https://opencollective.com/fastify/expenses/new
diff --git a/docs/Guides/Database.md b/docs/Guides/Database.md
index 3369b33498..72449133f1 100644
--- a/docs/Guides/Database.md
+++ b/docs/Guides/Database.md
@@ -2,17 +2,17 @@
## Database
-Fastify's ecosystem provides a handful of
-plugins for connecting to various database engines.
-This guide covers engines that have Fastify
+Fastify's ecosystem provides a handful of
+plugins for connecting to various database engines.
+This guide covers engines that have Fastify
plugins maintained within the Fastify organization.
-> If a plugin for your database of choice does not exist
-> you can still use the database as Fastify is database agnostic.
-> By following the examples of the database plugins listed in this guide,
-> a plugin can be written for the missing database engine.
+> If a plugin for your database of choice does not exist
+> you can still use the database as Fastify is database agnostic.
+> By following the examples of the database plugins listed in this guide,
+> a plugin can be written for the missing database engine.
-> If you would like to write your own Fastify plugin
+> If you would like to write your own Fastify plugin
> please take a look at the [plugins guide](./Plugins-Guide.md)
### [MySQL](https://github.com/fastify/fastify-mysql)
@@ -104,8 +104,8 @@ fastify.listen({ port: 3000 }, err => {
})
```
-By default `@fastify/redis` doesn't close
-the client connection when Fastify server shuts down.
+By default `@fastify/redis` doesn't close
+the client connection when Fastify server shuts down.
To opt-in to this behavior, register the client like so:
```javascript
@@ -126,7 +126,7 @@ fastify.register(require('@fastify/mongodb'), {
// force to close the mongodb connection when app stopped
// the default value is false
forceClose: true,
-
+
url: 'mongodb://mongo/mydb'
})
@@ -178,8 +178,8 @@ fastify.listen({ port: 3000 }, err => {
```
### Writing plugin for a database library
-We could write a plugin for a database
-library too (e.g. Knex, Prisma, or TypeORM).
+We could write a plugin for a database
+library too (e.g. Knex, Prisma, or TypeORM).
We will use [Knex](https://knexjs.org/) in our example.
```javascript
@@ -281,7 +281,7 @@ async function migrate() {
const client = new pg.Client({
host: 'localhost',
port: 5432,
- database: 'example',
+ database: 'example',
user: 'example',
password: 'example',
});
@@ -313,7 +313,7 @@ async function migrate() {
console.error(err)
process.exitCode = 1
}
-
+
await client.end()
}
diff --git a/docs/Guides/Detecting-When-Clients-Abort.md b/docs/Guides/Detecting-When-Clients-Abort.md
index 644f3f6f74..e2771013b7 100644
--- a/docs/Guides/Detecting-When-Clients-Abort.md
+++ b/docs/Guides/Detecting-When-Clients-Abort.md
@@ -4,30 +4,30 @@
## Introduction
-Fastify provides request events to trigger at certain points in a request's
-lifecycle. However, there isn't a built-in mechanism to
-detect unintentional client disconnection scenarios such as when the client's
+Fastify provides request events to trigger at certain points in a request's
+lifecycle. However, there isn't a built-in mechanism to
+detect unintentional client disconnection scenarios such as when the client's
internet connection is interrupted. This guide covers methods to detect if
and when a client intentionally aborts a request.
-Keep in mind, Fastify's `clientErrorHandler` is not designed to detect when a
-client aborts a request. This works in the same way as the standard Node HTTP
-module, which triggers the `clientError` event when there is a bad request or
-exceedingly large header data. When a client aborts a request, there is no
+Keep in mind, Fastify's `clientErrorHandler` is not designed to detect when a
+client aborts a request. This works in the same way as the standard Node HTTP
+module, which triggers the `clientError` event when there is a bad request or
+exceedingly large header data. When a client aborts a request, there is no
error on the socket and the `clientErrorHandler` will not be triggered.
## Solution
### Overview
-The proposed solution is a possible way of detecting when a client
-intentionally aborts a request, such as when a browser is closed or the HTTP
-request is aborted from your client application. If there is an error in your
-application code that results in the server crashing, you may require
+The proposed solution is a possible way of detecting when a client
+intentionally aborts a request, such as when a browser is closed or the HTTP
+request is aborted from your client application. If there is an error in your
+application code that results in the server crashing, you may require
additional logic to avoid a false abort detection.
-The goal here is to detect when a client intentionally aborts a connection
-so your application logic can proceed accordingly. This can be useful for
+The goal here is to detect when a client intentionally aborts a connection
+so your application logic can proceed accordingly. This can be useful for
logging purposes or halting business logic.
### Hands-on
@@ -78,10 +78,10 @@ const start = async () => {
start()
```
-Our code is setting up a Fastify server which includes the following
+Our code is setting up a Fastify server which includes the following
functionality:
-- Accepting requests at http://localhost:3000, with a 3 second delayed response
+- Accepting requests at http://localhost:3000, with a 3 second delayed response
of `{ ok: true }`.
- An onRequest hook that triggers when every request is received.
- Logic that triggers in the hook when the request is closed.
@@ -108,7 +108,7 @@ app.get('/', async (request, reply) => {
})
```
-At any point in your business logic, you can check if the request has been
+At any point in your business logic, you can check if the request has been
aborted and perform alternative actions.
```js
@@ -122,14 +122,14 @@ app.get('/', async (request, reply) => {
})
```
-A benefit to adding this in your application code is that you can log Fastify
-details such as the reqId, which may be unavailable in lower-level code that
+A benefit to adding this in your application code is that you can log Fastify
+details such as the reqId, which may be unavailable in lower-level code that
only has access to the raw request information.
### Testing
-To test this functionality you can use an app like Postman and cancel your
-request within 3 seconds. Alternatively, you can use Node to send an HTTP
+To test this functionality you can use an app like Postman and cancel your
+request within 3 seconds. Alternatively, you can use Node to send an HTTP
request with logic to abort the request before 3 seconds. Example:
```js
@@ -151,7 +151,7 @@ setTimeout(() => {
}, 1000);
```
-With either approach, you should see the Fastify log appear at the moment the
+With either approach, you should see the Fastify log appear at the moment the
request is aborted.
## Conclusion
@@ -160,13 +160,13 @@ Specifics of the implementation will vary from one problem to another, but the
main goal of this guide was to show a very specific use case of an issue that
could be solved within Fastify's ecosystem.
-You can listen to the request close event and determine if the request was
-aborted or if it was successfully delivered. You can implement this solution
+You can listen to the request close event and determine if the request was
+aborted or if it was successfully delivered. You can implement this solution
in an onRequest hook or directly in an individual route.
-This approach will not trigger in the event of internet disruption, and such
-detection would require additional business logic. If you have flawed backend
-application logic that results in a server crash, then you could trigger a
-false detection. The `clientErrorHandler`, either by default or with custom
-logic, is not intended to handle this scenario and will not trigger when the
+This approach will not trigger in the event of internet disruption, and such
+detection would require additional business logic. If you have flawed backend
+application logic that results in a server crash, then you could trigger a
+false detection. The `clientErrorHandler`, either by default or with custom
+logic, is not intended to handle this scenario and will not trigger when the
client aborts a request.
diff --git a/docs/Guides/Ecosystem.md b/docs/Guides/Ecosystem.md
index 81e4ed99f1..bee56704fe 100644
--- a/docs/Guides/Ecosystem.md
+++ b/docs/Guides/Ecosystem.md
@@ -249,7 +249,7 @@ section.
plugin to authenticate HTTP requests based on API key and signature
- [`fastify-appwrite`](https://github.com/Dev-Manny/fastify-appwrite) Fastify
Plugin for interacting with Appwrite server.
-- [`fastify-asyncforge`](https://github.com/mcollina/fastify-asyncforge) Plugin
+- [`fastify-asyncforge`](https://github.com/mcollina/fastify-asyncforge) Plugin
to access Fastify instance, logger, request and reply from Node.js [Async
Local Storage](https://nodejs.org/api/async_context.html#class-asynclocalstorage).
- [`fastify-at-mysql`](https://github.com/mateonunez/fastify-at-mysql) Fastify
@@ -277,7 +277,7 @@ section.
development servers that require Babel transformations of JavaScript sources.
- [`fastify-bcrypt`](https://github.com/beliven-it/fastify-bcrypt) A Bcrypt hash
generator & checker.
-- [`fastify-better-sqlite3`](https://github.com/punkish/fastify-better-sqlite3)
+- [`fastify-better-sqlite3`](https://github.com/punkish/fastify-better-sqlite3)
Plugin for better-sqlite3.
- [`fastify-blipp`](https://github.com/PavelPolyakov/fastify-blipp) Prints your
routes to the console, so you definitely know which endpoints are available.
@@ -289,7 +289,7 @@ section.
to add [bree](https://github.com/breejs/bree) support.
- [`fastify-bugsnag`](https://github.com/ZigaStrgar/fastify-bugsnag) Fastify plugin
to add support for [Bugsnag](https://www.bugsnag.com/) error reporting.
-- [`fastify-cacheman`](https://gitlab.com/aalfiann/fastify-cacheman)
+- [`fastify-cacheman`](https://gitlab.com/aalfiann/fastify-cacheman)
Small and efficient cache provider for Node.js with In-memory, File, Redis
and MongoDB engines for Fastify
- [`fastify-casbin`](https://github.com/nearform/fastify-casbin) Casbin support
@@ -344,7 +344,7 @@ section.
- [`fastify-event-bus`](https://github.com/Shiva127/fastify-event-bus) Event bus
support for Fastify. Built upon [js-event-bus](https://github.com/bcerati/js-event-bus).
- [`fastify-evervault`](https://github.com/Briscoooe/fastify-evervault/) Fastify
- plugin for instantiating and encapsulating the
+ plugin for instantiating and encapsulating the
[Evervault](https://evervault.com/) client.
- [`fastify-explorer`](https://github.com/Eomm/fastify-explorer) Get control of
your decorators across all the encapsulated contexts.
diff --git a/docs/Guides/Index.md b/docs/Guides/Index.md
index 9e80b16605..a26fac6fec 100644
--- a/docs/Guides/Index.md
+++ b/docs/Guides/Index.md
@@ -15,7 +15,7 @@ This table of contents is in alphabetical order.
met in your application. This guide focuses on solving the problem using
[`Hooks`](../Reference/Hooks.md), [`Decorators`](../Reference/Decorators.md),
and [`Plugins`](../Reference/Plugins.md).
-+ [Detecting When Clients Abort](./Detecting-When-Clients-Abort.md): A
++ [Detecting When Clients Abort](./Detecting-When-Clients-Abort.md): A
practical guide on detecting if and when a client aborts a request.
+ [Ecosystem](./Ecosystem.md): Lists all core plugins and many known community
plugins.
diff --git a/docs/Guides/Migration-Guide-V4.md b/docs/Guides/Migration-Guide-V4.md
index ccabda5f04..0049f43954 100644
--- a/docs/Guides/Migration-Guide-V4.md
+++ b/docs/Guides/Migration-Guide-V4.md
@@ -9,13 +9,13 @@ work after upgrading.
## Codemods
### Fastify v4 Codemods
-To help with the upgrade, we’ve worked with the team at
+To help with the upgrade, we’ve worked with the team at
[Codemod](https://github.com/codemod-com/codemod) to
-publish codemods that will automatically update your code to many of
+publish codemods that will automatically update your code to many of
the new APIs and patterns in Fastify v4.
-Run the following
-[migration recipe](https://go.codemod.com/fastify-4-migration-recipe) to
+Run the following
+[migration recipe](https://go.codemod.com/fastify-4-migration-recipe) to
automatically update your code to Fastify v4:
```
@@ -30,7 +30,7 @@ This will run the following codemods:
- [`fastify/4/await-register-calls`](https://go.codemod.com/fastify-4-await-register-calls)
Each of these codemods automates the changes listed in the v4 migration guide.
-For a complete list of available Fastify codemods and further details,
+For a complete list of available Fastify codemods and further details,
see [Codemod Registry](https://go.codemod.com/fastify).
@@ -52,14 +52,14 @@ fastify.register(async fastify => {
console.log(err.message) // 'kaboom'
throw new Error('caught')
})
-
+
fastify.get('/encapsulated', async () => {
throw new Error('kaboom')
})
})
fastify.setErrorHandler(async err => {
- console.log(err.message) // 'caught'
+ console.log(err.message) // 'caught'
throw new Error('wrapped')
})
@@ -67,10 +67,10 @@ const res = await fastify.inject('/encapsulated')
console.log(res.json().message) // 'wrapped'
```
->The root error handler is Fastify’s generic error handler.
->This error handler will use the headers and status code in the Error object,
+>The root error handler is Fastify’s generic error handler.
+>This error handler will use the headers and status code in the Error object,
>if they exist. **The headers and status code will not be automatically set if
->a custom error handler is provided**.
+>a custom error handler is provided**.
### Removed `app.use()` ([#3506](https://github.com/fastify/fastify/pull/3506))
@@ -242,7 +242,7 @@ As such, schemas like below will need to be changed from:
properties: {
api_key: { type: 'string' },
image: { type: ['object', 'array'] }
- }
+ }
}
```
diff --git a/docs/Guides/Migration-Guide-V5.md b/docs/Guides/Migration-Guide-V5.md
index 7848bdb1ed..a288215e1c 100644
--- a/docs/Guides/Migration-Guide-V5.md
+++ b/docs/Guides/Migration-Guide-V5.md
@@ -159,7 +159,7 @@ the following:
+++ b/index.ts
@@ -11,7 +11,8 @@ import {
import { FromSchema, FromSchemaDefaultOptions, FromSchemaOptions, JSONSchema } from 'json-schema-to-ts'
-
+
export interface JsonSchemaToTsProvider<
Options extends FromSchemaOptions = FromSchemaDefaultOptions
> extends FastifyTypeProvider {
@@ -298,7 +298,7 @@ use the `constraints` option instead.
We have a more strict requirement for custom `HEAD` route when
`exposeHeadRoutes: true`.
-When you provides a custom `HEAD` route, you must either explicitly
+When you provides a custom `HEAD` route, you must either explicitly
set `exposeHeadRoutes` to `false`
```js
@@ -403,7 +403,7 @@ and requires the route definition to be passed as it is defined in the route.
fastify.get('/example/:file(^\\d+).png', function (request, reply) { })
console.log(fastify.hasRoute({
- method: 'GET',
+ method: 'GET',
url: '/example/12345.png'
)); // true
```
@@ -414,7 +414,7 @@ console.log(fastify.hasRoute({
fastify.get('/example/:file(^\\d+).png', function (request, reply) { })
console.log(fastify.hasRoute({
- method: 'GET',
+ method: 'GET',
url: '/example/:file(^\\d+).png'
)); // true
```
@@ -480,7 +480,7 @@ or as a getter
```js
// v5
fastify.decorateRequest('myObject', {
- getter () {
+ getter () {
return { hello: 'world' }
}
});
diff --git a/docs/Guides/Plugins-Guide.md b/docs/Guides/Plugins-Guide.md
index ae5e7d6f59..4fc8821b3a 100644
--- a/docs/Guides/Plugins-Guide.md
+++ b/docs/Guides/Plugins-Guide.md
@@ -316,7 +316,7 @@ based on a [route config option](../Reference/Routes.md#routes-options):
```js
fastify.register((instance, opts, done) => {
instance.decorate('util', (request, key, value) => { request[key] = value })
-
+
function handler(request, reply, done) {
instance.util(request, 'timestamp', new Date())
done()
diff --git a/docs/Guides/Prototype-Poisoning.md b/docs/Guides/Prototype-Poisoning.md
index c2ff2f1cc3..0d01aa9047 100644
--- a/docs/Guides/Prototype-Poisoning.md
+++ b/docs/Guides/Prototype-Poisoning.md
@@ -8,7 +8,7 @@
Based on the article by Eran Hammer,the issue is created by a web security bug.
-It is also a perfect illustration of the efforts required to maintain
+It is also a perfect illustration of the efforts required to maintain
open-source software and the limitations of existing communication channels.
But first, if we use a JavaScript framework to process incoming JSON data, take
@@ -16,7 +16,7 @@ a moment to read up on [Prototype Poisoning](https://medium.com/intrinsic/javasc
in general, and the specific
[technical details](https://github.com/hapijs/hapi/issues/3916) of this issue.
This could be a critical issue so, we might need to verify your own code first.
-It focuses on specific framework however, any solution that uses `JSON.parse()`
+It focuses on specific framework however, any solution that uses `JSON.parse()`
to process external data is potentially at risk.
### BOOM
@@ -42,7 +42,7 @@ defect a validation library can have.
To understand this, we need to understand how JavaScript works a bit.
Every object in JavaScript can have a prototype. It is a set of methods and
-properties it "inherits" from another object. I have put inherits in quotes
+properties it "inherits" from another object. I have put inherits in quotes
because JavaScript isn't really an object-oriented language. It is a prototype-
based object-oriented language.
diff --git a/docs/Guides/Recommendations.md b/docs/Guides/Recommendations.md
index 58e921d614..3e23be6224 100644
--- a/docs/Guides/Recommendations.md
+++ b/docs/Guides/Recommendations.md
@@ -307,22 +307,22 @@ readinessProbe:
## Capacity Planning For Production
-In order to rightsize the production environment for your Fastify application,
-it is highly recommended that you perform your own measurements against
+In order to rightsize the production environment for your Fastify application,
+it is highly recommended that you perform your own measurements against
different configurations of the environment, which may
use real CPU cores, virtual CPU cores (vCPU), or even fractional
vCPU cores. We will use the term vCPU throughout this
recommendation to represent any CPU type.
-Tools such as [k6](https://github.com/grafana/k6)
+Tools such as [k6](https://github.com/grafana/k6)
or [autocannon](https://github.com/mcollina/autocannon) can be used for
conducting the necessary performance tests.
That said, you may also consider the following as a rule of thumb:
-* To have the lowest possible latency, 2 vCPU are recommended per app
-instance (e.g., a k8s pod). The second vCPU will mostly be used by the
-garbage collector (GC) and libuv threadpool. This will minimize the latency
+* To have the lowest possible latency, 2 vCPU are recommended per app
+instance (e.g., a k8s pod). The second vCPU will mostly be used by the
+garbage collector (GC) and libuv threadpool. This will minimize the latency
for your users, as well as the memory usage, as the GC will be run more
frequently. Also, the main thread won't have to stop to let the GC run.
@@ -330,7 +330,7 @@ frequently. Also, the main thread won't have to stop to let the GC run.
requests per second per vCPU available), consider using a smaller amount of vCPUs
per app instance. It is totally fine to run Node.js applications with 1 vCPU.
-* You may experiment with an even smaller amount of vCPU, which may provide
+* You may experiment with an even smaller amount of vCPU, which may provide
even better throughput in certain use-cases. There are reports of API gateway
solutions working well with 100m-200m vCPU in Kubernetes.
@@ -347,7 +347,7 @@ would be exposing metrics endpoints on a separate port,
to prevent public access, when using a reverse proxy or an ingress
firewall is not an option.
-It is perfectly fine to spin up several Fastify instances within the same
-Node.js process and run them concurrently, even in high load systems.
+It is perfectly fine to spin up several Fastify instances within the same
+Node.js process and run them concurrently, even in high load systems.
Each Fastify instance only generates as much load as the traffic it receives,
plus the memory used for that Fastify instance.
diff --git a/docs/Guides/Serverless.md b/docs/Guides/Serverless.md
index be434b967f..454d77bbae 100644
--- a/docs/Guides/Serverless.md
+++ b/docs/Guides/Serverless.md
@@ -36,10 +36,10 @@ snippet of code.
To integrate with AWS, you have two choices of library:
-- Using [@fastify/aws-lambda](https://github.com/fastify/aws-lambda-fastify)
+- Using [@fastify/aws-lambda](https://github.com/fastify/aws-lambda-fastify)
which only adds API Gateway support but has heavy optimizations for fastify.
-- Using [@h4ad/serverless-adapter](https://github.com/H4ad/serverless-adapter)
- which is a little slower as it creates an HTTP request for each AWS event but
+- Using [@h4ad/serverless-adapter](https://github.com/H4ad/serverless-adapter)
+ which is a little slower as it creates an HTTP request for each AWS event but
has support for more AWS services such as: AWS SQS, AWS SNS and others.
So you can decide which option is best for you, but you can test both libraries.
@@ -263,7 +263,7 @@ curl -X POST https://$GOOGLE_REGION-$GOOGLE_PROJECT.cloudfunctions.net/me \
## Google Firebase Functions
-Follow this guide if you want to use Fastify as the HTTP framework for
+Follow this guide if you want to use Fastify as the HTTP framework for
Firebase Functions instead of the vanilla JavaScript router provided with
`onRequest(async (req, res) => {}`.
@@ -280,7 +280,7 @@ const { onRequest } = require("firebase-functions/v2/https")
### Creation of Fastify instance
Create the Fastify instance and encapsulate the returned application instance
-in a function which will register routes, await the server's processing of
+in a function which will register routes, await the server's processing of
plugins, hooks and other settings. As follows:
```js
diff --git a/docs/Guides/Testing.md b/docs/Guides/Testing.md
index 1dfc59247f..3fb4081660 100644
--- a/docs/Guides/Testing.md
+++ b/docs/Guides/Testing.md
@@ -264,7 +264,7 @@ test('should work with undici', async t => {
'http://localhost:' + fastify.server.address().port, {
keepAliveTimeout: 10,
keepAliveMaxTimeout: 10
- }
+ }
)
t.after(() => {
@@ -279,8 +279,8 @@ test('should work with undici', async t => {
})
```
-Alternatively, starting with Node.js 18,
-[`fetch`](https://nodejs.org/docs/latest-v18.x/api/globals.html#fetch)
+Alternatively, starting with Node.js 18,
+[`fetch`](https://nodejs.org/docs/latest-v18.x/api/globals.html#fetch)
may be used without requiring any extra dependencies:
**test-listen.js**
@@ -296,7 +296,7 @@ test('should work with fetch', async t => {
t.after(() => fastify.close())
await fastify.listen()
-
+
const response = await fetch(
'http://localhost:' + fastify.server.address().port
)
@@ -386,7 +386,7 @@ test("Test the Plugin Route", async t => {
fastify.register(myPlugin)
- // Add an endpoint of your choice
+ // Add an endpoint of your choice
fastify.get("/", async (request, reply) => {
return ({ message: request.helloRequest })
})
@@ -396,7 +396,7 @@ test("Test the Plugin Route", async t => {
method: "GET",
url: "/"
})
-
+
console.log('status code: ', fastifyResponse.statusCode)
console.log('body: ', fastifyResponse.body)
})
@@ -440,7 +440,7 @@ test("Test the Plugin Route", async t => {
method: "GET",
url: "/"
})
-
+
t.assert.strictEqual(fastifyResponse.statusCode, 200)
t.assert.deepStrictEqual(JSON.parse(fastifyResponse.body), { message: "Hello World" })
})
@@ -465,7 +465,7 @@ test("Test the Plugin Route", async t => {
fastify.get("/", async (request, reply) => {
// Testing the fastify decorators
- t.assert.ifError(request.helloRequest)
+ t.assert.ifError(request.helloRequest)
t.assert.ok(request.helloRequest, "Hello World")
t.assert.ok(fastify.helloInstance, "Hello Fastify Instance")
return ({ message: request.helloRequest })
diff --git a/docs/Guides/Write-Plugin.md b/docs/Guides/Write-Plugin.md
index cc5b70266b..00eee85467 100644
--- a/docs/Guides/Write-Plugin.md
+++ b/docs/Guides/Write-Plugin.md
@@ -63,7 +63,7 @@ among different versions of its dependencies.
We do not enforce any testing library. We use [`node:test`](https://nodejs.org/api/test.html)
since it offers out-of-the-box parallel testing and code coverage, but it is up
to you to choose your library of preference.
-We highly recommend you read the [Plugin Testing](./Testing.md#plugins) to
+We highly recommend you read the [Plugin Testing](./Testing.md#plugins) to
learn about how to test your plugins.
## Code Linter
diff --git a/docs/Guides/Write-Type-Provider.md b/docs/Guides/Write-Type-Provider.md
index 4078345015..0f0d750fdf 100644
--- a/docs/Guides/Write-Type-Provider.md
+++ b/docs/Guides/Write-Type-Provider.md
@@ -10,9 +10,9 @@ Whereas exhaustive type narrowing checks normally rely on `never` to represent
an unreachable state, reduction in type provider interfaces should only be done
up to `unknown`.
-The reasoning is that certain methods of `FastifyInstance` are
-contravariant on `TypeProvider`, which can lead to TypeScript surfacing
-assignability issues unless the custom type provider interface is
+The reasoning is that certain methods of `FastifyInstance` are
+contravariant on `TypeProvider`, which can lead to TypeScript surfacing
+assignability issues unless the custom type provider interface is
substitutable with `FastifyTypeProviderDefault`.
For example, `FastifyTypeProviderDefault` will not be assignable to the following:
diff --git a/docs/Reference/Decorators.md b/docs/Reference/Decorators.md
index 4465ad5e9e..735bd2386c 100644
--- a/docs/Reference/Decorators.md
+++ b/docs/Reference/Decorators.md
@@ -59,7 +59,7 @@ close as possible to the value intended to be set dynamically in the future.
Initialize a decorator as a `''` if the intended value is a string, and as
`null` if it will be an object or a function.
-Remember this example works only with value types as reference types will
+Remember this example works only with value types as reference types will
thrown and error during the fastify startup. See [decorateRequest](#decorate-request).
See [JavaScript engine fundamentals: Shapes and Inline
@@ -109,7 +109,7 @@ fastify.decorate('db', new DbConnection())
fastify.get('/', async function (request, reply) {
// using return
return { hello: await this.db.query('world') }
-
+
// or
// using reply.send()
reply.send({ hello: await this.db.query('world') })
diff --git a/docs/Reference/Errors.md b/docs/Reference/Errors.md
index 34f1621b2e..ad19abafd8 100644
--- a/docs/Reference/Errors.md
+++ b/docs/Reference/Errors.md
@@ -178,13 +178,13 @@ When utilizing Fastify's custom error handling through [`setErrorHandler`](./Ser
you should be aware of how errors are propagated between custom and default
error handlers.
-If a plugin's error handler re-throws an error, and the error is not an
+If a plugin's error handler re-throws an error, and the error is not an
instance of [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
(as seen in the `/bad` route in the following example), it will not propagate
to the parent context error handler. Instead, it will be caught by the default
error handler.
-To ensure consistent error handling, it is recommended to throw instances of
+To ensure consistent error handling, it is recommended to throw instances of
`Error`. For instance, in the following example, replacing `throw 'foo'` with
`throw new Error('foo')` in the `/bad` route ensures that errors propagate through
the custom error handling chain as intended. This practice helps avoid potential
diff --git a/docs/Reference/Hooks.md b/docs/Reference/Hooks.md
index 13a07d02a0..206a2ab6fe 100644
--- a/docs/Reference/Hooks.md
+++ b/docs/Reference/Hooks.md
@@ -107,7 +107,7 @@ returned stream. This property is used to correctly match the request payload
with the `Content-Length` header value. Ideally, this property should be updated
on each received chunk.
-**Notice:** The size of the returned stream is checked to not exceed the limit
+**Notice:** The size of the returned stream is checked to not exceed the limit
set in [`bodyLimit`](./Server.md#bodylimit) option.
### preValidation
@@ -256,8 +256,8 @@ The `onResponse` hook is executed when a response has been sent, so you will not
be able to send more data to the client. It can however be useful for sending
data to external services, for example, to gather statistics.
-**Note:** setting `disableRequestLogging` to `true` will disable any error log
-inside the `onResponse` hook. In this case use `try - catch` to log errors.
+**Note:** setting `disableRequestLogging` to `true` will disable any error log
+inside the `onResponse` hook. In this case use `try - catch` to log errors.
### onTimeout
@@ -428,8 +428,8 @@ fastify.addHook('onReady', async function () {
### onListen
-Triggered when the server starts listening for requests. The hooks run one
-after another. If a hook function causes an error, it is logged and
+Triggered when the server starts listening for requests. The hooks run one
+after another. If a hook function causes an error, it is logged and
ignored, allowing the queue of hooks to continue. Hook functions accept one
argument: a callback, `done`, to be invoked after the hook function is
complete. Hook functions are invoked with `this` bound to the associated
@@ -451,7 +451,7 @@ fastify.addHook('onListen', async function () {
})
```
-> **Note**
+> **Note**
> This hook will not run when the server is started using `fastify.inject()` or `fastify.ready()`
### onClose
@@ -462,7 +462,7 @@ HTTP requests have been completed.
It is useful when [plugins](./Plugins.md) need a "shutdown" event, for example,
to close an open connection to a database.
-The hook function takes the Fastify instance as a first argument,
+The hook function takes the Fastify instance as a first argument,
and a `done` callback for synchronous hook functions.
```js
// callback style
diff --git a/docs/Reference/Reply.md b/docs/Reference/Reply.md
index 31e6c0f19d..daaf599314 100644
--- a/docs/Reference/Reply.md
+++ b/docs/Reference/Reply.md
@@ -71,14 +71,14 @@ since the request was received by Fastify.
serialized payload.
- `.getSerializationFunction(schema | httpStatus, [contentType])` - Returns the serialization
function for the specified schema or http status, if any of either are set.
-- `.compileSerializationSchema(schema, [httpStatus], [contentType])` - Compiles
- the specified schema and returns a serialization function using the default
- (or customized) `SerializerCompiler`. The optional `httpStatus` is forwarded
+- `.compileSerializationSchema(schema, [httpStatus], [contentType])` - Compiles
+ the specified schema and returns a serialization function using the default
+ (or customized) `SerializerCompiler`. The optional `httpStatus` is forwarded
to the `SerializerCompiler` if provided, default to `undefined`.
-- `.serializeInput(data, schema, [,httpStatus], [contentType])` - Serializes
+- `.serializeInput(data, schema, [,httpStatus], [contentType])` - Serializes
the specified data using the specified schema and returns the serialized payload.
- If the optional `httpStatus`, and `contentType` are provided, the function
- will use the serializer function given for that specific content type and
+ If the optional `httpStatus`, and `contentType` are provided, the function
+ will use the serializer function given for that specific content type and
HTTP Status Code. Default to `undefined`.
- `.serializer(function)` - Sets a custom serializer for the payload.
- `.send(payload)` - Sends the payload to the user, could be a plain text, a
@@ -243,7 +243,7 @@ The hints parameter is an object containing the early hint key-value pairs.
Example:
```js
-reply.writeEarlyHints({
+reply.writeEarlyHints({
Link: '; rel=preload; as=style'
});
```
@@ -366,8 +366,8 @@ If the `Content-Type` has a JSON subtype, and the charset parameter is not set,
### .getSerializationFunction(schema | httpStatus, [contentType])
-By calling this function using a provided `schema` or `httpStatus`,
-and the optional `contentType`, it will return a `serialzation` function
+By calling this function using a provided `schema` or `httpStatus`,
+and the optional `contentType`, it will return a `serialzation` function
that can be used to serialize diverse inputs. It returns `undefined` if no
serialization function was found using either of the provided inputs.
@@ -377,12 +377,12 @@ the serialization functions compiled by using `compileSerializationSchema`.
```js
const serialize = reply
.getSerializationFunction({
- type: 'object',
- properties: {
- foo: {
- type: 'string'
- }
- }
+ type: 'object',
+ properties: {
+ foo: {
+ type: 'string'
+ }
+ }
})
serialize({ foo: 'bar' }) // '{"foo":"bar"}'
@@ -411,8 +411,8 @@ The function returned (a.k.a. _serialization function_) returned is compiled
by using the provided `SerializerCompiler`. Also this is cached by using
a `WeakMap` for reducing compilation calls.
-The optional parameters `httpStatus` and `contentType`, if provided,
-are forwarded directly to the `SerializerCompiler`, so it can be used
+The optional parameters `httpStatus` and `contentType`, if provided,
+are forwarded directly to the `SerializerCompiler`, so it can be used
to compile the serialization function if a custom `SerializerCompiler` is used.
This heavily depends of the `schema#responses` attached to the route, or
@@ -421,12 +421,12 @@ the serialization functions compiled by using `compileSerializationSchema`.
```js
const serialize = reply
.compileSerializationSchema({
- type: 'object',
- properties: {
- foo: {
- type: 'string'
- }
- }
+ type: 'object',
+ properties: {
+ foo: {
+ type: 'string'
+ }
+ }
})
serialize({ foo: 'bar' }) // '{"foo":"bar"}'
@@ -434,12 +434,12 @@ serialize({ foo: 'bar' }) // '{"foo":"bar"}'
const serialize = reply
.compileSerializationSchema({
- type: 'object',
- properties: {
- foo: {
- type: 'string'
- }
- }
+ type: 'object',
+ properties: {
+ foo: {
+ type: 'string'
+ }
+ }
}, 200)
serialize({ foo: 'bar' }) // '{"foo":"bar"}'
@@ -485,7 +485,7 @@ const schema1 = {
```
*Not*
-```js
+```js
const serialize = reply.compileSerializationSchema(schema1)
// Later on...
@@ -519,25 +519,25 @@ function will be compiled, forwarding the `httpStatus` and `contentType` if prov
```js
reply
- .serializeInput({ foo: 'bar'}, {
- type: 'object',
- properties: {
- foo: {
- type: 'string'
- }
- }
+ .serializeInput({ foo: 'bar'}, {
+ type: 'object',
+ properties: {
+ foo: {
+ type: 'string'
+ }
+ }
}) // '{"foo":"bar"}'
// or
reply
.serializeInput({ foo: 'bar'}, {
- type: 'object',
- properties: {
- foo: {
- type: 'string'
- }
- }
+ type: 'object',
+ properties: {
+ foo: {
+ type: 'string'
+ }
+ }
}, 200) // '{"foo":"bar"}'
// or
@@ -712,7 +712,7 @@ fastify.get('/streams', async function (request, reply) {
If you are sending a buffer and you have not set a `'Content-Type'` header,
*send* will set it to `'application/octet-stream'`.
-As noted above, Buffers are considered to be pre-serialized, so they will be
+As noted above, Buffers are considered to be pre-serialized, so they will be
sent unmodified without response validation.
```js
@@ -743,7 +743,7 @@ fastify.get('/streams', async function (request, reply) {
`send` manages TypedArray like a Buffer, and sets the `'Content-Type'`
header to `'application/octet-stream'` if not already set.
-As noted above, TypedArray/Buffers are considered to be pre-serialized, so they
+As noted above, TypedArray/Buffers are considered to be pre-serialized, so they
will be sent unmodified without response validation.
```js
@@ -759,7 +759,7 @@ fastify.get('/streams', function (request, reply) {
`ReadableStream` will be treated as a node stream mentioned above,
-the content is considered to be pre-serialized, so they will be
+the content is considered to be pre-serialized, so they will be
sent unmodified without response validation.
```js
@@ -778,7 +778,7 @@ fastify.get('/streams', function (request, reply) {
`Response` allows to manage the reply payload, status code and
headers in one place. The payload provided inside `Response` is
-considered to be pre-serialized, so they will be sent unmodified
+considered to be pre-serialized, so they will be sent unmodified
without response validation.
Please be aware when using `Response`, the status code and headers
diff --git a/docs/Reference/Request.md b/docs/Reference/Request.md
index 2acd11e92f..a1fdcf149f 100644
--- a/docs/Reference/Request.md
+++ b/docs/Reference/Request.md
@@ -30,13 +30,13 @@ Request is a core Fastify object containing the following fields:
- `protocol` - the protocol of the incoming request (`https` or `http`)
- `method` - the method of the incoming request
- `url` - the URL of the incoming request
-- `originalUrl` - similar to `url`, this allows you to access the
- original `url` in case of internal re-routing
+- `originalUrl` - similar to `url`, this allows you to access the
+ original `url` in case of internal re-routing
- `is404` - true if request is being handled by 404 handler, false if it is not
- `socket` - the underlying connection of the incoming request
- `context` - Deprecated, use `request.routeOptions.config` instead.
A Fastify internal object. You should not use
-it directly or modify it. It is useful to access one special key:
+it directly or modify it. It is useful to access one special key:
- `context.config` - The route [`config`](./Routes.md#routes-config) object.
- `routeOptions` - The route [`option`](./Routes.md#routes-options) object
- `bodyLimit` - either server limit or route limit
@@ -44,15 +44,15 @@ it directly or modify it. It is useful to access one special key:
- `method` - the http method for the route
- `url` - the path of the URL to match this route
- `handler` - the handler for this route
- - `attachValidation` - attach `validationError` to request
+ - `attachValidation` - attach `validationError` to request
(if there is a schema defined)
- `logLevel` - log level defined for this route
- `schema` - the JSON schemas definition for this route
- `version` - a semver compatible string that defines the version of the endpoint
- `exposeHeadRoute` - creates a sibling HEAD route for any GET routes
- - `prefixTrailingSlash` - string used to determine how to handle passing /
+ - `prefixTrailingSlash` - string used to determine how to handle passing /
as a route with a prefix.
-- [.getValidationFunction(schema | httpPart)](#getvalidationfunction) -
+- [.getValidationFunction(schema | httpPart)](#getvalidationfunction) -
Returns a validation function for the specified schema or http part,
if any of either are set or cached.
- [.compileValidationSchema(schema, [httpPart])](#compilevalidationschema) -
@@ -117,7 +117,7 @@ fastify.post('/:params', options, function (request, reply) {
### .getValidationFunction(schema | httpPart)
-By calling this function using a provided `schema` or `httpPart`,
+By calling this function using a provided `schema` or `httpPart`,
it will return a `validation` function that can be used to
validate diverse inputs. It returns `undefined` if no
serialization function was found using either of the provided inputs.
@@ -128,12 +128,12 @@ are assigned to errors
```js
const validate = request
.getValidationFunction({
- type: 'object',
- properties: {
- foo: {
- type: 'string'
- }
- }
+ type: 'object',
+ properties: {
+ foo: {
+ type: 'string'
+ }
+ }
})
console.log(validate({ foo: 'bar' })) // true
console.log(validate.errors) // null
@@ -168,12 +168,12 @@ are assigned to errors
```js
const validate = request
.compileValidationSchema({
- type: 'object',
- properties: {
- foo: {
- type: 'string'
- }
- }
+ type: 'object',
+ properties: {
+ foo: {
+ type: 'string'
+ }
+ }
})
console.log(validate({ foo: 'bar' })) // true
console.log(validate.errors) // null
@@ -182,12 +182,12 @@ console.log(validate.errors) // null
const validate = request
.compileValidationSchema({
- type: 'object',
- properties: {
- foo: {
- type: 'string'
- }
- }
+ type: 'object',
+ properties: {
+ foo: {
+ type: 'string'
+ }
+ }
}, 200)
console.log(validate({ hello: 'world' })) // false
console.log(validate.errors) // validation errors
@@ -217,7 +217,7 @@ const schema1 = {
```
*Not*
-```js
+```js
const validate = request.compileValidationSchema(schema1)
// Later on...
@@ -252,25 +252,25 @@ function will be compiled, forwarding the `httpPart` if provided.
```js
request
- .validateInput({ foo: 'bar'}, {
- type: 'object',
- properties: {
- foo: {
- type: 'string'
- }
- }
+ .validateInput({ foo: 'bar'}, {
+ type: 'object',
+ properties: {
+ foo: {
+ type: 'string'
+ }
+ }
}) // true
// or
request
.validateInput({ foo: 'bar'}, {
- type: 'object',
- properties: {
- foo: {
- type: 'string'
- }
- }
+ type: 'object',
+ properties: {
+ foo: {
+ type: 'string'
+ }
+ }
}, 'body') // true
// or
diff --git a/docs/Reference/Routes.md b/docs/Reference/Routes.md
index 9a030f20c7..94a3b5912b 100644
--- a/docs/Reference/Routes.md
+++ b/docs/Reference/Routes.md
@@ -93,16 +93,16 @@ fastify.route(options)
* `childLoggerFactory(logger, binding, opts, rawReq)`: a custom factory function
that will be called to produce a child logger instance for every request.
See [`childLoggerFactory`](./Server.md#childloggerfactory) for more info.
- Overrides the default logger factory, and anything set by
+ Overrides the default logger factory, and anything set by
[`setChildLoggerFactory`](./Server.md#setchildloggerfactory), for requests to
- the route. To access the default factory, you can access
+ the route. To access the default factory, you can access
`instance.childLoggerFactory`. Note that this will point to Fastify's default
`childLoggerFactory` only if a plugin hasn't overridden it already.
* `validatorCompiler({ schema, method, url, httpPart })`: function that builds
schemas for request validations. See the [Validation and
Serialization](./Validation-and-Serialization.md#schema-validator)
documentation.
-* `serializerCompiler({ { schema, method, url, httpStatus, contentType } })`:
+* `serializerCompiler({ { schema, method, url, httpStatus, contentType } })`:
function that builds schemas for response serialization. See the [Validation and
Serialization](./Validation-and-Serialization.md#schema-serializer)
documentation.
@@ -121,8 +121,8 @@ fastify.route(options)
* `version`: a [semver](https://semver.org/) compatible string that defined the
version of the endpoint. [Example](#version-constraints).
* `constraints`: defines route restrictions based on request properties or
- values, enabling customized matching using
- [find-my-way](https://github.com/delvedor/find-my-way) constraints. Includes
+ values, enabling customized matching using
+ [find-my-way](https://github.com/delvedor/find-my-way) constraints. Includes
built-in `version` and `host` constraints, with support for custom constraint
strategies.
* `prefixTrailingSlash`: string used to determine how to handle passing `/` as a
@@ -796,10 +796,10 @@ const secret = {
> inside the callback. If the error is not preventable, it is recommended to provide
> a custom `frameworkErrors` handler to deal with it. Otherwise, you route selection
> may break or expose sensitive information to attackers.
->
+>
> ```js
> const Fastify = require('fastify')
->
+>
> const fastify = Fastify({
> frameworkErrors: function (err, res, res) {
> if (err instanceof Fastify.errorCodes.FST_ERR_ASYNC_CONSTRAINT) {
diff --git a/docs/Reference/Server.md b/docs/Reference/Server.md
index 8376ae88cb..21c5afe962 100644
--- a/docs/Reference/Server.md
+++ b/docs/Reference/Server.md
@@ -152,7 +152,7 @@ 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.
+use.
When `serverFactory` option is specified this option is ignored.
@@ -203,7 +203,7 @@ ignored.
Defines the maximum number of milliseconds for receiving the entire request from
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.
+to understand the effect of this option.
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
@@ -387,12 +387,12 @@ attaching custom `onRequest` and `onResponse` hooks.
The other log entries that will be disabled are:
- an error log written by the default `onResponse` hook on reply callback errors
-- the error and info logs written by the `defaultErrorHandler`
+- the error and info logs written by the `defaultErrorHandler`
on error management
-- the info log written by the `fourOhFour` handler when a
+- the info log written by the `fourOhFour` handler when a
non existent route is requested
-Other log messages emitted by Fastify will stay enabled,
+Other log messages emitted by Fastify will stay enabled,
like deprecation warnings and messages
emitted when requests are received while the server is closing.
@@ -456,7 +456,7 @@ Please note that setting this option to `false` goes against
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.
@@ -493,7 +493,7 @@ Setting `requestIdHeader` to `true` will set the `requestIdHeader` to
Setting `requestIdHeader` to a non-empty string will use
the specified string as the `requestIdHeader`.
By default `requestIdHeader` is set to `false` and will immediately use [genReqId](#genreqid).
-Setting `requestIdHeader` to an empty String (`""`) will set the
+Setting `requestIdHeader` to an empty String (`""`) will set the
requestIdHeader to `false`.
+ Default: `false`
@@ -827,7 +827,7 @@ is an instance-wide configuration.
// @param {object} req The raw Node.js HTTP request, not the `FastifyRequest` object.
// @this Fastify The root Fastify instance (not an encapsulated instance).
// @returns {string} The path that the request should be mapped to.
-function rewriteUrl (req) {
+function rewriteUrl (req) {
if (req.url === '/hi') {
this.log.debug({ originalUrl: req.url, url: '/hello' }, 'rewrite url');
return '/hello'
@@ -948,7 +948,7 @@ Starts the server and internally waits for the `.ready()` event. The signature
is `.listen([options][, callback])`. Both the `options` object and the
`callback` parameters extend the [Node.js
core](https://nodejs.org/api/net.html#serverlistenoptions-callback) options
-object. Thus, all core options are available with the following additional
+object. Thus, all core options are available with the following additional
Fastify specific options:
### `listenTextResolver`
@@ -956,13 +956,13 @@ Fastify specific options:
Set an optional resolver for the text to log after server has been successfully
started.
-It is possible to override the default `Server listening at [address]` log
+It is possible to override the default `Server listening at [address]` log
entry using this option.
```js
-server.listen({
- port: 9080,
- listenTextResolver: (address) => { return `Prometheus metrics server is listening at ${address}` }
+server.listen({
+ port: 9080,
+ listenTextResolver: (address) => { return `Prometheus metrics server is listening at ${address}` }
})
```
@@ -1090,7 +1090,7 @@ 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 the payload. `url` and `method` are mandatory fields. It
+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.
@@ -1110,8 +1110,8 @@ if (routeExists === false) {
Method to retrieve a route already registered to the internal router. It
-expects an object as the payload. `url` and `method` are mandatory fields. It
-is possible to also specify `constraints`.
+expects an object as the payload. `url` and `method` are mandatory fields. It
+is possible to also specify `constraints`.
The method returns a route object or `null` if the route cannot be found.
```js
@@ -1351,7 +1351,7 @@ 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**
+> **Note**
> [`setReplySerializer`](#set-reply-serializer) has priority if set!
#### validatorCompiler
@@ -1966,7 +1966,7 @@ The properties that can currently be exposed are:
- requestIdHeader
- requestIdLogLabel
- http2SessionTimeout
-- useSemicolonDelimiter
+- useSemicolonDelimiter
```js
const { readFileSync } = require('node:fs')
diff --git a/docs/Reference/TypeScript.md b/docs/Reference/TypeScript.md
index 18297ff277..7176192bc6 100644
--- a/docs/Reference/TypeScript.md
+++ b/docs/Reference/TypeScript.md
@@ -182,7 +182,7 @@ route-level `request` object.
admin"}`
🎉 Good work, now you can define interfaces for each route and have strictly
-typed request and reply instances. Other parts of the Fastify type system rely
+typed request and reply instances. Other parts of the Fastify type system rely
on generic properties. Make sure to reference the detailed type system
documentation below to learn more about what is available.
@@ -877,7 +877,7 @@ a more detailed http server walkthrough.
import path from 'path'
import fastify from 'fastify'
```
-2. Perform the following steps before setting up a Fastify HTTPS server
+2. Perform the following steps before setting up a Fastify HTTPS server
to create the `key.pem` and `cert.pem` files:
```sh
openssl genrsa -out key.pem
diff --git a/lib/error-serializer.js b/lib/error-serializer.js
index 71fb87b9ce..5fb7b8146e 100644
--- a/lib/error-serializer.js
+++ b/lib/error-serializer.js
@@ -24,15 +24,15 @@
const JSON_STR_EMPTY_ARRAY = JSON_STR_BEGIN_ARRAY + JSON_STR_END_ARRAY
const JSON_STR_EMPTY_STRING = JSON_STR_QUOTE + JSON_STR_QUOTE
const JSON_STR_NULL = 'null'
-
-
-
+
+
+
// #
function anonymous0 (input) {
const obj = (input && typeof input.toJSON === 'function')
? input.toJSON()
: input
-
+
if (obj === null) return JSON_STR_EMPTY_OBJECT
let value
@@ -50,7 +50,7 @@ let addComma = false
if (value !== undefined) {
!addComma && (addComma = true) || (json += JSON_STR_COMMA)
json += "\"code\":"
-
+
if (typeof value !== 'string') {
if (value === null) {
json += JSON_STR_EMPTY_STRING
@@ -64,14 +64,14 @@ let addComma = false
} else {
json += serializer.asString(value)
}
-
+
}
value = obj["error"]
if (value !== undefined) {
!addComma && (addComma = true) || (json += JSON_STR_COMMA)
json += "\"error\":"
-
+
if (typeof value !== 'string') {
if (value === null) {
json += JSON_STR_EMPTY_STRING
@@ -85,14 +85,14 @@ let addComma = false
} else {
json += serializer.asString(value)
}
-
+
}
value = obj["message"]
if (value !== undefined) {
!addComma && (addComma = true) || (json += JSON_STR_COMMA)
json += "\"message\":"
-
+
if (typeof value !== 'string') {
if (value === null) {
json += JSON_STR_EMPTY_STRING
@@ -106,15 +106,15 @@ let addComma = false
} else {
json += serializer.asString(value)
}
-
+
}
return json + JSON_STR_END_OBJECT
-
+
}
-
+
const main = anonymous0
return main
-
+
}(validator, serializer)
/* c8 ignore stop */
diff --git a/test/allow-unsafe-regex.test.js b/test/allow-unsafe-regex.test.js
index 6b9b784812..5f48eed8c3 100644
--- a/test/allow-unsafe-regex.test.js
+++ b/test/allow-unsafe-regex.test.js
@@ -112,7 +112,7 @@ test('allow unsafe regex allow unsafe', (t, done) => {
}, (err, response, body) => {
t.assert.ifError(err)
t.assert.strictEqual(response.statusCode, 200)
- t.assert.deepEqual(JSON.parse(body), {
+ t.assert.deepStrictEqual(JSON.parse(body), {
foo: '1234'
})
done()
diff --git a/test/buffer.test.js b/test/buffer.test.js
index c06d634a61..2f09456ead 100644
--- a/test/buffer.test.js
+++ b/test/buffer.test.js
@@ -25,7 +25,7 @@ test('Buffer test', async t => {
t.assert.ifError(response.error)
t.assert.strictEqual(response.statusCode, 200)
- t.assert.deepEqual(response.payload.toString(), '{"hello":"world"}')
+ t.assert.deepStrictEqual(response.payload.toString(), '{"hello":"world"}')
})
await test('should return 400 if the body is empty', async t => {
@@ -42,7 +42,7 @@ test('Buffer test', async t => {
t.assert.ifError(response.error)
t.assert.strictEqual(response.statusCode, 400)
- t.assert.deepEqual(JSON.parse(response.payload.toString()), {
+ t.assert.deepStrictEqual(JSON.parse(response.payload.toString()), {
error: 'Bad Request',
code: 'FST_ERR_CTP_EMPTY_JSON_BODY',
message: 'Body cannot be empty when content-type is set to \'application/json\'',
diff --git a/test/bundler/README.md b/test/bundler/README.md
index e4040bfb8b..d0f7c46eee 100644
--- a/test/bundler/README.md
+++ b/test/bundler/README.md
@@ -1,12 +1,12 @@
# Bundlers test stack
-In some cases, developers bundle their apps for several targets such as serverless applications.
-Even if it's not recommended by Fastify team; we need to ensure we do not break the build process.
+In some cases, developers bundle their apps for several targets such as serverless applications.
+Even if it's not recommended by Fastify team; we need to ensure we do not break the build process.
Please note this might result in features behaving differently, like the version handling check for plugins.
## Test bundlers
-The bundler test stack has been defined separately from the rest of the Unit testing stack because it's not a
+The bundler test stack has been defined separately from the rest of the Unit testing stack because it's not a
part of the fastify lib itself. Note that the tests run in CI only on NodeJs LTS version.
Developers do not need to install every bundler to run unit tests.
@@ -23,7 +23,7 @@ stack dependencies. See:
## Bundler test development
-To not break the fastify unit testing stack please name test files like this `*-test.js` and not `*.test.js`,
+To not break the fastify unit testing stack please name test files like this `*-test.js` and not `*.test.js`,
otherwise it will be targeted by the regular expression used for unit tests for fastify.
-Tests need to ensure the build process works and the fastify application can be run,
+Tests need to ensure the build process works and the fastify application can be run,
no need to go in deep testing unless an issue is raised.
diff --git a/test/case-insensitive.test.js b/test/case-insensitive.test.js
index 8604154b5a..b71c34db35 100644
--- a/test/case-insensitive.test.js
+++ b/test/case-insensitive.test.js
@@ -25,7 +25,7 @@ test('case insensitive', (t, done) => {
}, (err, response, body) => {
t.assert.ifError(err)
t.assert.strictEqual(response.statusCode, 200)
- t.assert.deepEqual(JSON.parse(body), {
+ t.assert.deepStrictEqual(JSON.parse(body), {
hello: 'world'
})
done()
@@ -54,7 +54,7 @@ test('case insensitive inject', (t, done) => {
}, (err, response) => {
t.assert.ifError(err)
t.assert.strictEqual(response.statusCode, 200)
- t.assert.deepEqual(JSON.parse(response.payload), {
+ t.assert.deepStrictEqual(JSON.parse(response.payload), {
hello: 'world'
})
done()
@@ -84,7 +84,7 @@ test('case insensitive (parametric)', (t, done) => {
}, (err, response, body) => {
t.assert.ifError(err)
t.assert.strictEqual(response.statusCode, 200)
- t.assert.deepEqual(JSON.parse(body), {
+ t.assert.deepStrictEqual(JSON.parse(body), {
hello: 'world'
})
done()
@@ -114,7 +114,7 @@ test('case insensitive (wildcard)', (t, done) => {
}, (err, response, body) => {
t.assert.ifError(err)
t.assert.strictEqual(response.statusCode, 200)
- t.assert.deepEqual(JSON.parse(body), {
+ t.assert.deepStrictEqual(JSON.parse(body), {
hello: 'world'
})
done()
diff --git a/test/check.test.js b/test/check.test.js
index 0d3dd3a60c..e932b4a05f 100644
--- a/test/check.test.js
+++ b/test/check.test.js
@@ -72,7 +72,6 @@ const options = {
}
const handler = (request, reply) => {
- console.log('in handler')
if (request.body.id === '400') {
return reply.status(400).send({
statusCode: 400,
@@ -125,7 +124,7 @@ test('serialize the response for a Bad Request error, as defined on the schema',
}, (err, response, body) => {
t.assert.ifError(err)
t.assert.strictEqual(response.statusCode, 400)
- t.assert.deepEqual(body, {
+ t.assert.deepStrictEqual(body, {
statusCode: 400,
error: 'Bad Request',
message: 'body must be object'
diff --git a/test/conditional-pino.test.js b/test/conditional-pino.test.js
index a6705c1b92..4bce8eb9c8 100644
--- a/test/conditional-pino.test.js
+++ b/test/conditional-pino.test.js
@@ -21,7 +21,7 @@ test("pino is require'd if logger is passed", t => {
logger: true
})
- t.assert.notEqual(require.cache[require.resolve('pino')], undefined)
+ t.assert.notStrictEqual(require.cache[require.resolve('pino')], undefined)
})
test("pino is require'd if loggerInstance is passed", t => {
@@ -43,5 +43,5 @@ test("pino is require'd if loggerInstance is passed", t => {
loggerInstance
})
- t.assert.notEqual(require.cache[require.resolve('pino')], undefined)
+ t.assert.notStrictEqual(require.cache[require.resolve('pino')], undefined)
})
diff --git a/test/encapsulated-error-handler.test.js b/test/encapsulated-error-handler.test.js
index 88927324af..48c29d3e8e 100644
--- a/test/encapsulated-error-handler.test.js
+++ b/test/encapsulated-error-handler.test.js
@@ -1,6 +1,6 @@
'use strict'
-const { test } = require('tap')
+const { test } = require('node:test')
const Fastify = require('..')
// Because of how error handlers wrap things, following the control flow can be tricky
@@ -13,7 +13,7 @@ test('encapsulates an asynchronous error handler', async t => {
fastify.register(async function (fastify) {
fastify.setErrorHandler(async function a (err) {
// 3. the inner error handler catches the error, and throws a new error
- t.equal(err.message, 'from_endpoint')
+ t.assert.strictEqual(err.message, 'from_endpoint')
throw new Error('from_inner')
})
fastify.get('/encapsulated', async () => {
@@ -24,7 +24,7 @@ test('encapsulates an asynchronous error handler', async t => {
fastify.setErrorHandler(async function b (err) {
// 4. the outer error handler catches the error thrown by the inner error handler
- t.equal(err.message, 'from_inner')
+ t.assert.strictEqual(err.message, 'from_inner')
// 5. the outer error handler throws a new error
throw new Error('from_outer')
})
@@ -32,7 +32,7 @@ test('encapsulates an asynchronous error handler', async t => {
// 1. the endpoint is called
const res = await fastify.inject('/encapsulated')
// 6. the default error handler returns the error from the outer error handler
- t.equal(res.json().message, 'from_outer')
+ t.assert.strictEqual(res.json().message, 'from_outer')
})
// See discussion in https://github.com/fastify/fastify/pull/5222#discussion_r1432573655
@@ -43,7 +43,7 @@ test('encapsulates a synchronous error handler', async t => {
fastify.register(async function (fastify) {
fastify.setErrorHandler(function a (err) {
// 3. the inner error handler catches the error, and throws a new error
- t.equal(err.message, 'from_endpoint')
+ t.assert.strictEqual(err.message, 'from_endpoint')
throw new Error('from_inner')
})
fastify.get('/encapsulated', async () => {
@@ -54,7 +54,7 @@ test('encapsulates a synchronous error handler', async t => {
fastify.setErrorHandler(async function b (err) {
// 4. the outer error handler catches the error thrown by the inner error handler
- t.equal(err.message, 'from_inner')
+ t.assert.strictEqual(err.message, 'from_inner')
// 5. the outer error handler throws a new error
throw new Error('from_outer')
})
@@ -62,7 +62,7 @@ test('encapsulates a synchronous error handler', async t => {
// 1. the endpoint is called
const res = await fastify.inject('/encapsulated')
// 6. the default error handler returns the error from the outer error handler
- t.equal(res.json().message, 'from_outer')
+ t.assert.strictEqual(res.json().message, 'from_outer')
})
test('onError hook nested', async t => {
@@ -72,7 +72,7 @@ test('onError hook nested', async t => {
fastify.register(async function (fastify) {
fastify.setErrorHandler(async function a (err) {
// 4. the inner error handler catches the error, and throws a new error
- t.equal(err.message, 'from_endpoint')
+ t.assert.strictEqual(err.message, 'from_endpoint')
throw new Error('from_inner')
})
fastify.get('/encapsulated', async () => {
@@ -83,20 +83,20 @@ test('onError hook nested', async t => {
fastify.setErrorHandler(async function b (err) {
// 5. the outer error handler catches the error thrown by the inner error handler
- t.equal(err.message, 'from_inner')
+ t.assert.strictEqual(err.message, 'from_inner')
// 6. the outer error handler throws a new error
throw new Error('from_outer')
})
fastify.addHook('onError', async function (request, reply, err) {
// 3. the hook receives the error
- t.equal(err.message, 'from_endpoint')
+ t.assert.strictEqual(err.message, 'from_endpoint')
})
// 1. the endpoint is called
const res = await fastify.inject('/encapsulated')
// 7. the default error handler returns the error from the outer error handler
- t.equal(res.json().message, 'from_outer')
+ t.assert.strictEqual(res.json().message, 'from_outer')
})
// See https://github.com/fastify/fastify/issues/5220
@@ -107,7 +107,7 @@ test('encapuslates an error handler, for errors thrown in hooks', async t => {
fastify.register(async function (fastify) {
fastify.setErrorHandler(function a (err) {
// 3. the inner error handler catches the error, and throws a new error
- t.equal(err.message, 'from_hook')
+ t.assert.strictEqual(err.message, 'from_hook')
throw new Error('from_inner')
})
fastify.addHook('onRequest', async () => {
@@ -119,7 +119,7 @@ test('encapuslates an error handler, for errors thrown in hooks', async t => {
fastify.setErrorHandler(function b (err) {
// 4. the outer error handler catches the error thrown by the inner error handler
- t.equal(err.message, 'from_inner')
+ t.assert.strictEqual(err.message, 'from_inner')
// 5. the outer error handler throws a new error
throw new Error('from_outer')
})
@@ -127,7 +127,7 @@ test('encapuslates an error handler, for errors thrown in hooks', async t => {
// 1. the endpoint is called
const res = await fastify.inject('/encapsulated')
// 6. the default error handler returns the error from the outer error handler
- t.equal(res.json().message, 'from_outer')
+ t.assert.strictEqual(res.json().message, 'from_outer')
})
// See https://github.com/fastify/fastify/issues/5220
@@ -153,7 +153,7 @@ test('encapuslates many synchronous error handlers that rethrow errors', async t
} else if (depth === 0) {
fastify.setErrorHandler(function a (err) {
// 3. innermost error handler catches the error, and throws a new error
- t.equal(err.message, 'from_route')
+ t.assert.strictEqual(err.message, 'from_route')
throw new Error(`from_handler_${depth}`)
})
fastify.get('/encapsulated', async () => {
@@ -163,7 +163,7 @@ test('encapuslates many synchronous error handlers that rethrow errors', async t
} else {
fastify.setErrorHandler(function d (err) {
// 4 to {DEPTH+4}. error handlers each catch errors, and then throws a new error
- t.equal(err.message, `from_handler_${depth - 1}`)
+ t.assert.strictEqual(err.message, `from_handler_${depth - 1}`)
throw new Error(`from_handler_${depth}`)
})
@@ -179,7 +179,7 @@ test('encapuslates many synchronous error handlers that rethrow errors', async t
// 1. the endpoint is called
const res = await fastify.inject('/encapsulated')
// {DEPTH+5}. the default error handler returns the error from the outermost error handler
- t.equal(res.json().message, `from_handler_${DEPTH}`)
+ t.assert.strictEqual(res.json().message, `from_handler_${DEPTH}`)
})
// See https://github.com/fastify/fastify/issues/5220
@@ -207,7 +207,7 @@ test('encapuslates many asynchronous error handlers that rethrow errors', async
} else if (depth === 0) {
fastify.setErrorHandler(async function a (err) {
// 3. innermost error handler catches the error, and throws a new error
- t.equal(err.message, 'from_route')
+ t.assert.strictEqual(err.message, 'from_route')
throw new Error(`from_handler_${depth}`)
})
fastify.get('/encapsulated', async () => {
@@ -217,7 +217,7 @@ test('encapuslates many asynchronous error handlers that rethrow errors', async
} else {
fastify.setErrorHandler(async function m (err) {
// 4 to {DEPTH+4}. error handlers each catch errors, and then throws a new error
- t.equal(err.message, `from_handler_${depth - 1}`)
+ t.assert.strictEqual(err.message, `from_handler_${depth - 1}`)
throw new Error(`from_handler_${depth}`)
})
@@ -233,5 +233,5 @@ test('encapuslates many asynchronous error handlers that rethrow errors', async
// 1. the endpoint is called
const res = await fastify.inject('/encapsulated')
// {DEPTH+5}. the default error handler returns the error from the outermost error handler
- t.equal(res.json().message, `from_handler_${DEPTH}`)
+ t.assert.strictEqual(res.json().message, `from_handler_${DEPTH}`)
})
diff --git a/test/http-methods/head.test.js b/test/http-methods/head.test.js
index f9d39b58bf..0b4d169a3d 100644
--- a/test/http-methods/head.test.js
+++ b/test/http-methods/head.test.js
@@ -122,7 +122,6 @@ test('shorthand - should set get and head route in the same api call', t => {
t.assert.ok(true)
} catch (e) {
- console.log(e)
t.assert.fail()
}
})
@@ -147,7 +146,6 @@ test('shorthand - head, querystring schema', t => {
})
t.assert.ok(true)
} catch (e) {
- console.log(e)
t.assert.fail()
}
})
@@ -160,7 +158,6 @@ test('missing schema - head', t => {
})
t.assert.ok(true)
} catch (e) {
- console.log(e)
t.assert.fail()
}
})
diff --git a/test/middleware.test.js b/test/middleware.test.js
index 990c505d22..05da956673 100644
--- a/test/middleware.test.js
+++ b/test/middleware.test.js
@@ -1,6 +1,6 @@
'use strict'
-const { test } = require('tap')
+const { test } = require('node:test')
const Fastify = require('..')
const {
FST_ERR_DEC_ALREADY_PRESENT
@@ -10,7 +10,7 @@ test('Should be able to override the default use API', t => {
t.plan(1)
const fastify = Fastify()
fastify.decorate('use', () => true)
- t.equal(fastify.use(), true)
+ t.assert.strictEqual(fastify.use(), true)
})
test('Cannot decorate use twice', t => {
@@ -20,17 +20,16 @@ test('Cannot decorate use twice', t => {
try {
fastify.decorate('use', () => true)
} catch (err) {
- t.ok(err instanceof FST_ERR_DEC_ALREADY_PRESENT)
+ t.assert.ok(err instanceof FST_ERR_DEC_ALREADY_PRESENT)
}
})
test('Encapsulation works', t => {
- t.plan(1)
const fastify = Fastify()
fastify.register((instance, opts, done) => {
instance.decorate('use', () => true)
- t.equal(instance.use(), true)
+ t.assert.strictEqual(instance.use(), true)
done()
})
diff --git a/test/request-timeout.test.js b/test/request-timeout.test.js
index faf5455dc2..995dc38404 100644
--- a/test/request-timeout.test.js
+++ b/test/request-timeout.test.js
@@ -42,12 +42,12 @@ test('requestTimeout should be set', async (t) => {
t.plan(1)
const initialConfig = Fastify({ requestTimeout: 5000 }).initialConfig
- t.assert.deepEqual(initialConfig.requestTimeout, 5000)
+ t.assert.strictEqual(initialConfig.requestTimeout, 5000)
})
test('requestTimeout should 0', async (t) => {
t.plan(1)
const initialConfig = Fastify().initialConfig
- t.assert.deepEqual(initialConfig.requestTimeout, 0)
+ t.assert.strictEqual(initialConfig.requestTimeout, 0)
})
diff --git a/test/route.3.test.js b/test/route.3.test.js
index f329ff8e4f..d324b972be 100644
--- a/test/route.3.test.js
+++ b/test/route.3.test.js
@@ -5,7 +5,7 @@ const joi = require('joi')
const Fastify = require('..')
test('does not mutate joi schemas', (t, done) => {
- t.plan(4)
+ t.plan(5)
const fastify = Fastify()
function validatorCompiler ({ schema, method, url, httpPart }) {
@@ -31,7 +31,8 @@ test('does not mutate joi schemas', (t, done) => {
params: { an_id: joi.number() }
},
handler (req, res) {
- t.assert.deepEqual(req.params, { an_id: 42 })
+ t.assert.strictEqual(Object.keys(req.params).length, 1)
+ t.assert.strictEqual(req.params.an_id, '42')
res.send({ hello: 'world' })
}
})
diff --git a/test/wrapThenable.test.js b/test/wrap-thenable.test.js
similarity index 100%
rename from test/wrapThenable.test.js
rename to test/wrap-thenable.test.js