0
0
NodejsDebug / FixBeginner · 4 min read

How to Prevent SQL Injection in Node.js: Safe Database Queries

To prevent SQL injection in Node.js, always use parameterized queries or prepared statements provided by your database library instead of building SQL strings manually. This ensures user input is treated as data, not code, stopping attackers from injecting harmful SQL.
🔍

Why This Happens

SQL injection happens when user input is directly added into a SQL query string without checks. Attackers can add SQL code that changes the query's meaning, leading to data leaks or damage.

javascript
const userInput = "' OR '1'='1";
const query = `SELECT * FROM users WHERE username = '${userInput}'`;
// This query becomes: SELECT * FROM users WHERE username = '' OR '1'='1'
// which returns all users, bypassing login checks.
Output
The query returns all users, ignoring intended username filtering, causing a security breach.
🔧

The Fix

Use parameterized queries to separate SQL code from data. This way, user input is never executed as SQL but treated as a safe value.

javascript
import mysql from 'mysql2/promise';

async function getUser(username) {
  const connection = await mysql.createConnection({host: 'localhost', user: 'root', database: 'test'});
  const [rows] = await connection.execute('SELECT * FROM users WHERE username = ?', [username]);
  await connection.end();
  return rows;
}

// Usage example:
getUser("' OR '1'='1").then(console.log);
Output
[ /* only users matching the exact username are returned, no injection possible */ ]
🛡️

Prevention

Always use parameterized queries or prepared statements with your database library. Avoid building SQL strings by concatenation or template literals with user input. Use libraries like mysql2, pg, or sequelize that support safe query methods. Validate and sanitize inputs as an extra layer. Enable strict linting rules to catch unsafe query patterns.

⚠️

Related Errors

Other common database errors include:

  • Syntax errors: caused by malformed SQL strings.
  • Connection errors: when database credentials or network fail.
  • Data type mismatches: passing wrong types in queries.

Using parameterized queries also helps avoid syntax and type errors.

Key Takeaways

Always use parameterized queries or prepared statements to separate code from data.
Never build SQL queries by concatenating user input directly into strings.
Use trusted database libraries that support safe query methods.
Validate and sanitize user inputs as an additional safety measure.
Enable linting rules to detect unsafe SQL query patterns early.