1

In my Express 4 server I have a middleware function that checks whether the user is signed in or not and adjusts the request accordingly.

app.use((req, res, next) => {
  const { IdToken } = req.signedCookies;
  if (!IdToken) {
    req.signedIn = false;
  } else {
    // TODO: Verify IdToken
    req.signedIn = true;
  }
  next();
});

Currently, in every route I manually add the signed-in state to every res.render.

router.get('/', (req, res) => {
  res.render('index', { signedIn: req.signedIn });
});

Can I somehow include this information without manually adding it to every res.render call?

Hallur A.
  • 299
  • 1
  • 3
  • 13

1 Answers1

-1

Add a middleware that adds a req.view function, and a req.addState function.

function addViewer(req, res, next) {
  req.state = {}
  req.addState = function(key, value) {
     req.state[key] = value
  }
  res.view = function(viewName, moreState) {
    res.render(viewName, Object.assign({}, req.state, moreState));
  }
  next();
}

Now you can call res.view instead of res.render. Note that you can make the view function a lot more powerful and the addState more customizable.

Bamieh
  • 10,358
  • 4
  • 31
  • 52
  • You want every incoming request to execute this function? Because that's what middlewares do. Maybe you can instead define a custom `view` function once and use it instead of `res.render`. – darksky Feb 25 '23 at 02:09
  • See this answer https://stackoverflow.com/a/32874084/1362294 for a great solution to this. – darksky Feb 25 '23 at 02:50
  • it is actually a very bad solution, and focusing on an extra function call to evaluate if this is a good code or not is a very bad way to build web – Bamieh Feb 26 '23 at 16:09