How to share token between different routes in node js?

Viewed 327

In the user.js file, I created the token here with this code

  if (user && bcrypt.compareSync(req.body.password, user.passwordHash)) {
    const token = jwt.sign(
      {
        userId: user.id,
        isAdmin: user.isAdmin,
      },
      process.env.SECRET,
      {
        expiresIn: "50d", // >> on day
      }
    );

And the token work and everything is ok, But I want to use the token somewhere else, for example, here in cupon.js file

router.post("/cupon", async (req, res) => {
 ...
  const token = req.header("authorization").substring(7);
 ...

I used this

  const token = req.header("authorization").substring(7);

to get the token from the header, Is there a better way to get the token?

1 Answers

You can create a separate middleware for authentication and authorisation. It will help you to reuse it any where or in multiple routes, you can use the same auth middleware and if every thing goes good in auth, you can call next else send the response with 401 status code.

In Auth.js

const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
  try {
    const token = req.headers.authorization.split(' ')[1];
    const decodedToken = jwt.verify(token, 'RANDOM_TOKEN_SECRET');
    const userId = decodedToken.userId;
    if (req.body.userId && req.body.userId !== userId) {
      throw 'Invalid user ID';
    } else {
      next();
    }
  } catch {
    res.status(401).json({
      error: new Error('Invalid request!')
    });
  }
};

Import this Auth.js and pass it to your routes which needs it. This way you can unit test your auth layer and can re-use it anywhere in the code. The below code is for sample purpose:

const express = require('express');
const router = express.Router();

const auth = require('../middleware/auth');

const stuffCtrl = require('../controllers/stuff');

router.get('/', auth, stuffCtrl.getAllStuff);
router.post('/', auth, stuffCtrl.createThing);
router.get('/:id', auth, stuffCtrl.getOneThing);
router.put('/:id', auth, stuffCtrl.modifyThing);
router.delete('/:id', auth, stuffCtrl.deleteThing);

module.exports = router;

For more details, you can check this link and follow along.

Related