114 thoughts to “Node.js + MongoDB: User Authentication & Authorization with JWT”

  1. I got your code running on my MongoDB, but every user I signup for has the same role. How do I assign different roles. You should maybe have it set up so that the first login is for Admin role and have them assign other roles? I see there are 3 roles set up in the DB but from login there is no way to assign a role. Where do we assign -user, moderator or Admin role?

  2. Everything works great so far but when I go to my user page it says “No token provided!” When I sent a get request to postman with the same access token as the user has it returns “User content”. Not sure what could be causing the difference in the browser vs through the Postman API

    1. Hi, if you use browser, maybe you run one of my clients (frontend code).
      I think the problem is your HTTP request header. You need to notice to choose Bearer Token or x-access-token on the client side. 🙂

  3. One of the best thorough and step by step guide to my most challenging concepts authentication.

  4. It is really nice project.
    Thank you for your work.
    But I have some errors like this:

    ReferenceError: Cannot access ‘app’ before initialization
    at Object. (E:\Exercise\node-js-jwt-auth-mongodb\server.js:5:37)

    please help me!

  5. Hi. I absolutely love your tutorials. I thought I’d let you know that body-parser has been deprecated. Express has integrated the same things body-parser does.

  6. Good day. Wonderful tutorial btw. When i tried signing up using roles “user” and “admin” in an array in the request body I got an error saying Cast to [ObjectId] failed for value \”[ ‘user’, ‘admin’ ]\” (type string) at path \”roles.0\””. I don’t know what’s wrong, every other thing works fine. Thanks in advance

    1. module.exports = {
      HOST: ‘localhost’,
      PORT: 27017,
      DB: ‘bezkoder_db’,

      What do i replace with this to point to my db? I’ve tried connecting my cluster to this but its showing an error

      1. Error: Illegal arguments: undefined, string    at Object.bcrypt.hashSync (/Users/mac/Authentication MongoDb/node-auth/node_modules/bcryptjs/dist/bcrypt.js:189:19)    at exports.signup (/Users/mac/Authentication MongoDb/node-auth/app/controllers/auth.controller.js:13:22)

  7. I’ve been working with Mongo atlas starting from scratch, so duplicating someone else code or just utilizing Mongodb is a little tricky to me. Please excuse me for being a noob and explain….

  8. I copied the github code and can’t get the mongodb connection to work.
    Connection error MongooseServerSelectionError: connect ECONNREFUSED

  9. Hi man thank you so much for this tutorial.
    But i have a problem on “verifySignUp.js” that “username” in the last of this line ‘username: req.body.username’
    ( TypeError: Cannot read property ‘username’ of undefined:
    checkDuplicateUsernameOrEmail (E:\node.js-backend\app\middlewares\verifySignUp.js:10:24))
    i don’t know how to fix it please help me

    1. Hi, you can check if your HTTP request header includes Content-Type: application/json.

  10. throw new TypeError(‘app.use() requires a middleware function’)

    TypeError: app.use() requires a middleware function
    at Function.use (/Users/ahmadirshad/Desktop/test/node-js-jwt-auth-mongodb/node_modules/express/lib/application.js:210:11)
    at Object. (/Users/ahmadirshad/Desktop/test/node-js-jwt-auth-mongodb/server.js:6:5)

    I am getting this error anyone here for help?

  11. Thank you so much for this tutorial….It was very helpful for me…I really appreciate it….could you tell me why did you use next() in verifySignUp.js?

  12. Thank you so much for this tutorial it has been very helpful! Just in case anyone stumbles across any issues setting this up in conjunction with nuxtjs auth, i found adding req.headers.authorization to the authJWT middleware file. “let token = req.headers[“x-access-token”] || req.headers.authorization || req.body.token;”

  13. Thank you for all your effort sharing awesome tutorials here. We really appreciate it.

  14. Hi, can someone elaborate in `.populate(“roles”, “-__v”)`, why we have used `-__v`. You can find the populate function in auth.controllers.js

    1. It means “excluding the __V field(version key) when populate the query”. It is generated whenever a document is inserted by Mongoose.

  15. Hello, I want to display the data of a user in flatlist , but i didn’t find what to modify in routes/controller so i can do this , i’ll appreciate if you can help me

  16. hiii thank you so much for this tutorial but i’m actually facing some problems with the roles as they don’t show in the db when i sign up a new user

  17. hi i keep getting network error when trying to submit a form not sure why no error and all is working fine.

  18. hello, when I do this in my routes :

    const { authJwt } = require(“../middlewares”);
    const controller = require(“../controllers/user.controller”);

    I have the error
    const { authJwt } = require(“../middlewares”);

    SyntaxError: Unexpected token ‘const’

  19. Thanks for this amazing post, Initially I faced issue but with going through comments. Everything gone fine. I really appreciate your work. Including this blog I found your another blogs useful too. Thanks mate

  20. Hi,

    First of all thanks for the tutorial. At a level of concepts, I got it. At the practical level, User.findOne is not a function hits me from checkDuplicateUsernameOrEmail() in verifySignUp middleware.

    What is this error actually telling me? I am understanding this as the seat is taken somehow.

    I have googled it for a while but there’s nothing wrong with the syntax from what I can understand. Any solutions or at least a more detailed explanation of why this is occuring?

    I have checked that mongoose it’s installed. I manage to connect to the mongo database and inser the roles data, but when I try to add a new user via the api i receive this error

    TypeError: User.findOne is not a function
    at checkDuplicateUsernameOrEmail (/home/alin/Work/BackEnd/token-based-auth/app/middlewares/verifySignUp.js:7:8)


    1. In my user.model.js at the very last line i was exporting module.exports = ‘User’; instead of module.exports = User;

      Thanks again!

  21. make me happy after competing this module…that make me feel i am expert with node.js
    ….thanks a lot..

  22. Hey there,

    I really appreciate your site and the code you’re offering us.
    I’m a (backend)beginner and really blown away from the complexity of your code (in a postive way). It seems so clean and well made. My question is… what is your experience and how long did you code? As far as I can understand this code.. this is clean and clear at the same time! My biggest concern right now is,that I cannot write this whole code alone at all. Backend is special for itself. What is your opinion about that? Thanks in advance!

  23. I appreciate, cause I found the tutorial what I was looking for. You’ve ended my four day long hunt! God Bless you man. Have a great day. Thanks!

  24. Hi sir, that a great tutorial! But i have an error at:

    TypeError: Role.estimatedDocumentCount is not a function

    Why? Thanks

  25. did the x-access-token came as a header or is it typed by copying accessToken and pasting it in headers. plllsssss reply

  26. Great Guide! Just a slight problem on my end with the Bcrypt hashing as it continuously gives me an error that writes : “Error: Illegal arguments: undefined, string at Object.bcrypt.hashSync”. Not sure if this is normal or dependency error, please advice. Thanks in advance!

          1. I checked over and over for typos. I had Body -> raw -> JSON selected and still got this error. Finally, I saw comment from Partha above…

            “Same is here also in postman I have set ‘Content-Type’: ‘application/json’ in the HTTP request header.”

            I put that in the header, and voila! worked.

    1. You need to select Body – > raw -> JSON(application/json)


  27. Upon downloading the code from your GitHub page the code does not work. I get the error Cannot GET /api/auth/signup. Can you advise how to fix this as I did not modify the code in any way.

    1. Hi, please make sure that your MongoDB runs correctly with db configuration, and the Node.js server runs successfully also.

  28. C:\Users\test\Desktop\testing\node-js-jwt-auth-mongodb\server.js:24
    .connect(`mongodb://${dbConfig.HOST}:${dbConfig.PORT}/${dbConfig.DB}`, {

    TypeError: Cannot read property ‘connect’ of undefined
    at Object. (C:\Users\test\Desktop\testing\node-js-jwt-auth-mongodb\server.js:24:4)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

    getting an error like this please help.

  29. Hello,

    I am having a lot of issues with this tutorial and nothing is working for me so far…
    I follow the Node.js, Express & MongoDb: Build a CRUD Rest Api example to get a front and back end. I’m basically trying to do this tutorial to get the user to log in to then access all the Tutorials (from the mentioned tutorial). But it wasn’t working. Now I’m simply trying to make this one work on its own and I am getting : TypeError: User.findOne is not a function at checkDuplicateUsername

    I am on my mac, using mongo community 4.4. I’m not sure why I am getting this error

  30. Great tutorial. I really enjoyed reading it.
    Would be nice to have fully asynchronous functions.

  31. I have a question – you have an array of functions being passed to an express route. I wasn’t aware you could do this – and my version of express only allows a single function (not an array). Do you have documentation on how this will execute?

    1. If you have it like me, then the following worked for me because there can be any amount of callback functions sent and I found out that the first callback is executed first:
      router.get(‘/test/admin’, authJwt.verifyToken, authJwt.isAdmin, adminBoard)

  32. Hi, great article I must say. Think it’s clicked now how JWT and Express.js working so thank you very much!
    All is working great, already building onto the system.
    Just wondering, what would be the best way to logout the user, reset the password, forgot password? Any tips, please?
    Keep up the good work

  33. I am getting this error in my postman “Client network socket disconnected before secure TLS connection was established” what can I do, please help

  34. Great tutorial and great tutorial site!
    I found a weird bug though, might be caused by newer versions installed here.
    auth.controller.signup: Role.Find({ name: {$in: req.body.roles} is case sensitive and matches what is stored in db.
    verifySignup.checkRoleexisted: if(!ROLES.includes(req.body.roles[i]) is also case sensitive and require lowercase because the ROLES are returned as lowercase.
    I solved it by changing to “if(!ROLES.includes(req.body.roles[i].toLowerCase()))” but it is not beautiful in any way.

  35. how can i change this

    module.exports = {
    HOST: “localhost”,
    PORT: 27017,
    DB: “bezkoder_db”

    to my mongo db cloud url , i am getting an error after changing it to this
    module.exports = {
    url: “mongodb+srv://james:[email protected]/crud?retryWrites=true&w=majority”

    the error i got is this
    throw new MongooseError(‘The `uri` parameter to `openUri()` must be a ‘ +

    MongooseError: The `uri` parameter to `openUri()` must be a string, got “undefined”. Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
    at NativeConnection.Connection.openUri (C:\Users\user\Documents\node-js-jwt-auth-mongodb-master\node_modules\mongoose\lib\connection.js:582:11)
    at Mongoose.connect (C:\Users\user\Documents\node-js-jwt-auth-mongodb-master\node_modules\mongoose\lib\index.js:335:15)
    at Object. (C:\Users\user\Documents\node-js-jwt-auth-mongodb-master\server.js:24:2)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

    1. James I did like that… in the server.js
      I clear:
      .connect(`mongodb://${dbConfig.HOST}:${dbConfig.PORT}/${dbConfig.DB}`, {
      useNewUrlParser: true,
      useUnifiedTopology: true
      }) ”

      and create:

      “const path = ‘mongodb+srv://USER:[email protected]/DB?retryWrites=true&w=majority’;
      .connect(path, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true

  36. Hi, loved the post I was wondering if you had any insides on how you would go about unit testing your middleware classes I was looking at verifySignUp, and haven’t been able to figure out how to mock the DB in order to isolate any of the methods for unit testing.

    Thanks a lot for your post!

  37. Hello Bezkoder,
    how I can redirect to the appropriate page after successful login depending on the Role (user, moderator or admin)?

  38. got this error “TypeError: Cannot read property ‘username’ of undefined
    at checkDuplicateUsernameOrEmail” can anyone please help?

    Same is here also in postman I have set ‘Content-Type’: ‘application/json’ in the HTTP request header. inspite of that I am getting this error please helpme.

    1. app.use(bodyParser.urlencoded({ extended: false }))


      use these line of code in server.js file

  39. Hello there,
    I got a problem with the initial() function, result is “Role.estimatedDocumentCount is not a function”
    I’m using mongoDB on cloud Atlas and mongoose version is 5.9.19,
    Thank you for debug information, I really want to practice more this wonderful tutorial 😉

    1. Role.estimatedDocumentCount is not a function” I got this issue due to old version of mongoose
      used Role.collection.estimatedDocumentCount to solve this.

    2. Hello how you solve this problem because i have te same problem, Im using MongoDB Atlas v4.8 and i get this error:
      Connection error TypeError: Role.estimatedDocumentCount is not a function

  40. Great tutorial

    i got this error “TypeError: Cannot read property ‘username’ of undefined
    at checkDuplicateUsernameOrEmail” can anyone please help?

    1. Hi, maybe you forgot to set 'Content-Type': 'application/json' in the HTTP request header.

      1. thank you very much for your guide
        it will be great help if help me out in solving this prblm

        error is:
        C:\Users\Lenovo\feb-mern-2020\mern project\node-js-jwt-auth-mongodb\server.js:24
        .connect(`mongodb://${dbConfig.HOST}:${dbConfig.PORT}/${dbConfig.DB}`, {

        TypeError: Cannot read property ‘connect’ of undefined
        at Object. (C:\Users\Lenovo\feb-mern-2020\mern project\node-js-jwt-auth-mongodb\server.js:24:4)
        at Module._compile (internal/modules/cjs/loader.js:1158:30)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
        at Module.load (internal/modules/cjs/loader.js:1002:32)
        at Function.Module._load (internal/modules/cjs/loader.js:901:14)
        at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
        at internal/main/run_main_module.js:18:47

    2. you must move these lines
      // routes
      after these lines:
      app.get(“/”, (req, res) => {
      res.json({ message: “Welcome to bezkoder application.” });

      in server.js file.

    3. I was having the same issue. I’m not sure why, but node was having an issue with the import of that verifySignup module. I had to change my import to explicitly be:

      const verifySignup = require(‘../middleware/verifySignUp.js’)

      rather than trying to use the neater importing/object destructuring used in the tutorial.

    4. Check the imports and exports. Do not use const { verifySignUp } = require(“../middlewares”); instead use const verifySignUp = require(“../middlewares”);

    5. app.use(bodyParser.urlencoded({ extended: false }))

      use these line of code in server.js file

  41. Great tutorial!
    This is something I was looking for.

    You could mention in your other tutorials, this could be used as small reference for a one-to-many for NodeJS – Express – MongoDB

  42. HI,

    I got this error when model creation, exactly got this one in this line db.user = require(“./user.model”);
    message: ‘Cannot overwrite `users` model once compiled.’,
    name: ‘OverwriteModelError’. how to reproduce this one.

    1. Hi, maybe you have instantiated mongoose.Model() on the same schema twice.

  43. Hey thank you, everything worked perfectly the first time! 😀

    FYI – I’m on Windows, and I have previously been instructed to use bcryptjs, but fyi, plain old bcrypt works just fine. I already had bcrypt installed, so instead of also installing bcryptjs, I decided to just try and see if it works, and it did!

    I truly appreciate when I come across a well-written article from someone who actually has working code lol… It’s frustrating how many people write articles and clearly did not even use their own code… grr… so, thanks again!

  44. Hi I am getting error as app.use is not a function. Can anyone please help?

  45. Hello, thank for the great guide – I have followed it closely, had a few issues…
    1. In the your project structure, you defined the folder “middleware” – but in the guide is referred to as “middlewares”
    2. Initalize Mongoose – adding to the server.js file the db configurations were not found – I added:
    const dbConfig = require(“./config/db.config”);
    just above the mongoose config – worked!

    Having a major issue, when starting up the app and using Postman to register a new user, get the following error serverside:
    TypeError: Cannot read property ‘findOne’ of undefined

    Double check the code and tried looking on-line, couldn’t find anything solid to go on – thought the feedback may help. Thank you

    1. Hey check your

      auth.controller.js and index.js to make sure you have correct values there…

      I had db.users = require(“./user.model.js”)(mongoose); in index.js and const User = db.user; in the controller.

      Please notice the typo there…

  46. Hello, thanks for your work on the guide…
    Having an issue connecting to mongoDB, fixed the connection by adding:
    const dbConfig = require(“./config/db.config”); to server JS – the ${dbConfig.HOST} variables can be found…

    but cant figure were the function inital()… code is placed? the connection just hangs.

    Warm Regards

    1. Right, fully following the steps, const dbConfig = require (“./config/db.config”); line is missing in Initialize Mongoose section.

Comments are closed to reduce spam. If you have any question, please send me an email.