Note that there are some explanatory texts on larger screens.

plurals
  1. PONodeJS + session object in ALL views without passing it on all controller actions
    text
    copied!<p>I want my session to be available in all views (*.ejs) without having to pass it on every single action. My code is shown below, but the req.session object is always null here, even though in my "controllers" I can access a session object after an user has authenticated, by specifying:</p> <pre><code>req.session.whatever </code></pre> <p>My initialization code (that is currently executed on every single request (I double checked with a debug breakpoint) is:</p> <pre><code>var appendLocalsToUseInViews = function(req, res, next) { //append request and session to use directly in views and avoid passing around needless stuff res.locals.request = req; if(req.session != null &amp;&amp; req.session.user != null) { res.locals.user = req.session.user; } next(null, req, res); }; </code></pre> <p>I register this function in the app setup preamble:</p> <pre><code>app.use(appendLocalsToUseInViews); </code></pre> <p>I have seen people use app.use methods and dynamicHelpers. I am using express 3, and it seems they are gone, deprecated from Express 2... But that does not seem to be the point, as the function is being called correctly on every single request. How to I access the Express session in this sort of pre-controller code?</p> <p>Thanks!</p> <p>SOLUTION thanks Jani Hartikainen: </p> <p>I moved the code to after the session middleware is loaded and its working!!! Here is the new code.</p> <pre><code> app.use(express.cookieParser(appSecret)); app.use(express.session({ secret: appSecret })); ----&gt;&gt;&gt;app.use(appendLocalsToUseInViews); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload