How to call a function (not controller) from express 4 views

For example, I want to show the name of the authenticated user in the top of the page, so that name must be located in the layout view of my app. But I don't want to send the name as a variable in each controller function, I want to avoid this:

If I want to access the index page:

res.render('index', {user: req.session.username});

If I want to access another page:

res.render('page', {user: req.session.username});

and so on...

So I want to call from my view a function that returns me the name of that user, something similar to rails helpers.

Is that possible?

I tried res.locals

app.use(function(req, res, next){
  res.locals.user = '';
  next();
});

and then when the user is authenticated I change the value of res.locals with the name, but that just work one time with the next page that is rendered...

You had it close with the res.locals. Simply do:

app.use(function(req, res, next){
    res.locals.user = req.session.username;
    next();
});

Add this after the session middleware, and assuming you have your authentication system setup correctly, you should be able to access the username from the views.