Set current user in NodeJS with Express

Krunal Shah

Oct 17, 2017

2 min readLast Updated Nov 01, 2023

Set current user in NodeJS with Express

Introduction

We always want to access currentUser in all the controllers. I have seen many people use the token to fetch the user all the time.

Instead I think it’s better we set the currentUser in the middleware at the time of authentication.

Lets explore using below example

var jwt = require('jsonwebtoken');
var config = require('./../config/config.constants');

module.exports = function (req, res, next) {

  // check header or url parameters or post parameters for token
  var token = req.body.token || req.query.token || req.headers['x-access-token'] || req.headers['authorization'];

  // decode token
  if (token) {

    var hash = config.secret.replace(/^\$2y(.+)$/i, '\$2a$1');
    // verifies secret
    jwt.verify(token, hash, function (err, decoded) {
      if (err) {
        return res.status(403).json({ message: 'Invalid token' });
      } else {
        // if everything is good, save to request for use in other routes
        req.decoded = decoded;
        wpUserModel.getUserInformationById(req.decoded.id, function (err, user) {
          req.currentUser = user;
          next();
        });
      }
    });
  } else {
    // if there is no token

    return res.status(403).json({
      message: 'Invalid token'
    });
  }
};

As you can see in the above gist, I have set currentUser after successfully check the authentication token.

So, now we can easily access currentUser in all your controllers like req.currentUser

If you are looking to get an application developed may it be a web application or a mobile application just drop us a message and experts from Third Rock Techkno will get back to you in 4 hours.

Visit Third Rock Techkno to know more about our expertise in AngularJS, NodeJS and IONIC.

TRT

We are a team of expert developers, testers and business consultants who strive to deliver nothing but the best. Planning to build a completely secure and efficient Node app? 'Hire Node JS Developer'.

· · · ·

Third Rock Techkno is a leading IT services company. We are a top-ranked web, voice and mobile app development company with over 10 years of experience. Client success forms the core of our value system.

We have expertise in the latest technologies including angular, react native, iOs, Android and more. Third Rock Techkno has developed smart, scalable and innovative solutions for clients across a host of industries.

Our team of dedicated developers combine their knowledge and skills to develop and deliver web and mobile apps that boost business and increase output for our clients.

Projects Completed till now.

Discover how we can help your business grow.

"Third Rock Techkno's work integrates complex frameworks and features to offer everything researchers need. They are open-minded and worked smoothly with the academic subject matter."

- Dr Daniel T. Michaels, NINS

Related Resources

Our Services

You May Also Like