'Express: how do I let the template view know that I'm logged in?

I need to render a logout button and for that it needs a condition based on the login state. The problem is: I'm using a template engine, which has the navigation bar in the layout.pug, so I can't access just the bar, also I don't want to repeat the same code to check the session on all pages. After search a little I decided to use res.locals

At first I simply tried using the login route to load a boolean into the res.locals.isloggedIn variable, but it didn't work at all. So after thinking a lot I came to this conclusion:`

app.use(function (
  req: express.Request,
  res: express.Response,
  next: express.NextFunction
): void {
  res.locals.isLoggedIn = Boolean(req.session.token);
  next();
});

I'm going to make this look better later, I promise

So that works, great, but then why would I ask about it? Because it left me with more questions than answers.

First, why does it work here and not within a route? I read that it should be loaded before any route, but why? Another thing, wouldn't this sort of thing make all requests share the same state? I know it doesn't work that way, but it's something else that I don't really know why it happens.

And finally, and most importantly, is that really the right way to solve this problem? You see, I made a middleware to allow access to some pages, but why waste time on this if this solution was apparently simpler?

Here is the middleware:

export function ensureAuthenticated(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const token = req.session.token;
  const loginPath = "/auth/login";

  if (!token) {
    req.flash("error", "Please log in");
    res.redirect(loginPath);
    return;
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as any;

    models.user
      .findById(decoded.id)
      .then((user) => {
        if (!user) {
          req.flash("error", "User not found");
          res.redirect(loginPath);
          return;
        }

        req.user = user;
        next();
      })
      .catch((err) => {
        console.log(err);
        req.flash("error", "Something went wrong");
        res.redirect(loginPath);
      });
  } 
  
  catch (err) {
    req.flash("error", "Please log in");
    res.redirect(loginPath);
  }
}

small note: normally when I ask this kind of question people think I haven't studied. I took a ten hour freecodecamp course yesterday so I decided to do something myself, unfortunately it didn't teach me how to log out. please don't judge me for asking too much, i can assure you that if i didn't have other things to do i would spend all the time in the world looking for an answer on my own. thank you for understanding and peace



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source