0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Yakov Kemer
  • 373
  • 3
  • 17
  • Sounds like you want to read through the docs ASAP, then. Learning a new framework ad hoc instead of first taking the time to read the docs is an excellent way to write code that only _seems_ to work but is held together by assumptions, bubblegum, and bugs waiting to happen. – Mike 'Pomax' Kamermans May 17 '20 at 20:28
  • you should check [request decorators](https://github.com/fastify/fastify/blob/2.x/docs/Decorators.md#decoraterequestname-value-dependencies) and [pre handler hook](https://github.com/fastify/fastify/blob/2.x/docs/Hooks.md#prehandler) – Manuel Spigolon May 18 '20 at 08:09
  • Thank. I used decorator, but local doesn't work on front side – Yakov Kemer May 18 '20 at 14:17

1 Answers1

0

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!

Aspiiire
  • 308
  • 3
  • 7