MySQL in Node.js

What is Node.js

Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser.

What is MySQL

MySQL is an open-source relational database management system. Its name is a combination of “My”, the name of co-founder Michael Widenius’s daughter, and “SQL”, the abbreviation for Structured Query Language.


  1. You should have strong knowledge of Javascript.
  2. Basic knowledge of Node.js and Express.js.

Creating Express.js App using Node.js

To get started we will first initialize npm in our backend by executing the below command.

Now once its initialized, lets install the required packages by executing the below command.

Setting up Node.js App

Next I will create a file called as server.js and the basic structure of our backend in Express.js.

Setting up MYSQL

To start using MySQL I will be using MySQL workbench to execute queries and I will be using XAMPP to run MySQL server.

MySQL Workbench

Creating connection of MySQL and integrating it in your backend.

By default your MySQL credentials will be as follows:

Now we will integrate MySQL with our backend.

Before integrating our database with our backend I execute the below commands in MySQL workbench to create database, create a table and insert record.

Now we have a database named as testDB with some user data in it containing username and password.

Writing a Query

Now in ‘get’ request I am writing and executing the basic query and selecting data that exist in testDB user table.

Now the image will show that what will our root route looks like after running the select query and sending it to the web browser.

This is the data that is stored in our database. We are showing the db data on browser.

We are handling the error if an error will occur I will log that error on console. It can be a connection error, invalid query error etc.

Now the above error is occurring since I have deliberately made a mistake in our query to replicate an error.

Now you might have better understanding on how to connect MySQL with Node.js. Please comment if you like this article and want to see a full video tutorial on my Youtube channel.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Musab Abbasi

Musab Abbasi


Computer Science Graduate with MERN stack website development expertise.