Overview
Injection vulnerabilities in Node.js Express apps translate into real-world risks: attackers can alter queries to steal or delete data, bypass authentication, or perform unauthorized actions. SQL injection can exfiltrate customer data, while OS command injection can lead to arbitrary code execution on the server, potentially compromising the running process or the entire host. No CVEs are provided for this general guide, but these patterns have been observed in many deployments.
These issues arise when user input is interpolated into SQL strings, NoSQL queries, shell commands, or template data without proper validation or escaping. In Express, common patterns include building dynamic queries with string concatenation, or invoking eval or Function on request data, and passing unchecked input to system commands. The risk scales with database privileges and service exposure.
Mitigations emphasize parameterized queries and safe query builders, strict input validation, and least-privilege database access. Use ORM/ODM protections, enable input whitelisting, avoid dynamic code execution, and sanitize data before rendering templates. Add secure defaults, proper error handling, and automated tests to detect injection attempts early.
Code Fix Example
Node.js (Express) API Security Remediation
Vulnerable:
const express = require('express');
const mysql = require('mysql');
const app = express();
const pool = mysql.createPool({ host: 'localhost', user: 'app', password: 'secret', database: 'mydb' });
app.get('/user', (req, res) => {
const username = req.query.username;
// Vulnerable: string interpolation leading to SQL injection
const query = `SELECT * FROM users WHERE username = '${username}'`;
pool.query(query, (err, results) => {
if (err) return res.status(500).send('Server error');
res.json(results);
});
});
Fixed:
app.get('/user-fixed', (req, res) => {
const username = req.query.username;
// Fixed: parameterized query to prevent injection
const query = 'SELECT * FROM users WHERE username = ?';
pool.query(query, [username], (err, results) => {
if (err) return res.status(500).send('Server error');
res.json(results);
});
});