title: Getting [jwt is not defined] while fetching data from MongoDB backend -
body: <p>the question is pretty self explanatory. I am registering/signing up users in a mongoDB database. They are being registered fine and an accesstoken [jwt based] is also being generated.
  Now, when I go to query the database to fetch the list of users I am getting that error -
  <strong><em>jwt is not defined.</em></strong></p>
  
  <p>It is worthwhile to mention that users also in my backend can have two type of roles - basic and admin. And only an admin user can fetch list of all users by sending accessToken in the header as Bearer authorization parameter.</p>
  
  <p>I have 2 main files in my backend project structure that uses <strong><em>jwt.access methods like jwt.verify or jwt.signIn</em></strong>; these are the server.js and userController.js [a separate file where I have written all individual db related methods].</p>
  
  <p>As far as I am concerned, all necessary packages are there in my project - express, node, jwa, jws, jsonwebtoken, mongo, mongoose, bcrypt, cors etc. So what is the trouble?</p>
  
  <p>My route.js --></p>
  
  <pre><code>const User = require('../models/user.model');
  const jwt = require('jsonwebtoken');
  const bcrypt = require('bcrypt');
  
  const { roles } = require('../models/roles');
  
  
  const JWT_SECRET = "$#GR24T4344$#$@#%ETWWTEME%$6";
  
  async function hashPassword(password) {
      return await bcrypt.hash(password, 10);
  }
  
  
  async function validatePassword(plainPassword, hashedPassword) {
      return await bcrypt.compare(plainPassword, hashedPassword);
  }
  
  
  exports.grantAccess = function (action, resource) {
      return async (req, res, next) =&gt; {
          try {
              const permission = roles.can(req.user.role)[action](resource);
              if (!permission.granted) {
                  return res.status(401).json({
                      error: "You don't have enough permission to perform this action"
                  });
              }
              next();
          } catch (error) {
              next(error);
          }
      }
  }
  
  
  exports.allowIfLoggedin = async (req, res, next) =&gt; {
      try {
          const user = res.locals.loggedInUser;
          if (!user)
              return res.status(401).json({
                  error: "You need to be logged in to access this route"
              });
          req.user = user;
          next();
      } catch (error) {
          next(error);
      }
  }
  
  
  exports.signup = async (req, res, next) =&gt; {
      try {
          const { role, email, password } = req.body;
          const hashedPassword = await hashPassword(password);
          const newUser = new User({ email, password: hashedPassword, role: role || "basic" });
          const accessToken = jwt.sign({ userId: newUser._id }, JWT_SECRET, {
              expiresIn: "1d"
          });
          newUser.accessToken = accessToken;
          await newUser.save();
          res.json({
              data: newUser,
              message: "You have signed up successfully"
          });
      } catch (error) {
          next(error);
      }
  }
  
  
  exports.login = async (req, res, next) =&gt; {
      try {
          const { email, password } = req.body;
          const user = await User.findOne({ email });
          if (!user)
              return next(new Error('Email does not exist'));
          const validPassword = await validatePassword(password, user.password);
          if (!validPassword)
              return next(new Error('Password is not correct'));
          const accessToken = jwt.sign({ userId: user._id }, JWT_SECRET, {
              expiresIn: "1d"
          });
          await User.findByIdAndUpdate(user._id, { accessToken });
          res.status(200).json({
              data: { email: user.email, role: user.role },
              accessToken
          });
      } catch (error) {
          next(error);
      }
  }
  
  
  exports.getUsers = async (req, res, next) =&gt; {
      const users = await User.find({});
      res.status(200).json({
          data: users
      });
  }
  
  
  exports.getUser = async (req, res, next) =&gt; {
      try {
          const userId = req.params.userId;
          const user = await User.findById(userId);
          if (!user)
              return next(new Error('User does not exist'));
          res.status(200).json({
              data: user
          });
      } catch (error) {
          next(error);
      }
  }
  
  
  exports.updateUser = async (req, res, next) =&gt; {
      try {
          const { role } = req.body;
          const userId = req.params.userId;
          await User.findByIdAndUpdate(userId, { role });
          const user = await User.findById(userId);
          res.status(200).json({
              data: user
          });
      } catch (error) {
          next(error);
      }
  }
  
  
  exports.deleteUser = async (req, res, next) =&gt; {
      try {
          const userId = req.params.userId;
          await User.findByIdAndDelete(userId);
          res.status(200).json({
              data: null,
              message: 'User has been deleted'
          });
      } catch (error) {
          next(error);
      }
  }
  </code></pre>
  
  <p>My server.js --></p>
  
  <pre><code>const express = require('express');
  const bodyParser = require('body-parser');
  const cors = require('cors');
  const PORT = 4000;
  const mongoose = require('mongoose');
  const Schema = mongoose.Schema;
  const playerRoutes = express.Router();
  const userRoutes = express.Router();
  const userController = require('./controllers/userController');
  const user_routes = require('./apiroutes/route');
  const app = express();
  
  const JWT_SECRET = "$#GR24T4344$#$@#%ETWWTEME%$6";
  
  
  const users = "users";
  
  require("dotenv").config({path: __dirname+ '../.env'});
  
  
  
  let Player = require('./models/player.model');
  let User = require('./models/user.model');
  
  app.use(cors());
  app.use(bodyParser.json());
  
  app.use(
      bodyParser.urlencoded({
          extended: false
      })
  );
  
  mongoose.connect('mongodb://127.0.0.1:27017/playerDB', function (err, db) {
      if (err)
          throw err;
      db.createCollection(users, function (err, resp) {
          if (err)
              throw err;
          console.log("Collection created!");
  
      });
  }, { useNewUrlParser: true });
  
  
  const connection = mongoose.connection;
  
  connection.once('open', function () {
      console.log("MongoDB database connection established successfully");
  });
  
  ..... blablablaaaa
  
  
  app.use('/playerDB', playerRoutes);
  
  
  app.use(async (req, res, next) =&gt; {
  
      res.header("Access-Control-Allow-Origin", "*");
  
      if (req.headers["x-access-token"]) {
          try {
              const accessToken = req.headers["x-access-token"];
              const { userId, exp } = await jwt.verify(accessToken, JWT_SECRET);
              // If token has expired
              if (exp &lt; Date.now().valueOf() / 1000) {
                  return res.status(401).json({
                      error: "JWT token has expired, please login to obtain a new one"
                  });
              }
              res.locals.loggedInUser = await User.findById(userId);
              next();
          } catch (error) {
              next(error);
          }
      } else {
          next();
      }
  
  
  });
  
  
  app.use('/users', user_routes);
  
  
  app.listen(PORT, function () {
      console.log("Server is running on Port: " + PORT);
  });
  </code></pre>
  
  <p>I hope you understand my approach and scenario? Can you guess, where it could have gone wrong? Any idea?
  Missing npm packages or something more critical?</p>
  
  <p>Look forward to some hints on this problem! Can't seem to figure out a way!</p>