Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

273
Views
NodeJS express - How to add session data inside router?

I need to add some session data express router (using express-session and passport).

I store the data correctly into user record in DB (mongo) and try to set the value to session data:

req.user.myData = "my session data";

Unfortunately the user data are serialized only during user authorization via passport. So "myData" are not stored into current session. When new user session is started, data are loaded from DB correctly and are available.

Is there any way (I expect so) to make data available in current session?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Most such things in ExpressJS world done using middlewares:

1) create js file in middlewares folder: populateUserData.js:

'use strict';

module.exports = (req, res, next) => {
  if(!req.user) req.user = {};
  req.user.someData = 'something';

  next();
}

2.1) attach it after passport:

app.use(passport.initialize());
app.use(passport.session());
app.use(require('./middlewares/populateUserData'));

or

2.2) attach it to specific route:

const populateUserData = require('./middlewares/populateUserData');

route.get('/api/users/me',
  passport.authenticate('basic', { session: false }),
  populateUserData,
  (req, res) => {
    res.json({ id: req.user.id, username: req.user.username });
  });

or

2.3) in group of routes:

app.use('/api/users',
  passport.authenticate('basic', { session: false }),
  require('./middlewares/populateUserData'),
  require('./routes/api/users'));

also You can create Your own middlewares that would be helpful,

for example: https://github.com/num8er/alttab-nodejs-challenge/blob/master/app.js#L19

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!