Yakov Kemer
Yakov Kemer

Reputation: 373

Fastify point-of-view local variables

I am switching from Express.js to Fastify. I need to do it quickly, so using only API is impossible yet. Haven't written React app.

My problem is: I am using point-of-view and I don't know how to pass local variable to all requests. In express there something like

app.use(function (req, res, next)
{
 res.local.new_notifications = 50;
})

and I can get it in template engine on every page like

<%= new_notifications %>

Is there something like this in Fastify + point-of-view?

Upvotes: 0

Views: 1103

Answers (1)

Aspiiire
Aspiiire

Reputation: 408

You can, I am not sure if it is a new implementation or not since you asked a solution more than 1 year ago, this is for future viewers.

You simple have to add a .locals object and attach to it anything you want available with your engine.

This is from the documentation:

If you want to provide data, which will be depended on by a request and available in all views, you have to add property locals to reply object, like in the example below:

fastify.addHook('preHandler', function (request, reply, done) {
  reply.locals = {
    text: getTextFromRequest(request) // it will be available in all views
  }

  done()
})

Be sure to create the object with the assignment {} since locals its not defined!

Upvotes: 0

Related Questions