-
-
Notifications
You must be signed in to change notification settings - Fork 8.1k
Description
I'm submitting a...
[x] Feature request
Current behavior
When registering middlewares via consumer.apply(middleware).....
they'll run always before the controller handler.
Expected behavior
Ability to run middleware after the route handler.
Environment
Nest version: 4.4.2
What is the motivation / use case for changing the behavior?
I have a use case where I'm using nestjs to create an API gateway. The gateway itself has some authentication / session management endpoints whose logic is implemented in controllers.
Their route is /v1/auth/*
.
All routes which are not handled by those controllers e.g. /v1/something
should be proxied to a set of other microservices. In the previous plain express app we had a simple middleware for that. Without getting into details, this middleware more or less pipes the request to another microservice via request
and contains a line like this req.pipe(request('http://targetUrl').pipe(res)
.
Now the problem in nestjs is that when registering middlewares they always run before the controllers route handler, but I need them to run only afterwards, if the request didn't get handled the /v1/auth/*
handler already.
My solution thoughts so far have been:
- turn the proxy middleware into a route handler itself. e.g.:
@Controller()
export class ProxyController {
constructor(@Inject(configProviderToken) private config: Config) {}
@All('*')
async proxyRequest(@Req() req, @Res() res, @Next() next) { }
that kind of works but doesn't feel right and I'm getting actually some problems with errors when piping the proxied response.
- Using interceptors
When using interceptors I don't get access to the underlyingres
object which I need to pipe the request / response.
Any idea on how to solve this use case? I think the most elegant solution would be the ability to register middlwares after the controller handler, maybe calling it afterWare
.