Skip to content

Commit c566cdd

Browse files
Merge pull request #2589 from Tony133/docs/update-middlewares
docs(): update middlewares for fastify
2 parents f904a49 + f122f3a commit c566cdd

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

content/middlewares.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ Nest middleware are, by default, equivalent to [express](https://expressjs.com/e
2020

2121
You implement custom Nest middleware in either a function, or in a class with an `@Injectable()` decorator. The class should implement the `NestMiddleware` interface, while the function does not have any special requirements. Let's start by implementing a simple middleware feature using the class method.
2222

23+
> warning **Warning** `Express` and `fastify` handle middleware differently and provide different method signatures, read more [here](/techniques/performance#middleware).
24+
25+
2326
```typescript
2427
@@filename(logger.middleware)
2528
import { Injectable, NestMiddleware } from '@nestjs/common';

content/techniques/performance.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,35 @@ You can pass options into the Fastify constructor through the `FastifyAdapter` c
7474
new FastifyAdapter({ logger: true });
7575
```
7676

77+
78+
#### Middleware
79+
80+
Middleware functions retrieve the raw `req` and `res` objects instead of Fastify's wrappers. This is how the `middie` package works (that's used under the hood) and `fastify` - check out this [page](https://www.fastify.io/docs/latest/Reference/Middleware/) for more information,
81+
82+
```typescript
83+
@@filename(logger.middleware)
84+
import { Injectable, NestMiddleware } from '@nestjs/common';
85+
import { FastifyRequest, FastifyReply } from 'fastify';
86+
87+
@Injectable()
88+
export class LoggerMiddleware implements NestMiddleware {
89+
use(req: FastifyRequest['raw'], res: FastifyReply['raw'], next: () => void) {
90+
console.log('Request...');
91+
next();
92+
}
93+
}
94+
@@switch
95+
import { Injectable } from '@nestjs/common';
96+
97+
@Injectable()
98+
export class LoggerMiddleware {
99+
use(req, res, next) {
100+
console.log('Request...');
101+
next();
102+
}
103+
}
104+
```
105+
77106
#### Example
78107

79108
A working example is available [here](https://github.com/nestjs/nest/tree/master/sample/10-fastify).

0 commit comments

Comments
 (0)