Skip to content
  • Github
  • Facebook
  • twitter
  • About Us
  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Site Map

XpertPhp

Expertphp Is The Best Tutorial For Beginners

  • Home
  • Javascript
    • Jquery
    • React JS
    • Angularjs
    • Angular
    • Nodejs
  • Codeigniter
  • Laravel
  • Contact Us
  • About Us
  • Live Demos
Node Js JWT Authentication Tutorial with Example

Node Js JWT Authentication Tutorial with Example

Posted on October 8, 2021December 11, 2022 By XpertPhp

In this article, we will learn how to implement JWT authentication example with Express, Sequelize & MySQL in node js(Node Js JWT Authentication Tutorial with Example). so we will give you a simple example of how to generate jwt token in node js(jwt node js example).

In this example, we use the Jsonwebtoken(JWT) npm package for authentication in Node.js(JWT Authentication with Node js). we will show you step by step to create Node.js Restful CRUD API with JWT authentication, Sequelize with MySQL.

So you can see our node js example.

Application Directory Structure

We have created the best directory structure for the rest API CRUD operations. so you can follow the directory structure below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/nodejs_rest_api
  /app
    /config
      db.config.js
      env.js
    /controller
      user.controller.js
    /middleware
      auth.js
    /model
      user.model.js
    /route
      user.route.js
  /node_modules
  package.json
  server.js

Create Node Js Application

First, we will open the command prompt and create the application in our directory. for this, you can follow the below command.

1
2
mkdir nodejs_rest_api
cd my_node_app

The run “npm init” command through we can create a new package.json file in our application directory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
npm init
name: (nodejs_rest_api)
version: (1.0.0)
description:
entry point: (index.js) server.js
test command:
git repository:
keywords:
author:
license: (ISC)
 
Is this ok? (yes) yes
 
 
{
  "name": "nodejs_rest_api",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Install NPM Package

After the done setup node js application, we will install the express, sequelize, bcryptjs, body-parser jsonwebtoken, mysql2 and cors npm package. so you can see the following npm command.

1
npm install express sequelize mysql2 cors bcryptjs body-parser jsonwebtoken --save

Setup Express web server

In this step, We will create the server.js file in our application directory. after then setup the our application.
server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const express = require("express");
const cors = require("cors");
const bodyParser   = require('body-parser');
const app = express();
 
 
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
 
const db = require('./app/config/db.config.js');
force: true will drop the table if it already exists
db.sequelize.sync({force: true}).then(() => {
    console.log('Drop and Resync with { force: true }');
});
 
// api routes
app.get("/", (req, res) => {
  res.json({ message: "Welcome to Our App." });
});
 
require('./app/route/user.route.js')(app);
 
// set port, listen for requests
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

Setting up Sequelize MySQL connection

In this step, we will create .env file and setup database connection using the sequelize with mysql.
app/config/env.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const env = {
  database: 'myapidb',
  username: 'root',
  password: "",
  host: 'localhost',
  dialect: 'mysql',
  pool: {
  max: 5,
  min: 0,
  acquire: 30000,
  idle: 10000
  }
};
 
module.exports = env;

app/config/db.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const env = require('./env.js');
 
const Sequelize = require('sequelize');
const sequelize = new Sequelize(env.database, env.username, env.password, {
  host: env.host,
  dialect: env.dialect,
  operatorsAliases: false,
 
  pool: {
    max: env.max,
    min: env.pool.min,
    acquire: env.pool.acquire,
    idle: env.pool.idle
  }
});
 
const db = {};
 
db.Sequelize = Sequelize;
db.sequelize = sequelize;
 
//Models/tables
db.users = require('../model/user.model.js')(sequelize, Sequelize);
 
 
module.exports = db;

Create Sequelize model

Now, We create the sequelize model and which is define database schema to this sequelize model. so you can see user.model.js file as example.
app/model/user.model.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
module.exports = (sequelize, Sequelize) => {
const User = sequelize.define('users', {
  firstname: {
type: Sequelize.STRING
  },
  lastname: {
type: Sequelize.STRING
  },
  email: {
  type: Sequelize.STRING
  },
  password: {
type: Sequelize.STRING
  }
});
 
 
return User;
}

Create controller

Here, we create some different methods such as findall, findById, update, delete, signup and signin. which is helpful for getting data, insert data and update data with mysql. here all data access by using token. means if you access any route then you must sign in and get the token and for every request you must pass the token. after then you can access it.
app/controller/user.controller.js

See also  How to Get Client IP Address in Node JS Application

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
const db = require('../config/db.config.js');
var jwt = require("jsonwebtoken");
var bcrypt = require("bcryptjs");
const env = require('../config/env.js');
 
const User = db.users;
 
// FETCH all Users
exports.findAll = (req, res) => {
User.findAll().then(users => {
  // Send all users to Client
  res.send(users);
});
};
 
// Find a User by Id
exports.findById = (req, res) => {
User.findById(req.params.userId).then(user => {
res.send(user);
})
};
// Update a User
exports.update = (req, res) => {
const id = req.params.userId;
User.update( { firstname: req.body.firstname, lastname: req.body.lastname, email: req.body.email },
{ where: {id: req.params.userId} }
).then(() => {
res.status(200).send({ message: 'updated successfully a user with id = ' + id });
});
};
// Delete a User by Id
exports.delete = (req, res) => {
const id = req.params.userId;
User.destroy({
  where: { id: id }
}).then(() => {
  res.status(200).send({ message: 'deleted successfully a user with id = ' + id });
});
};
 
 
 
exports.signup = (req, res) => {
//Check Email
    User.findOne({
where: {
  email: req.body.email
}
  }).then(user => {
if (user) {
  res.status(400).send({message: "Failed! Email is already in use!"});
}else{
//create User
User.create({
firstname: req.body.firstname,
lastname: req.body.lastname,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8)
})
.then(user => {
res.status(200).send({ message: "User was registered successfully!" });
})
.catch(err => {
res.status(500).send({ message: err.message });
});
}
});
  };
 
 
  exports.signin = (req, res) => {
User.findOne({
  where: {
email: req.body.email
  }
})
  .then(user => {
if (!user) {
  return res.status(404).send({ message: "User Not found." });
}else{
var passwordIsValid = bcrypt.compareSync(
req.body.password,
user.password
);
if (!passwordIsValid) {
return res.status(401).send({
accessToken: null,
message: "Invalid Password!"
});
}
var token = jwt.sign({ id: user.id }, env.JWT_ENCRYPTION, {
expiresIn:60 * 60 * 24 // 24 hours
});
res.status(200).send({
id: user.id,
email: user.email,
accessToken: token
});
}
  })
  .catch(err => {
res.status(500).send({ message: err.message });
  });
  };

Create middleware for authentication

Now, we will create the JWT middleware in node js. which is every time check this route is authorized or not. so it is a very helpful file.
app/middleware/auth.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const jwt = require("jsonwebtoken");
const env = require('../config/env.js');
const db = require('../config/db.config.js');
 
 
verifyToken = (req, res, next) => {
let token = req.headers['x-access-token'] || req.headers['authorization'];
if(token && token.startsWith('Bearer ')){
token = token.slice(7, token.length)
}
if (!token) {
  return res.status(403).send({
message: "A token is required for authentication"
  });
}
 
jwt.verify(token, env.JWT_ENCRYPTION, (err, decoded) => {
  if(err){
console.log(err);
return res.status(401).send({
  message: "Invalid Token!"
});
  }else{
req.user = decoded.id;
next();
//res.status(200).send({ message: "successs" });
  }
});
};
 
module.exports = verifyToken;

Create Route

Now, We will define all user’s routes. so you can see our route example.
app/route/user.route.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const auth = require('../middleware/auth.js');
module.exports = function(app) {
    const users = require('../controller/user.controller.js');
  
    // Retrieve all User
    app.get('/api/users',auth, users.findAll);
    // Retrieve a single User by Id
    app.get('/api/users/:userId', users.findById);
    // Update a User with Id
    app.put('/api/users/:userId',auth, users.update);
    // Delete a User with Id
    app.delete('/api/users/:userId',auth, users.delete);
 
    // User signup
    app.post('/api/user/signup', users.signup);
    
    // User signin
    app.post('/api/user/signin', users.signin);
}

Run Node js Application

we will run the node js application using the below command. so you can follow the below command.

1
node server.js

Now you can run the example using the below Url in the browser.

1
http://localhost:3000/

Nodejs

Post navigation

Previous Post: Node js Express Sequelize and Mysql Example
Next Post: Node js Session Management Using Express Session

Latest Posts

  • Laravel 12 Ajax CRUD Example
  • Laravel 12 CRUD Example Tutorial
  • How to Create Dummy Data in Laravel 11
  • Laravel 11 Yajra Datatables Example
  • Laravel 11 Ajax CRUD Example
  • Laravel 11 CRUD Example Tutorial
  • Laravel 10 Ajax CRUD Example Tutorial
  • Laravel 10 CRUD Example Tutorial
  • How to disable button in React js
  • JavaScript Interview Questions and Answers

Tools

  • Compound Interest Calculator
  • Hex to RGB Color Converter
  • Pinterest Video Downloader
  • Birthday Calculator
  • Convert JSON to PHP Array Online
  • JavaScript Minifier
  • CSS Beautifier
  • CSS Minifier
  • JSON Beautifier
  • JSON Minifier

Categories

  • Ajax
  • Angular
  • Angularjs
  • Bootstrap
  • Codeigniter
  • Css
  • Htaccess
  • Interview
  • Javascript
  • Jquery
  • Laravel
  • MongoDB
  • MySql
  • Nodejs
  • Php
  • React JS
  • Shopify Api
  • Ubuntu

Tags

angular 10 tutorial angular 11 ci tutorial codeigniter 4 image upload Codeigniter 4 Tutorial codeigniter tutorial CodeIgniter tutorial for beginners codeigniter with mysql crud operation eloquent relationships file upload File Validation form validation Image Upload jQuery Ajax Form Handling jquery tutorial laravel 6 Laravel 6 Eloquent Laravel 6 Model laravel 6 relationship laravel 6 relationship eloquent Laravel 6 Routing laravel 7 Laravel 7 Eloquent laravel 7 routing laravel 7 tutorial Laravel 8 laravel 8 example laravel 8 tutorial laravel 9 example laravel 9 tutorial Laravel Framework laravel from scratch laravel social login learn jquery nodejs pagination payment gateway php with mysql react js example react js tutorial send mail validation wysiwyg editor wysiwyg html editor

Copyright © 2018 - 2025,

All Rights Reserved Powered by XpertPhp.com