185 thoughts to “Node.js Express: JWT example | Token Based Authentication & Authorization”

  1. I am hosting my database on AWS, but once I created the User and Role models in my backend and run the code. It does not automatically create anything in mySQL database on AWS. Do you know what is wrong with this?

  2. Hello,

    First of all thanks you for your work, everything works perfectly except the capacities of adding multiple roles to one user. Adding one role is working but when i try to add two of them with postman i have the same error :
    “Unhandled rejection SequelizeDatabaseError: You have an error in your SQL syntax;”.
    The user is created and added to the database without any role, not even user who is set by default.

    I tried to modify the roles models, like it seems it’s not build to be an array with multiple string i don’t really know i’m still very new to this.

    Thanks in advance for you help

  3. hi , when i re run the server all the data that I have saved will be removed how to change that please !!

  4. i tried but this error not resolved
    TypeError: Cannot read property 'username' of undefined    at checkDuplicateUsernameOrEmail (C:\SRIHARI\my-projects\project-management\angular-node\node-pms\app\middleware\verifySignUp.js:8:26)    at Layer.handle [as handle_request] (C:\SRIHARI\my-projects\project-management\angular-node\node-pms\node_modules\express\lib\router\layer.js:95:5)    at next (C:\SRIHARI\my-projects\project-management\angular-node\node-pms\node_modules\express\lib\router\route.js:137:13)    at Route.dispatch

    1. Hi, kindly make sure that you use Content-Type: application/json in your HTTP request header. :)

  5. Getting these issues from the nuxt portion of the project:

    ERROR in ./node_modules/pg-connection-string/index.js
    Module not found: Error: Can’t resolve ‘fs’ in ‘node_modules\pg-connection-string’

    ERROR in ./node_modules/sequelize/dist/lib/dialects/sqlite/connection-manager.js
    Module not found: Error: Can’t resolve ‘fs’ in ‘node_modules\sequelize\dist\lib\dialects\sqlite’

    ERROR in ./node_modules/sequelize/dist/lib/dialects/postgres/hstore.js
    Module not found: Error: Can’t resolve ‘pg-hstore’ in ‘node_modules\sequelize\dist\lib\dialects\postgres’

    Installing fs and pg-hstore does not seem to resolve the issue, and besides that I don’t understand where this is coming from anyways. The frontend nuxt app shouldn’t be concerned about any of this stuff. Any ideas of where I should look? I did put all the folders for this project in the root folder of my Nuxt app instead of in a different folder.

  6. Hey, great work on this one!! I have been following you for a while and being new to react and all, you have really contributed to my letting loose. I only need some clarification for a certain addition to the server.js file, after the creation of the /models/index.js file.

    At that point in the tutorial you add the following lines to the server.js:
    const app = express();

    const db = require(“./app/models”);
    const Role = db.role;

    I do not understand why there is a spread operator inside the app.use function. What does app.use(…) do? Or is there something else implied there? Anyhow, running –node server.js — is blocked by the editor, because of that line. Thank you very much!

    1. Hi, the '...' just implies something else there :)
      You can read the source code on Github for details.

  7. Hai bezkoder. You give this tutorial it’s really awesome. I just tried it for the first time and understand. Thanks so much.

  8. great bezkode i have a question we can control other user or deleat or see profile other user like a admin role ? can u help me or send a tutorial for admin role

  9. Hello bezkoder

    I tried the tutorial and I think it is very geat job.

    I tried it in my local dev machine (localhost) and then published it on my cloud dev machine.

    I wanted to test the tutorial on my dev cloud machine with the usecase I provide old token when signing
    so i used the token (for the same user) used some minutest ago in my local dev machine
    the token i used before in my local dev machine worked also in my cloud dev machine.

    Is it because the token has 24hrs validity ?

    could we think to link the token also to the domain of the express application ?


  10. Hi, can anyone help me, i try to select all from my table: i do have tb1.models.js in the models folder

    exports.test = function (req, res) {
      db.tbl1.findAll({attributes: ['id', 'name']});

    The error here
    TypeError: Cannot read property ‘findAll’ of undefined

    1. I found the issue. the code can not connect other tables except: users, user_roles and roles.
      in the sql-management the db-account can access all tables.
      where is in the code to register other tables?

      1. Why the table name system add ‘s’ to the end and add more columns when execute that make me sick and need to findout where is the configuration.
        original table name tbl1: id, name

        Executing (default): SELECT [id], [name], [createdAt], [updatedAt] FROM [tbl1s] AS [tbl1];

    2. Finally i found the solution:
      add your original table name and set option timestamp in your model.js:

        name: {
            type: DataTypes.STRING(255),
            allowNull: true
        }, {
          tableName: 'tbl1',
          timestamps: false

      NOTED: you can add timestamps: false to the model/index.js as an option to all your models.

  11. Please help: what does it mean?
    “username”: “mod”,
    “email”: “[email protected]”,
    “password”: “test”,
    “roles”: [“moderator”, “user”]

    I get the below message from postman
    “message”: “Conversion failed when converting date and/or time from character string.”

    1. the datatype or id of roles is not matched the structure then i drop my table and use the initial fuction now is working thank you.

  12. Hi Bezkoder,

    Thank you very much for your tutorial, it is amazing! I followed it step by step and everything worked fine until when I tried to access the protected source. The signup and signin functions work well and I can get the token as well. However, when I tried to do “/api/test/user” (there is a user in my database), it said “no token provided” and when I tried to do”console.log(req.headers[“x-access-token”], it was undefined. The same thing happened when I downloaded your source code from git and ran it on my mac. Can you please tell me what happened and how I could fix it?

    Thank you so much.

    1. Please make sure to select the right back-end (Node or Spring Boot) in the src/services/auth-header.js file of your front-end implementation.

  13. Hello Bezkoder,
    Great job,kudos for your effort.

    I am new to MERN with mysql,and Sequelize,I tried to follow the steps in this tutorial,but it seems I have missed some important step,that prevent me from creating a new user,each time I execute the code,I get “TypeError: User.create is not a function” error message at User.create({}) of auth.controller.js. Kindly assist in resolving this issue.

    Thank you

  14. Hey There. A very great article which helped me from the beginning till the end.


  15. In server.js, line 23:

    // force: true will drop the table if it already exists
    // db.sequelize.sync({force: true}).then(() => {
    // console.log(‘Drop and Resync Database with { force: true }’);
    // initial();
    // });

    The call to initial() is never done so db.roles stays empty causing no insert into db.user_roles when a new user is inserted using /api/auth/signup

  16. Hello, can u help me?, im get stuck here after POST to localhost:3000/api/auth/daftar

    Executing (default): SELECT `id`, `namalengkap`, `username`, `email`, `password`, `createdAt`, `updatedAt` FROM `penggunas` AS `penggunas` WHERE `penggunas`.`username` = ‘madiajijah7’ LIMIT 1;
    Executing (default): SELECT `id`, `namalengkap`, `username`, `email`, `password`, `createdAt`, `updatedAt` FROM `penggunas` AS `penggunas` WHERE `penggunas`.`email` = ‘[email protected]’ LIMIT 1;

    there no error in Postman just a seinding request like this : https://prntscr.com/119eg9i

  17. Hi,
    This such a great tutorial man. So gladly i found it. Btw i wanna ask something, what the next(); meaning in every functions you’ve make it ?

  18. Hi, Great Tutorial! , can i can add permissions to this project , roles , rules, permissions may be come from database , have y some idea to do it ?

  19. Hi Bezcoder,
    A very nice tutorials and well documented.

    I have issue with ROLE not assigned to a respective (Moderator & admin) user, during signup, is there a suggestion on how to fix that please.

    warm regards

  20. Excellent tutorial. I am trying to convert to typescript, but it has a lot of errors. Do you have any examples with TS?

  21. Hello bezkoder, when I try to signup users using Postman, I get a error response saying socket hang up or read Econnreset. Can you help me with it?
    All other get requests work perfectly fine.

  22. Thank you for this tutorial. I’m facing these messages when I try to restart node server.js:
    (node:14036) [SEQUELIZE0004] DeprecationWarning: A boolean value was passed to options.operatorsAliases. This is a no-op with v5 and should be removed.

    Server is running on port 8080.

    (node:14036) UnhandledPromiseRejectionWarning: SequelizeConnectionRefusedError: connect ECONNREFUSED
    at ConnectionManager.connect (C:\Users\RARibeiro\OneDrive\ECOSTEEL\node-js-jwt-auth\node_modules\sequelize\lib\dialects\mysql\connection-manager.js:116:17)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

    (node:14036) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `–unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

    (node:14036) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

    1. I run into the same issue. This shows up when trying to setup the alternative postgres project.

      Haven’t found a solution yet.

  23. Hello, I;m stuck in “Unhandled rejection Error: WHERE parameter “username” has invalid “undefined” value”
    i do :
    // parse requests of content-type – application/json

    // parse requests of content-type – application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: true }));

    And below it i put :

    // routes

    Trying restart “node server.js” several times like a mention in comment before ,but still no luck still getting that error , maybe someone can help to resolve it ?. – Thanks –

    1. Hi, as mentioned by Ahsan some days ago, in postman you should change the input from raw text to raw JSON and then you’ll have a success message.

      I was stuck with this some time until noticed that.

  24. hello, how can retrieve a list of all the “mod” or “superadmin” from the table?

  25. hi there,

    i have an error for “message”: “No token provided!” and inside my postman there is no x-access token. is there something that I am missing ? on my postman there is content-type but not x-access

  26. Running Ubuntu 20.04

    It returns Cannot GET /api/auth/signin and Cannot GET /api/auth/signup. It does let me have access to the /api/test/user and /api/test/mod and /api/test/admin (these show {“message”:”No token provided!”}) and /api/test/all (shows Public Content.)

    Does anyone know the issue?

    Been trying to integrate the https://bezkoder.com/angular-10-jwt-auth/ into this. Does anyone know how to do it? Please share if you have any example?

    1. I have same problem. try to change usage header in auth-header.js
      // return { Authorization: ‘Bearer ‘ + user.accessToken }; // for Spring Boot back-end
      return { ‘x-access-token’: user.accessToken }; // for Node.js Express back-end

  27. How can we directly set roles for the user using a form from the frontend rather than using postman?

  28. Hey, great work!
    I had a question, How can we directly set roles for the user using a form from the frontend rather than using postman?

  29. Hi and thx for very nice tutorial!
    I have problem when I try to login with non-existing user – the node screams about UnhandledPromiseRejectionWarning but I don’t know how and what block should I put inside the try-catch to satisfy node. Do I have to somehow modify app.post(“/api/auth/signin”, controller.signin); ? The findOne already has catch. When I change the exports.signin into exports.signin = async (req, res) => {try {…} catch (err) {..} it isn’t solving the problem. Thank you very much!

    Executing (default): SELECT “id”, “username”, “email”, “password”, “createdAt”, “updatedAt” FROM “users” AS “users” WHERE “users”.”username” = ‘testuser’ LIMIT 1;
    (node:19868) UnhandledPromiseRejectionWarning: Error: WHERE parameter “email” has invalid “undefined” value (…)
    at async Function.findOne (node_modules\sequelize\lib\model.js:1917:12)
    (node:19868) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `–unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
    (node:19868) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

  30. When i use post api -> localhost:8080/api/auth/signup

    “username” : “ahmad”,
    “email” : “[email protected]”,
    “password”: “1245678”,
    “roles” : [“admin”, “user”]

    I face this error

    Unhandled rejection Error: WHERE parameter “username” has invalid “undefined” value
    at MySQLQueryGenerator.whereItemQuery (E:\test\node-js-jwt-auth-master\node_modules\sequelize\lib\dialects\abstract\query-generator.js:2184:13)
    at E:\test\node-js-jwt-auth-master\node_modules\sequelize\lib\dialects\abstract\query-generator.js:2173:25
    at Array.forEach ()
    at MySQLQueryGenerator.whereItemsQuery (E:\test\node-js-jwt-auth-master\node_modules\sequelize\lib\dialects\abstract\query-generator.js:2171:35)
    at MySQLQueryGenerator.getWhereConditions (E:\test\node-js-jwt-auth-master\node_modules\sequelize\lib\dialects\abstract\query-generator.js:2583:19)
    at MySQLQueryGenerator.selectQuery (E:\test\node-js-jwt-auth-master\node_modules\sequelize\lib\dialects\abstract\query-generator.js:1315:28)
    at QueryInterface.select (E:\test\node-js-jwt-auth-master\node_modules\sequelize\lib\query-interface.js:1127:27)
    at E:\test\node-js-jwt-auth-master\node_modules\sequelize\lib\model.js:1759:34
    at tryCatcher (E:\test\node-js-jwt-auth-master\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (E:\test\node-js-jwt-auth-master\node_modules\bluebird\js\release\promise.js:547:31)
    at Promise._settlePromise (E:\test\node-js-jwt-auth-master\node_modules\bluebird\js\release\promise.js:604:18)
    at Promise._settlePromise0 (E:\test\node-js-jwt-auth-master\node_modules\bluebird\js\release\promise.js:649:10)
    at Promise._settlePromises (E:\test\node-js-jwt-auth-master\node_modules\bluebird\js\release\promise.js:729:18)
    at _drainQueueStep (E:\test\node-js-jwt-auth-master\node_modules\bluebird\js\release\async.js:93:12)
    at _drainQueue (E:\test\node-js-jwt-auth-master\node_modules\bluebird\js\release\async.js:86:9)
    at Async._drainQueues (E:\test\node-js-jwt-auth-master\node_modules\bluebird\js\release\async.js:102:5)
    at Immediate.Async.drainQueues [as _onImmediate] (E:\test\node-js-jwt-auth-master\node_modules\bluebird\js\release\async.js:15:14)
    at processImmediate (internal/timers.js:456:21)

    1. Hi!

      I have found solution. When I chose raw option then I selected Text instead of Json option.

  31. This was incredibly useful. I’ve recently started learning NodeJs. It’s an awesome framework.

  32. hey bezkoder,

    I have this error :

    TypeError: Cannot read property ‘username’ of undefined
    at exports.signin (C:\Users\me\Desktop\env_node\JWT_mysql_node_tut\app\controllers\auth.controller.js:46:26)
    at Layer.handle [as handle_request] (C:\Users\me\Desktop\env_node\JWT_mysql_node_tut\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\me\Desktop\env_node\JWT_mysql_node_tut\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\me\Desktop\env_node\JWT_mysql_node_tut\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\me\Desktop\env_node\JWT_mysql_node_tut\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\me\Desktop\env_node\JWT_mysql_node_tut\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\me\Desktop\env_node\JWT_mysql_node_tut\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\me\Desktop\env_node\JWT_mysql_node_tut\node_modules\express\lib\router\index.js:275:10)
    at C:\Users\me\Desktop\env_node\JWT_mysql_node_tut\app\routes\auth.routes.js:10:5
    at Layer.handle [as handle_request] (C:\Users\me\Desktop\env_node\JWT_mysql_node_tut\node_modules\express\lib\router\layer.js:95:5)

    and unable to solve it till now. Any solution would be appreciated. Thank you!

  33. Great guide thank you!
    Posting this again as you may have missed it.

    In your explanation of folder stucture, you have “middleware”.
    However you refer to this folder throughout the guide as “middlewares” (plural), when we are creating the files authJwt, index, and verifySignUp.

    But, inside the code, you are importing files from the folder “middleware” (singular).

    Would advise changing to avoid any confusion on why code isn’t working if people are not checking this.

    Again, love all the guides and options you are providing for different stacks.

    1. I also wanted to add to this as I had an issue with the correct board being displayed per the users role.
      (User, Moderator, Admin)
      In the auth-header.js file you have the following object being returned to the user.service.js GET requests:

      return { Authorization: “Bearer ” + user.accessToken };

      This results in an error of “No token provided”. as it is looking for the header “x-access-token”, not Authorization.bearer

      I have changed it to reflect the following, which resulted in a correct display of the board being viewed by the users role.

      return { “x-access-token” : user.accessToken };

      If the way in which you have described the object in the guide is correct, could you explain a bit further on how that works?
      Because I received the error stated above, I have kept my chgange I made until further notice.

      Again, thank you!! :)

      1. Hi, it is because I use the frontend for 2 backend:
        – Spring Boot: using Bearer token
        – Node.js: using x-access-token

        I write this notification in the frontend tutorial.

    1. Hi, please look at how we define Sequelize Associations in app/models/index.js. The method user.getRoles() is supported without our implementation.

  34. UnhandledPromiseRejectionWarning: SequelizeDatabaseError: Cannot drop table ‘roles’ referenced by a foreign key constraint ‘user_roles_ibfk_1’ on table ‘user_roles’. . this is happen when i try to execute server.js . I know this is an error when i try to delete table that has foreign key , how to fix this in node js .

    1. Hi, you should change the code in server.js to:

      // db.sequelize.sync();
      // force: true will drop the table if it already exists
      db.sequelize.sync({force: true}).then(() => {
        console.log('Drop and Resync Database with { force: true }');

      It will create 3 necessary rows first. :)

  35. please i need an explanation; whats the setRole() for, is it a sequelize function.

    .then(roles => {
    user.setRoles(roles).then(() => {
    res.send({ message: “User was registered successfully!” });

  36. Hi and thanks bezkoder for this tutorial, it has helped me understand this process better considering I’ve rewritten parts to use node-postgres rather than sequelize since I’m more familiar with SQL than working with ORMs. The conversion “forced” me to learn more Postgresql functionality. Now to tackle the React frontend part where I’ll be using material-ui and formik but still following your React Hooks: JWT Authentication (without Redux) example. Excellent work.

  37. Hi Bezkoder,

    Thanks for this tutorial, very helpful. But I don’t understand one of the functions.
    What does ‘getRoles()’ from authJwt.js file do?
    I cannot see where it is defined or referenced in the project.

    1. Hi, you can see that we use belongsToMany() so that Sequelize supports the methods getRoles() for model User.

  38. hi, my token is throwing a 500 internal server error. It’s only the token that’s supposed to go in yeah?

  39. Do you have similar example using just mysql and not sequilize? Also can the above examples done using mysql?

    1. Hi Aak,

      I’ve just completed this tutorial by converting to using node-postgres rather than use sequelize, so it will be possible. As I’m new to most of this myself and haven’t used MySql I can’t be specific but it should just be a matter of creating the appropriate SQL statements for each of the database queries required.

      Best regards,

  40. Everything looks great except I fear many people using this may not realize that adding roles in the signup route is a bad idea. Anyone could hit the api of the site using postgres and create an account with admin privileges if they knew the website used this. I would highly recommend removing removing everything in this if statement and only keeping what is in the else (default User role) in the signup function in auth.user.js

    if (req.body.roles) {
              where: {
                name: {
                  [Op.or]: req.body.roles
            }).then(roles => {
              user.setRoles(roles).then(() => {
                res.send({ message: "User was registered successfully!" });
          } else {
            // user role = 1
            user.setRoles([1]).then(() => {
              res.send({ message: "User was registered successfully!" });
    1. Hi, this is just for development and understand how to run authorization. In real app, we don’t accept anybody signup for all roles.

      1. Hi,

        For my use case it’s ideal as I expect the admin to do the signups and allocate roles, so the signup route will be admin role protected.

  41. Hi,
    I’m getting an error, When I start the server node server.js. Please find the below error log:
    D:\Personal\NodeJS\node-js-jwt-auth>node server.js
    TypeError: Cannot read property ‘sync’ of undefined
    at Object. (D:\Personal\NodeJS\node-js-jwt-auth\server.js:23:14)
    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. Hi,
      I don’t know how to do this initialization.
      If anyone has source code, Kindly the share to me.
      Thank you so much for these tutorials.


  42. That’s awesome, thanks!

    One quick note: You’ve created the folder as “middlewares” but it’s importing it later as “middleware”. :)

  43. Hi greatesolution i tried the CRUD operations and it worked perfectly . I have an error in the api while trying the authentication with mysql. I’m not able to add a new user in both mysql db as well as in server (i.e) in the locahost:8080/api/auth/signup in server . in my db i’m getting the following error
    Unhandled rejection SequelizeForeignKeyConstraintError: Cannot add or update a child row: a foreign key constraint fails (`mysql`.`user_roles`, CONSTRAINT `user_roles_ibfk_1` FOREIGN KEY (`roleId`) REFERENCES `roles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
    Help needed. Thanks in advance!!!

    1. I came across this myself when doing another one of these excellent tutorials. It may be because you already have data in the table. Try truncating that table (or any related tables as well – after backing up or exporting any data) and then run it and it may work. HTH.

  44. Thanks a lot for the Tutorial, it helped me understand a lot I didn’t grasp before. It would be nice if you could make this post a bit clearer:
    React + Node.js Express: User Authentication with JWT example
    Scrolling through half the page was a little bit confusing to find the implementation.
    Besides that I have one question maybe you or someone else here can answer.

    const authJwt = {
    verifyToken: verifyToken,
    isAdmin: isAdmin,
    isModerator: isModerator,
    isModeratorOrAdmin: isModeratorOrAdmin

    Everything in these is undefined for me and thus the arrow functions also don’t work. Do you have any idea why that could be the case? I think I’m probably missing something super simple but I don’t know what.

    Thanks again for the great tutorial, even with my fails it was easy for me to follow and made some things clear.

  45. First i want thenks for tutorial – it work great … but i dont have rules. I think i dont create or add something. I have profile component from github like everything else. When i try find ROLES_USER, ROLES_ADMIN or ROLES_MODERATOR i cant find it in my code. If i dont give what i have in my code for you please tell me and i add in next comment. Do you know what i miss ?Sorry i dont add “my” code but i dont know what i should add and want know exacly what create ROLES.

    Sorry for my english – i know im terrible :P

  46. I got this to work on my local development machine using SQL Server (MSSQL) rather than MySQL. Also using Tedious and Express4/Tedious. Now trying to publish the Express app to Azure and unable to get to any of the ‘auth’ routes. It returns Cannot GET /api/auth/signin and Cannot GET /api/auth/signup. It does let me have access to the /api/test/user and /api/test/mod and /api/test/admin (these show {“message”:”No token provided!”}) and /api/test/all (shows Public Content.) All my other routes are protected, so they also show up as {“message”:”No token provided!”}. How does one go about getting the auth routes to work in Azure?

  47. Great work, quick question, why when i add a new model (table), it still enforces createdAt and updatedAt fields to be there? how can i remove this enforcement pls? much thankkkks

  48. This article is great.

    The checkDuplicateUserNameOrEmail function check email only when username is already in use. Maybe you should check email only when username is not in use.


  49. Hi, first of all, thank you for your guidance. Can you make a tutorial about Node.js Token Based Authentication & Authorization example without ORM Sequelize? Thank you!

  50. How would you add another protected route without sequelize?

    I have a route /alignments that I would like to add as a protected route. I’m trying to get it to work like the user route. I tried to add it to /user/alignments but that didn’t work either. Please help!

  51. Thanks for the great tutorial! I got this working with SQL Server using tedious and express4-tedious. Didn’t need mysql2 so uninstalled it. So I have a route set up in express4-tedious that I would like to only be available if a user (ROLE_USER) is logged in:

    app.use(‘/alignments’, require(‘./app/routes/alignments’));
    (in server.js)

    I have nothing against myql. Just need to use a mssql database because of some spatial functions that are not available in mysql, for example:

    /* GET alignments listing. */
    router.get(‘/’, function (req, res) {
    req.sql(“select id, fid, GeomCol1.AsTextZM() as alignmentwkt, GeomCol1.STSrid as srid, aligngrp1, aligngrp2, alignment, GeomCol1.STLength() as length, lrs.STStartMeasure(GeomCol1) as startm, lrs.STEndMeasure(GeomCol1) as endm, lrs.STMeasureRange(GeomCol1) as measure_range, hascurve, numsegs, thumbnail, mapurl from alignmentstest4 order by aligngrp1 asc, aligngrp2 asc, alignment asc for json path”)
    .into(res, ‘[]’);
    (in routes/alignments.js)

    So how would you go about making this new /alignments route available to only users who are logged in?

    Going further, there will be some POSTs and PUTs that I would like only moderators or admins to be able to get access to:

    /* PUT update station/offset/point. */
    router.put(‘/ptso/put/update/:ptid’, textParser, function (req, res) {
    req.sql(“exec update_pt_so_h @ptid, @pts”)
    .param(‘ptid’, req.params.ptid, TYPES.Int)
    .param(‘pts’, req.body, TYPES.NVarChar)

    Any pointers you can give will be appreciated. I’m very new to Express and have been working with React for a couple of months.

    Thanks again for a great tutorial!

  52. Hi bezkoder! Been working with some of your tutorials recently, which have been so great, and I’m trying to get a website up on my namecheap hosting server. When I have the API backend loaded and started server.js, I’m able to successfully register and login through the cPanel terminal using curl commands.

    So today I went through your “Vue.js JWT Authentication with Vuex and Vue Router” tutorial, and everything works in testing when connecting to a MySQL database on my local computer, but after loading my build to the server, I’m getting “net::ERR_CONNECTION_REFUSED”. At first I was getting a CORS error, so I changed the corsOptions origin value to my domain, thinking that would work. I’m no longer getting the CORS error message.. just “net::ERR_CONNECTION_REFUSED”.

    Any ideas? Thank you!!

        1. Hi, the message said that: “username is already in use!”. So did you try to signup with another one?

  53. Hi, great tutorial. btw have u tutorial for logout jwt? and is it good to save jwt in the database?

    1. Hi, we’re gonna save the Refresh Token in the database. I will write a tutorial for this when having time :)

  54. node run server stuck at:
    Executing (default): CREATE TABLE IF NOT EXISTS `roles` (`role_id` INTEGER , `role_code` VARCHAR(255), `role_descr` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`role_id`)) ENGINE=InnoDB;
    Executing (default): SHOW INDEX FROM `roles`

      1. Thanks for your quick reply but I’ve figured out the issue. server was running fine there was some other error in my code.

  55. Great tutorial, thanks a lot.
    Can you implement this with refresh token rotation method.
    Thanks in Advance

  56. bezkoder, excellent tutorial. Complete and well thought out. I’m facing an issue that you have appeared to solve, but for the life of me, I cant replicate from your tutorial into my own code.

    I have react/redux front-end with express.js api.
    Login works and returns a token.
    Attempts to access endpoints with the x-access-token fail from localhost, but succeed from PostMan.

    Attempts from localhost give the below error:
    Access to fetch at ‘https:///dev/buyer’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Request header field x-access-token is not allowed by Access-Control-Allow-Headers in preflight response.

    I have the below cors configuration

    let corsOptions = {
      origin: "http://localhost:3000",

    I dont understand why PostMan would work, but my localhost will not.

    1. Hi, your server should return that it accepts custom headers:

        "x-access-token, Origin, Content-Type, Accept"
  57. Hi,

    I am very new to backend. I follow the tutorial and also clone the repo but always showing the message “Coluld not get any response”. Please let me know what should I have to do. do I need to install any software along. like mySql?

    1. Hi, the example works with MySQL database, so you MUST install MySQL and configure appropriate db parameters :)

    1. If you use a REST Client such as Postman, you call API from the same origin http://localhost:8080. It is ok and CORS doesn’t need to work here.

      But when you send HTTP request from another origin (another front-end app with another port: Angular, React, Vue…), for example: http://localhost:8081, you must accept the Cross-origin resource sharing (CORS). It is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.

  58. I am having an issue with user.setRoles() is not a function in my signUp request:

    “message”: “user.setRoles is not a function”

    1. Hi, please make sure that you’ve initialized Sequelize object and models correctly.

      1. Hi i have the same error, I was wondering if you could explain where the setRoles function is coming from, is it automatically generated?

          1. Hi, thanks for your tutorial :)
            I fixed this issue with an alias :

            db.user.belongsToMany(db.role, {
              through: "Table_User_Roles",
              foreignKey: "idUser",
              otherKey: "idRole",
              as: "roles"

            I hope that help you ;)

  59. Hi really great tutorial.
    how to insert data to multiple tables at a time – parent/child relationship in nodejs to mySql ?
    Could you help me? I’m new to node.js Development.

    Relationship between Product & ProductDetails tables.
    Sample JSON object:

    			"name":"HP 15.6inc 64GB",
    			"name":"Dell 16.4inc 64GB",
    			"name":"Acer 14inc Spin 3",
    			"name":"Refurb HP Spectre x360 ",
      1. Thank you so much , its improves productivity in less time and works fine :)

      2. Hi,
        Really it’s a good tutorial.Is there anyway to generate( swagger integration) some default documentation without writing the API Documentations (comments) manually? Like in ASP.NET core.

        Sample swagger documentation comments in each routing page:
        * @swagger
        * /registerUser:
        * post:
        * tags:
        * – Users
        * name: Register
        * summary: Register a new user
        * consumes:
        * – application/json
        * produces:
        * – application/json
        * parameters:
        * – name: body
        * in: body
        * schema:
        * $ref: ‘#/definitions/User’
        * type: object
        * properties:
        * first_name:
        * type: string
        * last_name:
        * type: string
        * username:
        * type: string
        * email:
        * type: string
        * password:
        * type: string
        * format: password
        * required:
        * – username
        * – email
        * – password
        * responses:
        * ‘200’:
        * description: User created
        * ‘403’:
        * description: Username or email already taken

        Thanks in advance.

    1. You can check out Sequelize, an ORM for Node. It is easy to use and provides ability to represent such relationships

    1. Hi, you can create more routes and controllers, then apply auth middleware on the routes :)

  60. Hi Mr Bezkoder,
    Congratulations on this excellent tutorial. That’s what I’ve been looking for ever since.
    However, I have a hard time integrating this Backend into uen Development FrontEnd React with Redux and JWT Passport.

    Could you help me? I’m new to ReactJS Development.
    Thank you

  61. Thanks for this useful tutorial. When I run the node server.js after cloned the source code from GitHub I have following error. Unfortunately I couldn’t find any solution for that. Do you have any suggestions for that?

    Unhandled rejection SequelizeConnectionRefusedError: connect ECONNREFUSED
    at C:\Users\ShojaMo\webApp\tasktracker\node_modules\sequelize\lib\dialects\mysql\connection-manager.js:123:19
    at tryCatcher (C:\Users\ShojaMo\webApp\tasktracker\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (C:\Users\ShojaMo\webApp\tasktracker\node_modules\bluebird\js\release\promise.js:547:31)
    at Promise._settlePromise (C:\Users\ShojaMo\webApp\tasktracker\node_modules\bluebird\js\release\promise.js:604:18)
    at Promise._settlePromise0 (C:\Users\ShojaMo\webApp\tasktracker\node_modules\bluebird\js\release\promise.js:649:10)
    at Promise._settlePromises (C:\Users\ShojaMo\webApp\tasktracker\node_modules\bluebird\js\release\promise.js:725:18)
    at _drainQueueStep (C:\Users\ShojaMo\webApp\tasktracker\node_modules\bluebird\js\release\async.js:93:12)
    at _drainQueue (C:\Users\ShojaMo\webApp\tasktracker\node_modules\bluebird\js\release\async.js:86:9)
    at Async._drainQueues (C:\Users\ShojaMo\webApp\tasktracker\node_modules\bluebird\js\release\async.js:102:5)
    at Immediate.Async.drainQueues [as _onImmediate] (C:\Users\ShojaMo\webApp\tasktracker\node_modules\bluebird\js\release\async.js:15:14)
    at processImmediate (internal/timers.js:456:21)

    1. Hi, please make sure that you’ve already run MySQL database with correct configuration.

      1. Hi, I’m connecting in my db normaly using MySQL Workbench, but when I try to conect the application with database I have the follow error:

        Unhandled rejection SequelizeConnectionRefusedError: connect ECONNREFUSED

        How said Mohsen , infortunately I couldn’t find any solution for that. Do you have any others suggestions for that?

    2. Actually, I ran the code on Win and Mac and both have the same issue! It looks like something is wrong when it tries to run the database. Thanks in advance for any suggestions.

  62. Bezkoder, your tutorials are just awesome, thank you very much for your work :)
    Maybe u have this version without roles(admin, moder) only user?
    If yes, could you please share it?

    1. Hi, admin or moderator is just a role. You can remove them in the define steps of the model.
      Try your best to do it. :)

  63. Great article loved it..how would implement it with refresh tokens? Thanks in advance

  64. Thanks for sharing your code for this Node.js JWT auth. It works like a charm!

  65. Hi, really Great Tutorial, but i have the problem,
    when Access protected resources: GET /api/test/mod
    Access protected resources: GET /api/test/mod
    Error: Unhandled rejection TypeError: Cannot read property ‘getRoles’ of null

    1. Access protected resources: GET /api/test/admin

      Error: Unhandled rejection TypeError: Cannot read property ‘getRoles’ of null

  66. Can we have a version without serialize please? I already made my tables using serialize messes my erd design :(

      1. hi, their are three rows in roles table with user, moderator and admin names but still when i signup on application, user always becomes user not admin or moderator?
        Please help me with this problem?

  67. Hi. I have a problem whereby every time I start the server through “node server.js” command everything in the database gets reset. It’s making development a bit harder. Can you help with this??

  68. Hi, really Great Tutorial, but i have the problem, that the Signup doesnt work

    I checked out your source code from github, but i get the following message:

    Unhandled rejection Error: WHERE parameter “username” has invalid “undefined” value

    I think it is inside the verifysignup middleware – maybe you can imagine whats wrong?

    Thanks in Advance

    1. Hi, how did you send POST request? Did you set appropriate Header: Content-Type: application/json?

      1. Thank you! In postman, I had to change the content type from Text to JSON, and now it works :)

        For those looking for it, it’s below the text field where you input “http://localhost:8080/api/auth/signup”

    2. shift these lines:
      // routes

      below :

      // parse requests of content-type – application/json

      // parse requests of content-type – application/x-www-form-urlencoded
      app.use(bodyParser.urlencoded({ extended: true }));

      It will work, the issue is routes are called before parsing JSON so it gets undefined in the body.
      Hope this will help someone facing the same issue.
      Thanks a lot, bezkoder for this great tutorial :)

    3. I get a similar error, but when trying just to run the server (node server.js):
      TypeError: Cannot read properties of undefined (reading ‘signup’)
      at module.exports ([project path]\apps\routes\auth.routes.js:19:21)
      at Object. ([project path]\server.js:9:37)

      Since nobody else gets the same error, I’m thinking that I have something amiss in my code, but I checked against the code in GIT and I can’t find any discrepancy. What can you suggest?

      Thank you!

  69. Great Tutorial, thank you very much! It helped very much with my project :) I still have one question though – I hope you’ll be able to help:

    Everything is working and I am trying to build a page where an admin can change the User Roles of a specific user. Right now, I have no Idea what to change or how I would implement this on the backend site. How can I update a User and send a new array of roles to the backend and update the belongsToMany association?

    Thanks in advance!

    1. Hi, you can add a new route with [authJwt.verifyToken, authJwt.isAdmin] middlewares. This route calls controller method that updates just one table: user_roles.

    2. Hi Ben, I’m trying to implement the same thing.
      Did you achieve a solution to it?

  70. Great walkthrough! Helped a lot.
    I like the way that you organize the models, controllers and routes in every tutorial.

      1. Can u provide this in nestjs and in typeorm mysql.
        I need to learn to work with nestjs.

  71. Great job, thanks a lot!
    Just one question, can we integrate this with sequelize migrate due to the fact that it makes the job easier for entitites

    1. Yes, we can. But in this tutorial, I want to keep everything simple and clean, so we don’t use sequelize migrate :)

      1. Thanks a lot, this is the best explanation I’ve found, I’m learning a lot from your articles, If I will find you on social media (Medium and others) I’ll be following you.

      2. Great work, thanks a bunch.
        I have a simple question, you’re using those methods which you didn’t define like user.getRoles() but you never defined these methods. I tried to read on sequelize custom setters and getters but about setters and getters they must be defined on a model but these were used without definition so I wanted to know where they’re coming from.

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