0

I have applied middleware to one of my application in Nestjs Fastify. In middleware I want to access userId from req url and remove it from there. Since I was using FastifyRequest as a req type I was not able to reassign req.url.

I got to know that I have to use req.raw in such case but req.raw inside middleware class is undefined for me.

Even I found req.originalUrl and I tried to update it but with changed originalUrl I am getting req url not found exception.

AbcMiddleware.ts

const token = matches[0].indexOf('api') > -1 ? matches[1] : matches[0];
//(not able to reassign req.url since it is readonly property)
req.url = req.originalUrl.replace(`${token}/`, '');
//(I am getting req url not found exception with originalUrl)
req.originalUrl = req.originalUrl.replace(`${token}/`, '');
//(req.raw is undefined)
req.raw.url= req.originalUrl.replace(`${token}/`, '');
Raj
  • 598
  • 5
  • 23
  • What is the output you want to obtain by changing the `url` property? – Manuel Spigolon Mar 21 '22 at 14:46
  • In fastify middleware in NestJS, `req` actually is `req.raw` – Jay McDoniel Mar 21 '22 at 15:18
  • @ManuelSpigolon after removing userId from endpoint will only give me correct endpoint and with userId it will be 404. – Raj Mar 22 '22 at 13:53
  • @JayMcDoniel yeah that's correct but whichever requests are going through middleware... req.raw is undefined in middleware class – Raj Mar 22 '22 at 13:55
  • @Raj right, because `req` is `req.raw` so you don't need to do `.raw` to access req.raw. – Jay McDoniel Mar 22 '22 at 15:54
  • @JayMcDoniel Thanks and correct, I noticed this now, that I am getting req.raw as a req in middleware. But now question is how can i update the current endpoint and remove userId from url? – Raj Mar 23 '22 at 07:19

0 Answers0