How to Prevent SQL Injection in Node.js: Safe Database Queries
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.
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.
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.
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);
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.