Skip to content

Commit 459bbc8

Browse files
committed
docs(): update middlewares
1 parent 05d6294 commit 459bbc8

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

content/middlewares.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ 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` treat middleware differently and have different syntaxes for middleware.
24+
25+
#### Use with Express
26+
2327
```typescript
2428
@@filename(logger.middleware)
2529
import { Injectable, NestMiddleware } from '@nestjs/common';
@@ -44,6 +48,36 @@ export class LoggerMiddleware {
4448
}
4549
```
4650

51+
#### Use with Fastify
52+
53+
The middleware with `fastify` "works", but it retrieves only the raw `req` and `res` objects and not the fastify wrapper. This is a side effect of how `middie` works and `fastify` already talks about it in its documents for more information see [here](https://www.fastify.io/docs/latest/Reference/Middleware/).
54+
55+
> warning **Warning** The middleware in `fastify` has an IncomingMessage request type `FastifyRequest['raw']` and a ServerResponse type `FastifyReply['raw']`.
56+
57+
```typescript
58+
@@filename(logger.middleware)
59+
import { Injectable, NestMiddleware } from '@nestjs/common';
60+
import { FastifyRequest, FastifyReply } from 'fastify';
61+
62+
@Injectable()
63+
export class LoggerMiddleware implements NestMiddleware {
64+
use(req: FastifyRequest, res: FastifyReply, next: () => void) {
65+
console.log('Request...');
66+
next();
67+
}
68+
}
69+
@@switch
70+
import { Injectable } from '@nestjs/common';
71+
72+
@Injectable()
73+
export class LoggerMiddleware {
74+
use(req, res, next) {
75+
console.log('Request...');
76+
next();
77+
}
78+
}
79+
```
80+
4781
#### Dependency injection
4882

4983
Nest middleware fully supports Dependency Injection. Just as with providers and controllers, they are able to **inject dependencies** that are available within the same module. As usual, this is done through the `constructor`.

0 commit comments

Comments
 (0)