Fetch Data from MySQL Using Node.js

Introduction

Node.js is widely used to build applications that store and retrieve information from databases. MySQL is a popular relational database for managing data such as users, products, employees, customers, and orders.

To fetch data from MySQL using Node.js, we can use the mysql2 package to execute SQL SELECT queries. Express.js helps us create APIs that retrieve database records and return them to clients in JSON format.

In this tutorial, you will learn how to connect Node.js to MySQL, fetch all records, retrieve a single record, filter results, implement pagination, handle errors, and test APIs using Postman.

What Does Fetching Data from MySQL Mean?

Fetching data means retrieving existing records from a database. MySQL uses the SELECT statement for this operation.

For example:


SELECT * FROM users;

This query retrieves all records from the users table. Node.js can execute the query and return the results to a browser, mobile application, or another client.

Prerequisites

Before starting, make sure you have installed:

  • Node.js and npm
  • MySQL Server
  • Visual Studio Code or another code editor
  • Postman for API testing

You should also understand basic JavaScript, SQL, and Express.js.

Step 1: Create a Node.js Project

Create a project directory and initialize it:


mkdir node-mysql-fetch
cd node-mysql-fetch
npm init -y

Install the required packages:


npm install express mysql2 dotenv
  • express creates API endpoints.
  • mysql2 connects Node.js to MySQL.
  • dotenv loads configuration from environment variables.

Step 2: Create a MySQL Database

Execute the following SQL statements in MySQL Workbench or another MySQL client:


CREATE DATABASE node_app;
USE node_app;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(150) NOT NULL,
    age INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

INSERT INTO users (name, email, age)
VALUES
('John', 'john@example.com', 30),
('Sarah', 'sarah@example.com', 28),
('David', 'david@example.com', 35);

The users table now contains sample records that we can retrieve through Node.js.

Step 3: Configure Database Credentials

Create a .env file in your project directory:


DB_HOST=localhost
DB_USER=root
DB_PASSWORD=your_password
DB_NAME=node_app
DB_PORT=3306

Replace your_password with your MySQL password.

Create a .gitignore file containing:


node_modules/
.env

This helps prevent database credentials from being committed to a Git repository.

Step 4: Fetch Data from MySQL Using Node.js

Create an app.js file. The following example creates APIs to fetch all users, retrieve a specific user, and search users by name.


const express = require('express');
const mysql = require('mysql2/promise');
require('dotenv').config();

const app = express();

const pool = mysql.createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    port: Number(process.env.DB_PORT) || 3306,
    waitForConnections: true,
    connectionLimit: 10
});

// Fetch users by name
app.get('/api/users/search', async (req, res) => {
    try {
        const name = req.query.name;

        if (typeof name !== 'string' || !name.trim()) {
            return res.status(400).json({
                message: 'Name is required'
            });
        }

        const [users] = await pool.execute(
            'SELECT id, name, email, age FROM users WHERE name LIKE ?',
            [`%${name.trim()}%`]
        );

        res.status(200).json(users);
    } catch (error) {
        console.error('Database error:', error);
        res.status(500).json({
            message: 'Failed to search users'
        });
    }
});

// Fetch all users
app.get('/api/users', async (req, res) => {
    try {
        const [users] = await pool.execute(
            'SELECT id, name, email, age FROM users ORDER BY id DESC'
        );

        res.status(200).json(users);
    } catch (error) {
        console.error('Database error:', error);
        res.status(500).json({
            message: 'Failed to fetch users'
        });
    }
});

// Fetch a single user
app.get('/api/users/:id', async (req, res) => {
    try {
        const id = Number(req.params.id);

        if (!Number.isInteger(id) || id < 1) {
            return res.status(400).json({
                message: 'Invalid user ID'
            });
        }

        const [users] = await pool.execute(
            'SELECT id, name, email, age FROM users WHERE id = ?',
            [id]
        );

        if (users.length === 0) {
            return res.status(404).json({
                message: 'User not found'
            });
        }

        res.status(200).json(users[0]);
    } catch (error) {
        console.error('Database error:', error);
        res.status(500).json({
            message: 'Failed to fetch user'
        });
    }
});

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

Understanding the Code

1. Create a connection pool

mysql.createPool() manages reusable database connections, making it useful for applications that handle multiple requests.

2. Execute a SELECT query

The following code retrieves all users:


const [users] = await pool.execute(
    'SELECT id, name, email, age FROM users'
);

The users variable contains the rows returned by MySQL.

3. Use route parameters

In /api/users/2, the value 2 is available through req.params.id. The API uses it to retrieve one record.

4. Use query parameters

A request such as /api/users/search?name=John provides the search term through req.query.name. The SQL LIKE operator finds matching names.

5. Handle empty results

If a specific user does not exist, the query returns an empty array. Checking users.length allows the API to return a meaningful 404 Not Found response.

6. Use parameterized queries

The ? placeholder separates SQL instructions from supplied values. This helps protect against SQL injection and is preferable to building queries through string concatenation.

Step 5: Fetch Data with Filtering and Pagination

You can filter records using a WHERE condition:


const [users] = await pool.execute(
    'SELECT id, name, email FROM users WHERE age >= ?',
    [25]
);

This query retrieves users whose age is at least 25.

For large tables, pagination helps avoid returning too many records in one response:


const page = 2;
const limit = 10;
const offset = (page - 1) * limit;

const [users] = await pool.execute(
    'SELECT id, name, email FROM users ORDER BY id DESC LIMIT ? OFFSET ?',
    [limit, offset]
);

This retrieves 10 records after skipping the first 10. In a real API, validate page and limit values before using them.

Step 6: Test the API Using Postman

Start the application:


node app.js

You should see:


Server running on port 3000

Test the following GET requests in Postman or your browser:

  • Fetch all users: http://localhost:3000/api/users
  • Fetch one user: http://localhost:3000/api/users/2
  • Search by name: http://localhost:3000/api/users/search?name=John

A successful request for a single user may return:


{
    "id": 2,
    "name": "Sarah",
    "email": "sarah@example.com",
    "age": 28
}

The actual ID and response depend on the records in your database.

You can also test the endpoints using cURL:


curl http://localhost:3000/api/users
curl http://localhost:3000/api/users/2

Common Mistakes and Best Practices

Avoid these common mistakes when fetching MySQL data with Node.js:

  1. Using SQL string concatenation: Use parameterized queries for user-supplied values.
  2. Fetching unnecessary columns: Select only the fields your application needs instead of always using SELECT *.
  3. Ignoring empty results: Return 404 Not Found when a requested individual record does not exist.
  4. Exposing database errors: Log technical details on the server and return a general error message to clients.
  5. Fetching too many records: Use pagination, filtering, and appropriate database indexes for large datasets.
  6. Skipping input validation: Validate route parameters, search terms, and pagination values.

Common HTTP status codes include 200 OK for successful retrieval, 400 Bad Request for invalid input, 404 Not Found for a missing record, and 500 Internal Server Error for unexpected failures.

Conclusion

Fetching data from MySQL using Node.js is an important skill for building database-driven applications. With mysql2 and Express.js, you can retrieve all records, fetch individual users, search data, and implement pagination through REST APIs.

By using parameterized queries, validating input, handling errors, and returning appropriate HTTP status codes, you can build more reliable and secure database applications.

Fetch Data from MySQL Using Node.js – Interview Questions

Q 1: How do you fetch data from MySQL using Node.js?
Ans: Use the mysql2 package to execute a SELECT query.
Q 2: What is the purpose of SELECT in MySQL?
Ans: It retrieves records from one or more database tables.
Q 3: What is req.params?
Ans: It contains route parameters, such as the user ID in /api/users/2.
Q 4: What is req.query?
Ans: It contains query-string parameters, such as the name in /api/users/search?name=John.
Q 5: Why are parameterized queries important?
Ans: They separate SQL instructions from supplied values and help protect against SQL injection.