Building a Simple Backend with NodeJS, MySQL, Sequelize, and Express

Introduction
Node.js has become one of the most popular backend development frameworks in recent years. It is an open-source, cross-platform JavaScript runtime environment that allows developers to build scalable and high-performance web applications. As a starter backend developer, I chose Node.js as it is a popular JavaScript runtime that allows for server-side development. It is also lightweight and fast, making it ideal for building scalable applications. Additionally, I chose MySQL as my database management system as it is open-source and widely used, making it easy to find resources and support. Sequelize was chosen as the Object-Relational Mapping (ORM) tool as it simplifies database interactions and makes it easy to work with relational databases. Finally, I chose Express as my web application framework as it is minimalistic yet powerful, making it easy to build robust APIs and web applications.
One common challenge faced when building a backend with these technologies is setting up the environment and configuring the dependencies. To overcome this, I made sure to follow the documentation and best practices provided by the respective technologies. I also utilized online resources such as StackOverflow and GitHub to find solutions to any issues encountered. Additionally, I made sure to test my code thoroughly and implement error handling to ensure the smooth running of the application. In this article, we will discuss how to build a simple backend with Node.js, using MySQL as the database and Sequelize as the ORM, and Express as the framework.
Setting up the Environment
Before we dive into the code, let’s set up the environment. We begin by installing Node.js and npm (Node Package Manager) on our system then we create a new directory for our project and initialize it with npm.
mkdir myproject
cd myproject
npm init -yThis creates a package.json file in our project directory that will keep track of all the dependencies and configurations of our project.
Installing Dependencies
We then install and use the express module to create our API endpoints, mysql2 module to connect to MySQL database, and sequelize module as an ORM to interact with the database.
npm install express mysql2 sequelizeWe install nodemon as a development dependency. Nodemon automatically restart our server whenever we make changes to our code.
npm install nodemon --save-devCreating the Database
Let’s create a MySQL database for our project. We can use any MySQL client like phpMyAdmin or MySQL Workbench to create the database. Alternatively, we can use the MySQL CLI to create the database.
mysql -u root -pCREATE DATABASE mydatabase;Creating the Server
Now that we have set up our environment and installed the necessary dependencies, we start building our server. Create a new file called server.js in the root directory of your project and add the following code.
const express = require('express');
const { Sequelize } = require('sequelize');
const app = express();
// Connect to MySQL database from the server
const sequelize = new Sequelize('mydatabase', 'root', '', {
dialect: 'mysql',
host: 'localhost',
});
// Define a model
const User = sequelize.define('User', {
name: Sequelize.STRING,
email: Sequelize.STRING,
});
// Sync the model with the database
sequelize.sync();
// Middleware
app.use(express.json());
// Protection middleware
app.use((req, res, next) => {
const token = req.headers.authorization;
if (token !== 'secret-token') { //will be replaced when env is introduced
return res.status(401).json({ message: 'Unauthorized' });
}
next();
});
// Endpoints
app.get('/users', async (req, res) => {
const users = await User.findAll();
res.json(users);
});
app.post('/users', async (req, res) => {
const { name, email } = req.body;
const user = await User.create({ name, email });
res.json(user);
});
// Start the server
app.listen(3000, () => {
console.log('Server started on port 3000');
});In the above code, we have created an instance of Express and connected to the MySQL database using Sequelize. We have defined a User model with name and email fields. We have also added two endpoints — /users to get all users and /users to create a new user. We have also added a protection middleware that checks for a secret token in the request headers.
Testing the API
We can test our API using any REST client like Postman or Insomnia. Start the server using nodemon server.js and send a GET request to http://localhost:3000/users. You should get an empty array as the response. Now send a POST request to http://localhost:3000/users with the following JSON payload.
{
"name": "John Doe",
"email": "johndoe@example.com"
}You should get a JSON response with the newly created user.
{
"id": 1,
"name": "John Doe",
"email": "johndoe@example.com",
"updatedAt": "2022-01-01T00:00:00.000Z",
"createdAt": "2022-01-01T00:00:00.000Z"
}Conclusion
In this article, we have learned how to set up a Node.js environment, install dependencies, create a MySQL database, and build a simple server using Express and Sequelize. These technologies provide a powerful and efficient way to build scalable and high-performance web applications. With the knowledge gained from this article, you can now start building your own backend applications using Node.js.