Overview
Injection vulnerabilities in Node.js with Express occur when user-supplied input is concatenated into commands or queries. In real-world apps, attackers can modify SQL statements or OS commands, potentially exfiltrating data or altering behavior. No CVEs are referenced in this general guide.
In Express apps, common injection patterns arise when building SQL via string interpolation or when using shell commands with unsanitized input. NoSQL injections can also occur if query objects are constructed directly from client data. The impact can include data leakage, data corruption, or remote code execution in misconfigured environments.
Remediation involves using parameterized queries or ORM tools, validating and sanitizing input, and limiting database privileges. Adopt proper error handling and security testing to catch injection points before release.
Code Fix Example
Node.js (Express) API Security Remediation
const express = require('express');
const mysql = require('mysql2/promise');
const app = express();
async function initPool(){
return mysql.createPool({ host: 'localhost', user: 'app', password: 'secret', database: 'shop' });
}
let pool;
(async () => { pool = await initPool(); })();
// Vulnerable version
app.get('/search/vulnerable', async (req, res) => {
const q = req.query.q || '';
const sql = `SELECT id, name FROM products WHERE name LIKE '%${q}%'`;
try {
const [rows] = await pool.execute(sql);
res.json(rows);
} catch (err) {
res.status(500).json({ error: 'Internal error' });
}
});
// Fixed version
app.get('/search/fix', async (req, res) => {
const q = req.query.q || '';
const sql = 'SELECT id, name FROM products WHERE name LIKE ?';
try {
const [rows] = await pool.execute(sql, [`%${q}%`]);
res.json(rows);
} catch (err) {
res.status(500).json({ error: 'Internal error' });
}
});
app.listen(3000, () => console.log('Server listening on port 3000'));