Middleware not working with GraphQL and Fastify
Is there an existing issue for this?
- [X] I have searched the existing issues
Current behavior
When using a combination of @nestjs/graphql @nestjs/platform-fastify and apollo-server-fastify, middlewares does not seems to apply.
Middleware to test:
import { Injectable, NestMiddleware } from '@nestjs/common';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: any) {
console.log('Request...');
next();
}
}
Applying middleware in app.module
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggerMiddleware).forRoutes('(.*)');
}
Making a request to a "REST" route works correctly, middleware logs "Request..."
curl localhost:3000

But not when using the graphql endpoint.
curl -g \
-X POST \
-H "Content-Type: application/json" \
-d '{"query":"query{get {hello}}"}' \
localhost:3000/graphql
{"data":{"get":{"hello":"world"}}}

Nothing is logged.
If you switch packages to the express one: @nestjs/platform-express and apollo-server-express it works fine.
Bonus
If the fastify dependency is updated to 3.27.1 then the "REST" endpoint while not work either.
Minimum reproduction code
https://github.com/romainbrancourt/nestjs-graphql-fastify-middleware
Steps to reproduce
- yarn install
- Testing graphql endpoint
curl -g \
-X POST \
-H "Content-Type: application/json" \
-d '{"query":"query{get {hello}}"}' \
localhost:3000/graphql
{"data":{"get":{"hello":"world"}}}
- Testing rest endpoint
curl localhost:3000
Expected behavior
Middleware should run in both cases : REST and Graphql endpoint.
Package
- [ ] I don't know. Or some 3rd-party package
- [ ]
@nestjs/common - [ ]
@nestjs/core - [ ]
@nestjs/microservices - [ ]
@nestjs/platform-express - [X]
@nestjs/platform-fastify - [ ]
@nestjs/platform-socket.io - [ ]
@nestjs/platform-ws - [ ]
@nestjs/testing - [ ]
@nestjs/websockets - [ ] Other (see below)
Other package
fastify, apollo-server-fastify
NestJS version
8.2.6
Packages versions
"@nestjs/graphql": "^9.1.2",
"@nestjs/platform-fastify": "^8.2.6",
"apollo-server-fastify": "^3.6.2",
"fastify": "3.27.0",
"graphql": "^15.7.2",
Node.js version
16.10.0
In which operating systems have you tested?
- [X] macOS
- [ ] Windows
- [ ] Linux
Other
No response
I had:
"@nestjs/platform-fastify": "8.0.4",
"fastify": "3.19.1"
Updated to:
"@nestjs/platform-fastify": "8.2.6",
"fastify": "3.24.0"
And having the same problem as author. I tried to downgrade a little bit. Nothing works till I reach initial values.
Fixed in the latest version of "@nestjs/platform-fastify" (8.3.0)
Awesome thanks !
It looks like the issue is here again, it works for anything but not with graphql requests.
"@nestjs/platform-fastify": "10.2.8"
Edit: It's not the same issue, apparently using setGlobalPrefix() prevent Middleware to be applied to GraphQL. I had to exclude path 'graphql' from setGlobalPrefix.
Documentation doesn't mention it I think.