How to Registration REST API using Node JS Express MySQL?




How to Registration REST API using Node JS Express MySQL?

Hello Friends,

In this tutorial, I am going to create simple email and password login authentication and register a user using nodejs and MySQL. I will save the simple password in MySQL database but this is not good practice for security reasons so in the next tutorial

Node Express web framework is the best solution to create RESTful APIs in a quick time. This article will explain to you a more simple way to use external plugins to enrich your project APIs. Here you will find to create GET and POST requests with request payload validations to protect the endpoints.

Step 1: Create Database And Table

Execute the following command on the terminal to create a database and table:




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,


UNIQUE KEY email (email)



Step 2: Create Node Express js App

Execute the following command on the terminal to create the node js app:

mkdir nodejs-auth-rest-api-mysql

cd nodejs-auth-rest-api-mysql

npm init -y

Step 3: Connect 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 the 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 required Modules

Execute the following command on the terminal to install express express-validator MySQL body-parser JSON web token bcryptjs cors into your node js express app:

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

  • Express — Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
  • Express-validator — Express Validator is a set of Express. js middleware that wraps validator. js, a library that provides validator and sanitizer functions. Simply said, Express Validator is an Express middleware library that you can incorporate into your apps for server-side data validation.
  • MySQL — MySQL an open-source relational database management system (RDBMS).
  • body-parser — Express body-parser is an npm library used to process data sent through an HTTP request body. It exposes four express middlewares for parsing text, JSON, URL-encoded and raw data set through an HTTP request body.
  • jsonwebtoken — This module provides Express middleware for validating JWTs (JSON Web Tokens) through the jsonwebtoken module. The decoded JWT payload is available on the request object.
  • bcryptjs — The bcrypt hashing function allows us to build a password security platform that scales with computation power and always hashes every password with a salt.
  • cors — CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.
  • Step 5: Create Server.js File

    Create server.js file and import express express-validator MySQL body-parser JSON web token bcryptjs cors into your server.js file; as shown below:

    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();




    extended: true



    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";


    message: err.message,



    app.listen(3000,() => console.log('Server is running on port 3000'));

    Step 6: Create Validation.js, Router.js

    Create validation.js and router.js. So visit your app root directory and create these files.

    Then add 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 })


    Then add the following code to your router.js file:

    const express = require('express');

    const router = express.Router();

    const db = require('./dbConnection');

    const { signupValidation } = require('./validation');

    const { validationResult } = require('express-validator');

    const bcrypt = require('bcryptjs');

    const jwt = require('jsonwebtoken');'/register', signupValidation, (req, res, next) => {


    `SELECT * FROM users WHERE LOWER(email) = LOWER(${db.escape(


    (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


    `INSERT INTO users (name, email, password) VALUES ('${}', ${db.escape(

    )}, ${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!'










    module.exports = router;

    Step 7: Start Node Express Js App Server

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

    //run the below command

    nodemon server.js

    After running this command open your browser and hit

    Step 8 – Test Rest Apis with PostMan App

    Test node js experss + mysql user registration api with Postman app:

    POST - http://localhost:3000/api/register

    I hope it can help you...

    #Node.js Express

    #Node JS