Build Restful Apis with Node js Express and MySQL Authentication

Create restful apis with node js express and mysql authentication with jwt; In this tutorial; i am going to show you step by step how to build restful apis with node js express and mysql authentication with bcrypt.

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.

Node js rest api user authentication (registration and login apis) using mysql and express tutorial; i will install fresh node js app and then create database with table. And then install some required dependencies like experss, bcrypt mysql validation jwt in this app. And using this dependencies, i will create user authentication rest api in node js express and mysql with jwt bcrypt.

Node js expess User Authentication using MySQL and Express with jwt bcrypt

  • Step 1 – Build Database and Table
  • Step 2 – Create App Directory and Install Node js Express
  • Step 3 – Connect Node js Rest Api App to Database
  • Step 4 – Install express and Some Dependencies
  • Step 5 – Create Main.js File
  • Step 6 – Create Routes and Validation File
  • Step 7 – Run This App Server
  • Step 8 – Apis Testing

Step 1 – Create Database And Table

Run the following command on terminal to create database and table:

CREATE DATABASE node-app
CREATE TABLE users (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  email varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  password varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY email (email)
 ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Step 2 – Create App Directory and Install Node js Express

Run the following command on command prompt to create app directory and install node js app:

mkdir nodejs-auth-rest-api-mysql

cd nodejs-auth-rest-api-mysql

npm init -y

Step 3 – Connect Node js Rest Api App to Database

Create dbConnection.js file into your app root directory add the following code into it to connect your node js express app to database:

var mysql = require('mysql');
var conn = mysql.createConnection({
  host: 'localhost', // Replace with your host name
  user: 'root',      // Replace with your database username
  password: '',      // Replace with your database password
  database: 'my-node' // // Replace with your database Name
}); 
conn.connect(function(err) {
  if (err) throw err;
  console.log('Database is connected successfully !');
});
module.exports = conn;

Step 4 – Install express and Some Dependencies

Run the following command on command prompt to install express express-validator mysql body-parser jsonwebtoken bcryptjs cors into your node js express app:

npm install express express-validator mysql body-parser jsonwebtoken bcryptjs cors --save

Step 5 – Create Main.js File

Create main.js file and import express express-validator mysql body-parser jsonwebtoken bcryptjs cors into your main.js file; as following:

const createError = require('http-errors');
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const indexRouter = require('./router.js');
const app = express();
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(cors());
app.use('/api', indexRouter);
// Handling Errors
app.use((err, req, res, next) => {
    // console.log(err);
    err.statusCode = err.statusCode || 500;
    err.message = err.message || "Internal Server Error";
    res.status(err.statusCode).json({
      message: err.message,
    });
});
app.listen(3000,() => console.log('Server is running on port 3000'));

Step 6 – Create Routes and Validation File

Create two files; these names are following validation.js and router.js. So Go to your app root directory and create this files.

After that, Update the following code into your validation.js file:

const { check } = require('express-validator');
exports.signupValidation = [
    check('name', 'Name is requied').not().isEmpty(),
    check('email', 'Please include a valid email').isEmail().normalizeEmail({ gmail_remove_dots: true }),
    check('password', 'Password must be 6 or more characters').isLength({ min: 6 })
]
exports.loginValidation = [
     check('email', 'Please include a valid email').isEmail().normalizeEmail({ gmail_remove_dots: true }),
     check('password', 'Password must be 6 or more characters').isLength({ min: 6 })
]

Then update the following code into your router.js file:

const express = require('express');
const router = express.Router();
const db  = require('./dbConnection');
const { signupValidation, loginValidation } = require('./validation');
const { validationResult } = require('express-validator');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
router.post('/register', signupValidation, (req, res, next) => {
  db.query(
    `SELECT * FROM users WHERE LOWER(email) = LOWER(${db.escape(
      req.body.email
    )});`,
    (err, result) => {
      if (result.length) {
        return res.status(409).send({
          msg: 'This user is already in use!'
        });
      } else {
        // username is available
        bcrypt.hash(req.body.password, 10, (err, hash) => {
          if (err) {
            return res.status(500).send({
              msg: err
            });
          } else {
            // has hashed pw => add to database
            db.query(
              `INSERT INTO users (name, email, password) VALUES ('${req.body.name}', ${db.escape(
                req.body.email
              )}, ${db.escape(hash)})`,
              (err, result) => {
                if (err) {
                  throw err;
                  return res.status(400).send({
                    msg: err
                  });
                }
                return res.status(201).send({
                  msg: 'The user has been registerd with us!'
                });
              }
            );
          }
        });
      }
    }
  );
});
router.post('/login', loginValidation, (req, res, next) => {
  db.query(
    `SELECT * FROM users WHERE email = ${db.escape(req.body.email)};`,
    (err, result) => {
      // user does not exists
      if (err) {
        throw err;
        return res.status(400).send({
          msg: err
        });
      }
      if (!result.length) {
        return res.status(401).send({
          msg: 'Email or password is incorrect!'
        });
      }
      // check password
      bcrypt.compare(
        req.body.password,
        result[0]['password'],
        (bErr, bResult) => {
          // wrong password
          if (bErr) {
            throw bErr;
            return res.status(401).send({
              msg: 'Email or password is incorrect!'
            });
          }
          if (bResult) {
            const token = jwt.sign({id:result[0].id},'the-super-strong-secrect',{ expiresIn: '1h' });
            db.query(
              `UPDATE users SET last_login = now() WHERE id = '${result[0].id}'`
            );
            return res.status(200).send({
              msg: 'Logged in!',
              token,
              user: result[0]
            });
          }
          return res.status(401).send({
            msg: 'Username or password is incorrect!'
          });
        }
      );
    }
  );
});
router.post('/get-user', signupValidation, (req, res, next) => {
    if(
        !req.headers.authorization ||
        !req.headers.authorization.startsWith('Bearer') ||
        !req.headers.authorization.split(' ')[1]
    ){
        return res.status(422).json({
            message: "Please provide the token",
        });
    }
    const theToken = req.headers.authorization.split(' ')[1];
    const decoded = jwt.verify(theToken, 'the-super-strong-secrect');
    db.query('SELECT * FROM users where id=?', decoded.id, function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results[0], message: 'Fetch Successfully.' });
    });
});
module.exports = router;

Step 7 – Run This App Server

Execute the following command on terminal to start node express js server:

//run the below command

nodemon server.js

after run this command open your browser and hit 

http://127.0.0.1:3000/api/register

Step 8 – Apis Testing

Start your post man app and call the above created apis with the follwing methods:

POST - http://localhost:3000/api/register // Pass name, email and password
 

POST - http://localhost:3000/api/login // pass email and password


POST - http://localhost:3000/api/get-user // pass jwt token

Recommended Node js Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.