Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify or save data in request object in fastify

I use nestjs to build a REST API.

I have a middleware which loads data from redis cache and should save it in the request object to access it in the controller function.

If i use express as engine it works, but with fastify it doesn't work. The data is undefined in the controller function.

The code looks like:

function mymiddleware(req, res, next) => {
    req.data = {...};
    next();
};
like image 885
Daniel Däschle Avatar asked Jul 01 '26 03:07

Daniel Däschle


1 Answers

this is a simple working example:

const fastify = require('fastify')({ logger: true })

fastify.use(function (req, res, next) {
  console.log('middy')
  req.data = { hello: 'world' }
  next();
})

fastify.get('/', (req, res) => {
  res.send(`hello ${req.raw.data.hello}`)
})

fastify.listen(3000)

I think that your problem is due to the req object: in middleware (registered using .use you will get the standard Node.js request, instead of augmented HTTPRequest in the fastify handler.

So, you can access the low-level Http request with .raw field.

like image 56
Manuel Spigolon Avatar answered Jul 03 '26 18:07

Manuel Spigolon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!