How to access req.session in a large number of templates in Express.js 4.*

  node.js, question

The architecture is Node.js 4.* plus Express 4.13, and the template used is Nunjucks. I know that the template can access the session by passing req.session into res.render function in each specific routes:

router.get('/', function(req, res, next) {
 res.render('index', {
 session: req.session

However, this amount is too large and there are too many repetitions. Each render method must be passed once more. How else can I access req.session in all templates?

Wipe, ask yourself to answer again. . .

Solution reference:ExpressJS exposing variables and session to Jade templates

Then follow this article and look at the API document of Express.js 4.* as follows:


An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

Sample code:

app.use(function(req, res, next){
 res.locals.user = req.user;
 res.locals.authenticated = !   req.user.anonymous;

For my specific question, before all routing codes, add this code:

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

Then you can directly access it in the template.sessionHere we go.