In this tutorial, you will learn how to make user registration REST API in node.js express and MySQL using jwt bcrypt.
How to Make Registration rest API in Node js with MySQL
Steps to create registration or signup rest api with MySQL in Node js express:
Step 1 – Create a Database And Table
Run the following command on the terminal to create a 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 Node Express js App
Run the following command on the terminal to create node js app:
mkdir nodejs-auth-rest-api-mysql cd nodejs-auth-rest-api-mysql npm init -y
Step 3 – Connect the App to the Database
Create dbConnection.js file into your app root directory and 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
Run the following command on the terminal 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 Server.js File
Create a server.js
file and import express express-validator mysql body-parser jsonwebtoken bcryptjs cors
in it:
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 Validation.js, Router.js
Create validation.js, and add the following code to 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 }) ]
Create router.js file, and add the following code to it:
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'); 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!' }); } ); } }); } } ); }); module.exports = router;
Step 7 – Test Application
Run the following command on terminal to start node express js server:
//run the below command
nodemon server.js
Test node js express + mysql user registration API with Postman app:
POST - http://localhost:3000/api/register
Conclusion
Registration/Signup rest API in Node js using MySQL and express js jwt bcrypt example; Through this tutorial, you have learned how to build user registration REST API in node.js express and MySQL with jwt bcrypt.