Security
SQL Injection in Node.js: Example and Fix
SQL injection in Node.js occurs when user input is directly embedded into SQL query strings. Despite being one of the oldest vulnerabilities, it remains in the OWASP Top 10.
❌ Vulnerable Node.js Query
app.get('/user', async (req, res) => {
const { username } = req.query;
const result = await db.query(
`SELECT * FROM users WHERE username = '${username}'`
);
res.json(result.rows);
});✅ Fixed with Parameterized Query
app.get('/user', async (req, res) => {
const { username } = req.query;
const result = await db.query(
'SELECT * FROM users WHERE username = $1',
[username]
);
res.json(result.rows);
});💡
Pro tip: Use ORMs like Prisma or TypeORM which build parameterized queries automatically, making injection impossible through normal usage.
Paste this code into LearnCodeGuide
Detect JavaScript vulnerabilities and bugs automatically with AI-powered analysis.
Analyze JavaScript Code →