How do you prevent SQL injection in an Express.js application?
Answer
SQL injection occurs when user input is concatenated directly into a SQL query, allowing attackers to manipulate the query. Prevention with an ORM like Sequelize or TypeORM: use their query methods and model API — they parameterize queries automatically. With raw SQL, use parameterized queries: db.query('SELECT * FROM users WHERE id = ?', [req.params.id]) — never string concatenation. For MongoDB, use express-mongo-sanitize to strip $ and . characters from user input, preventing NoSQL injection. Additional defenses: validate input types strictly (if id should be an integer, reject non-integers before querying), use least-privilege database accounts, and never expose raw error messages that reveal schema information.
Previous
What is the role of reverse proxies in Express.js production deployments?
Next
What is streaming responses in Express.js and when should you use it?
More Express.js Questions
View all →- Advanced How do you implement WebSocket support alongside Express.js?
- Advanced What are security best practices for Express.js APIs?
- Advanced How does clustering work in Node.js/Express for better performance?
- Advanced What is the difference between Express 4.x and Express 5.x?
- Advanced How do you implement a graceful shutdown in Express.js?