0

Sorry for the poorly worded title, I'm not sure the best way to word it and I thought it'd be easier to explain with code. So lets say I have the following:

router.get('/chest', (req, res)=>res.render('muscles/chest/chest', {login: req.isAuthenticated(), user: req.user}));
router.get('/abs', (req, res)=>res.render('muscles/abs/abs', {login: req.isAuthenticated(), user: req.user}));
router.get('/biceps', (req, res)=>res.render('muscles/biceps/biceps', {login: req.isAuthenticated(), user: req.user}));
router.get('/frontdeltoids', (req, res)=>res.render('muscles/frontdeltoids/frontdeltoids', {login: req.isAuthenticated(), user: req.user}));
router.get('/quadriceps', (req, res)=>res.render('muscles/quadriceps/quadriceps', {login: req.isAuthenticated(), user: req.user}));

And in my layout.ejs file I have:

<% if (login) { %>
    <li class="nav-item">   
    <a class="nav-link" href="/users/profile/<%= user.id%>"><span class="fas fa-user"></span> Profile</a>
    </li>
        <li class="nav-item">
        <a class="nav-link" href="/users/logout"><span class="fas fa-sign-in-alt"></span> Logout</a>
    </li>

Is there a better way to do this than to have to add "login: req.isAuthenticated(), user: req.user" to everything I have so my layout.ejs file doesn't give me a login not defined error?

Chan Kim
  • 159
  • 8
  • 1
    I think you can make a middleware for authentication instead. https://stackoverflow.com/q/47515991/14032355 – ikhvjs Jun 18 '21 at 12:23

1 Answers1

0

The first solution that comes to my mind is to implement a middleware that could "globalize" your local variables.

Something like this will resolve this case:

router.use(function(req, res, next){
    res.locals.login = req.isAuthenticated();
    res.locals.user = req.user;
    next();
});

// The rest goes here

Please correct me if I'm misunderstanding you somehow.

Update: please check the comment by @ikhvjs (with thanks).