Express Middleware | res.locals needs page refreshed twice

Hello,

I have managed to create a functioning app thanks to the help of this website. I am currently cleaning up my code as I learn about best practices, and was hoping someone could explain the following. I have simplified the code. The issue is when I move the res.locals.homePage code to the middleware, it seems to need the page to be refreshed twice before it gives the intended effect.

Scenario A - this works properly

I have the following routes:

Homepage:

router.get("/", (req, res) => {
  res.locals.homePage = true;
  res.render("landing");
});

Login Page:

router.get("/login", (req, res) => {
  res.locals.homePage = false;
  res.render("login");  
});

Wildcard Handler

router.get("/*", (req, res, next) => {
  res.locals.homePage = true;
  res.render("landing");
});

Alongside this, I have the following simple ejs template, which just shows a Home link when not on the homepage:

<% if(!homePage) { %>             
    <a href="/">Home</a>
<% } %>

Middleware

app.use(function(req, res, next) {
    res.locals.error = req.flash("error");
    res.locals.success = req.flash("success");
    res.locals.currentUser = req.user;   
    next();
});

Now this all works fine. But when I change to the following, I need to refresh the page twice before the homePage variable in the ejs template is the correct value:

New Middleware

app.use(function(req, res, next) {
    res.locals.error = req.flash("error");
    res.locals.success = req.flash("success");
    res.locals.currentUser = req.user;   
    
    if (req.url == "/")  {
        res.locals.homePage = true;
    }
    else {
        res.locals.homePage = false;
    }

    next();
});

If someone could explain this it would be much appreciated.

Thank you!