Node.js SQL Injection Prevention – Complete Guide with Examples

Introduction

Node.js is widely used to build web applications, REST APIs, and backend services that connect to databases such as MySQL and PostgreSQL. Whenever an application accepts user input and uses it in an SQL query, it must handle that input carefully.

One common security risk is SQL injection. It occurs when an attacker manipulates user input to change the meaning of a database query. If an application builds SQL statements by directly combining strings with user input, an attacker may be able to access unauthorized data, bypass login checks, or modify database records.

The good news is that SQL injection can usually be prevented by following secure database programming practices. In Node.js, the most important technique is to use parameterized queries or prepared statements instead of concatenating user input into SQL strings.

In this tutorial, you will learn how SQL injection works, how to prevent it using Node.js and Express.js, and which security practices help protect database-driven applications.

What Is SQL Injection?

SQL injection is a security vulnerability in which an attacker supplies specially crafted input that changes the structure or behavior of an SQL query.

Consider a login query that checks a user’s email and password:


SELECT * FROM users
WHERE email = 'user@example.com'
AND password = 'mypassword';

This query is intended to find a user whose email and password match the supplied values.

However, if the application directly inserts user input into the query string, an attacker may provide input containing SQL syntax. Depending on how the query is constructed, that input could alter the conditions of the query.

SQL injection can potentially allow an attacker to:

  • Bypass authentication checks.
  • Read information they are not authorized to access.
  • Modify or delete database records.
  • Access sensitive business information.
  • Interfere with the availability or integrity of an application.

The impact depends on the database permissions, query construction, and security controls in place.

How SQL Injection Happens in Node.js

SQL injection commonly occurs when an application builds a query using string concatenation or template literals containing untrusted input.

For example, consider this Express.js route using the mysql2 package:


const express = require("express");
const mysql = require("mysql2");

const app = express();

app.use(express.json());

const connection = mysql.createConnection({
    host: "localhost",
    user: "app_user",
    password: process.env.DB_PASSWORD,
    database: "company_db"
});

app.get("/users", (req, res) => {
    const name = req.query.name;

    const sql = `SELECT id, name, email
                 FROM users
                 WHERE name = '${name}'`;

    connection.query(sql, (err, results) => {
        if (err) {
            return res.status(500).json({
                message: "Database query failed"
            });
        }

        res.json(results);
    });
});

app.listen(3000);

What Is Wrong With This Code?

The application inserts req.query.name directly into the SQL statement.

The database receives a query whose structure can be influenced by the supplied input. An attacker may exploit this behavior to change the intended query.

Important: Checking whether an input is a string or removing a few special characters does not reliably solve the problem. SQL syntax varies, and manual escaping is easy to implement incorrectly.

The correct solution is to separate the SQL statement from the values supplied by the user.

1. Use Parameterized Queries

Parameterized queries are the primary defense against SQL injection.

Instead of inserting a value directly into the SQL string, use a placeholder and pass the value separately. The database driver then handles the value as data rather than treating it as part of the SQL syntax.

Example Using MySQL and mysql2

Install the required packages:


npm install express mysql2 dotenv

Create a .env file for local development:


DB_HOST=localhost
DB_USER=app_user
DB_PASSWORD=your_database_password
DB_NAME=company_db
PORT=3000

Load environment variables at the beginning of your application:


require("dotenv").config();

Keep .env out of version control and do not commit real credentials to your repository.

Now use a parameterized query:


const express = require("express");
const mysql = require("mysql2");

const app = express();

app.use(express.json());

const connection = mysql.createConnection({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME
});

app.get("/users", (req, res) => {
    const name = req.query.name;

    const sql = `
        SELECT id, name, email
        FROM users
        WHERE name = ?
    `;

    connection.query(sql, [name], (err, results) => {
        if (err) {
            console.error("Database query failed:", err);

            return res.status(500).json({
                message: "Unable to retrieve users"
            });
        }

        res.json(results);
    });
});

app.listen(process.env.PORT || 3000);

How Does This Prevent SQL Injection?

The ? symbol is a placeholder for a value. The value is passed separately through the array [name].


connection.query(sql, [name], callback);

The SQL statement defines the query structure, while the parameter supplies the value to compare against the name column.

Even if a user supplies text containing SQL operators or quotation marks, it is treated as a parameter value rather than being inserted as executable SQL syntax.

Remember: With mysql2, connection.query(sql, values) performs client-side placeholder formatting and escaping. For true server-side prepared statements, use connection.execute(sql, values) where supported.

2. Use Prepared Statements with mysql2

Prepared statements provide another important defense against SQL injection. They allow the database driver to prepare a statement and supply its values separately.

With mysql2, you can use execute() for this purpose.


app.get("/users/:id", (req, res) => {
    const userId = req.params.id;

    const sql = `
        SELECT id, name, email
        FROM users
        WHERE id = ?
    `;

    connection.execute(sql, [userId], (err, results) => {
        if (err) {
            console.error("Database query failed:", err);

            return res.status(500).json({
                message: "Unable to retrieve user"
            });
        }

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

        res.json(results[0]);
    });
});

Here, the user ID is passed separately from the SQL statement. The query does not directly insert the supplied ID into the SQL text.

You should still validate the ID to ensure that it has the expected format. For example, if your application uses positive integer IDs, reject values that are not positive integers.

Prepared statements help prevent SQL injection, while validation helps ensure that input makes sense for your application.

3. Validate User Input

Input validation is an additional security layer. It helps ensure that incoming data follows the format and rules expected by your application.

For example, if an API expects a numeric user ID, validate it before accessing the database.


app.get("/users/:id", (req, res) => {
    const userId = Number(req.params.id);

    if (!Number.isSafeInteger(userId) || userId <= 0) {
        return res.status(400).json({
            message: "Invalid user ID"
        });
    }

    const sql = `
        SELECT id, name, email
        FROM users
        WHERE id = ?
    `;

    connection.execute(sql, [userId], (err, results) => {
        if (err) {
            console.error("Database query failed:", err);

            return res.status(500).json({
                message: "Unable to retrieve user"
            });
        }

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

        res.json(results[0]);
    });
});

This example combines two protections:

  • Input validation: Rejects values that do not match the expected ID format.
  • Parameterized query: Prevents the supplied ID from changing the SQL statement’s structure.

Validation alone is not a replacement for parameterized queries. Use both where appropriate.

4. Never Build SQL Queries Using User Input

Avoid concatenating untrusted values into SQL statements, even when using modern JavaScript syntax.

Unsafe Example


const email = req.body.email;

const sql =
    "SELECT id, email FROM users WHERE email = '" +
    email + "'";

connection.query(sql, callback);

Safe Example


const email = req.body.email;

const sql = `
    SELECT id, email
    FROM users
    WHERE email = ?
`;
connection.execute(sql, [email], callback);

The safe version keeps the query structure separate from the supplied value.

The same principle applies to INSERT, UPDATE, and DELETE statements.

INSERT Example


const sql = `
    INSERT INTO users (name, email)
    VALUES (?, ?)
`;
connection.execute(
    sql,
    [req.body.name, req.body.email],
    (err, result) => {
        if (err) {
            console.error("Database insert failed:", err);
            return res.status(500).json({
                message: "Unable to create user"
            });
        }
        res.status(201).json({
            message: "User created successfully",
            id: result.insertId
        });
    }
);

UPDATE Example


const sql = `
    UPDATE users
    SET name = ?
    WHERE id = ?
`;

connection.execute(
    sql,
    [req.body.name, req.params.id],
    (err) => {
        if (err) {
            console.error("Database update failed:", err);

            return res.status(500).json({
                message: "Unable to update user"
            });
        }

        res.json({
            message: "User update request completed"
        });
    }
);

DELETE Example


const sql = "DELETE FROM users WHERE id = ?";

connection.execute(
    sql,
    [req.params.id],
    (err) => {
        if (err) {
            console.error("Database delete failed:", err);

            return res.status(500).json({
                message: "Unable to delete user"
            });
        }

        res.json({
            message: "Delete request completed"
        });
    }
);

For production applications, validate request bodies and route parameters, check authorization before modifying records, and verify the number of affected rows where appropriate.

5. Handle Dynamic Column Names and Sorting Safely

Parameterized queries work for values, not SQL identifiers such as table names, column names, or keywords like ASC and DESC.

For example, this does not safely parameterize a column name:


const sql = "SELECT id, name FROM users ORDER BY ?";

A placeholder in this position is treated as a value, not as a dynamically selected column identifier. The query will not behave as intended.

A safer approach is to allow only predefined column names and sort directions.


app.get("/users", (req, res) => {
    const allowedColumns = {
        name: "name",
        email: "email",
        created: "created_at"
    };

    const requestedSort = req.query.sort;
    const sortColumn = allowedColumns[requestedSort] || "name";

    const sortDirection =
        req.query.direction === "desc" ? "DESC" : "ASC";

    const sql = `
        SELECT id, name, email
        FROM users
        ORDER BY ${sortColumn} ${sortDirection}
    `;

    connection.query(sql, (err, results) => {
        if (err) {
            console.error("Database query failed:", err);

            return res.status(500).json({
                message: "Unable to retrieve users"
            });
        }

        res.json(results);
    });
});

This example is safe from SQL injection through these two sorting parameters because:

  • sortColumn can only be one of the hard-coded column names.
  • sortDirection can only be ASC or DESC.
  • Neither SQL fragment is inserted directly from untrusted input.

Use this allowlist pattern whenever an application must dynamically select identifiers or SQL fragments. Do not use arbitrary request values for table names, column names, or sort expressions.

6. Use an ORM or Query Builder Carefully

Object-relational mapping (ORM) libraries and query builders can reduce the amount of SQL that developers write manually. Examples include Sequelize, Prisma, and Knex.

When used correctly, their normal query APIs help separate values from SQL syntax.

For example, with Sequelize:


const users = await User.findAll({
    where: {
        name: req.query.name
    },
    attributes: ["id", "name", "email"]
});

This uses a structured query API instead of manually concatenating the user’s input into an SQL string.

However, using an ORM does not automatically make every database operation safe. Raw SQL queries, manually constructed conditions, and unsafe handling of dynamic identifiers can still introduce vulnerabilities.

Follow the library’s documented parameterization practices, and review any raw-query functionality carefully.

7. Use Least-Privilege Database Accounts

Your Node.js application should connect to the database using an account with only the permissions it needs.

For example, a service that only reads user records should not require permission to drop tables or change database users.

Recommended practices include:

  • Create a dedicated database account for the application.
  • Grant only the required permissions.
  • Use separate credentials for development, testing, and production.
  • Keep database credentials in environment variables or a managed secrets system.
  • Rotate credentials when necessary.
  • Restrict database network access to trusted services.

Least privilege does not replace parameterized queries, but it can reduce the potential damage if an application vulnerability is exploited.

8. Handle Database Errors Securely

Database errors can contain SQL statements, table names, schema information, and other implementation details. Returning these details directly to users can expose information that helps an attacker understand the application.

Avoid responses such as:


res.status(500).send(err);

Instead, log useful details on the server and return a generic response to the client.


connection.execute(sql, values, (err, results) => {
    if (err) {
        console.error("Database operation failed:", err);
        return res.status(500).json({
            message: "An internal server error occurred"
        });
    }
    res.json(results);
});

In production, use a proper logging system with access controls, and avoid logging passwords, authentication tokens, or other sensitive values.

Do not expose raw database errors in API responses.

9. Test Your Application for SQL Injection

Testing helps identify unsafe query construction and confirms that your security controls behave as expected.

Consider the following checks:

  1. Review database queries for string concatenation involving request parameters or request-body values.
  2. Test search, login, filtering, sorting, and record-management endpoints.
  3. Verify that values containing quotes or SQL-like text are handled as ordinary data.
  4. Confirm that invalid input receives an appropriate validation error.
  5. Check that database errors do not reveal internal SQL or schema details.
  6. Use authorized security-testing tools to examine your application in a controlled environment.
  7. Include SQL injection checks in code reviews and automated security testing.

Never test against systems or databases you do not own or have permission to assess.

A successful security test should verify that untrusted input cannot alter the intended query structure, rather than relying only on whether a particular input produces an error.

Common SQL Injection Prevention Mistakes

Mistake Better Approach
Concatenating user input into SQL Use parameterized queries or prepared statements
Removing a few special characters Keep SQL values separate from query syntax
Relying only on input validation Combine validation with parameterization
Assuming an ORM makes every query safe Review raw SQL and dynamic query construction
Passing user input as a column name Use a strict allowlist of permitted identifiers
Returning raw database errors Log errors securely and return generic messages
Using a database administrator account in the app Apply least-privilege permissions
Storing credentials directly in source code Use environment variables or managed secrets

SQL Injection Prevention Best Practices

Follow these practices when developing Node.js applications that connect to a database:

  • Use parameterized queries or prepared statements for all untrusted values.
  • Validate input according to the expected type, format, and business rules.
  • Use allowlists for dynamic table names, column names, and sort directions.
  • Use ORM or query-builder APIs carefully, especially when raw SQL is involved.
  • Give the application database account only the permissions it requires.
  • Store database credentials securely and keep them out of version control.
  • Handle database errors without exposing internal implementation details.
  • Review database access code during code reviews.
  • Keep Node.js, database drivers, and dependencies updated.
  • Test security controls regularly and monitor suspicious application activity.

Conclusion

SQL injection is a serious risk for Node.js applications that communicate with databases, but developers can prevent many common SQL injection vulnerabilities by following secure query practices.

The most important rule is to never combine untrusted input directly with an SQL statement. Use parameterized queries or prepared statements, validate input, allowlist dynamic SQL identifiers, and apply least-privilege database permissions.

These techniques work together to protect the integrity of database operations and help you build more secure Node.js and Express.js applications.

When working with MySQL, mysql2 provides parameterized queries through query() and prepared-statement support through execute(). Similar safe query patterns are available in other database drivers and libraries, including PostgreSQL clients and popular Node.js ORMs.

Related Node.js Tutorials