QA
Intermediate LevelExpress JS

How do you defend Express endpoints against NoSQL injection attacks in MongoDB?

❓ Interview Prompt: Explain NoSQL injection ($gt, $ne operator injection in query params), express-mongo-sanitize, and input sanitization.

If an application passes raw 'req.body' directly into a MongoDB query ('db.collection.find(req.body)'), attackers can send JSON objects containing query operators:

'{ "username": "admin", "password": { "$ne": null } }', bypassing authentication completely!

Defense:

Use 'express-mongo-sanitize' middleware to automatically strip '$' and '.' characters from incoming 'req.body', 'req.query', and 'req.params'.

Code Implementation Example

javascript
import express from 'express';
import mongoSanitize from 'express-mongo-sanitize';

const app = express();
app.use(express.json());

// Sanitize incoming user input to block NoSQL operator injection ($ne, $gt)!
app.use(mongoSanitize());

app.post('/api/login', (req, res) => {
  // $ operators are stripped safely before reaching database queries!
  res.json({ status: 'Sanitized' });
});
💡Blocking MongoDB NoSQL operator injection using express-mongo-sanitize.
🎯 Interview Key Takeaway

Use express-mongo-sanitize to strip $ and . characters from user inputs, preventing NoSQL operator injection.

#NoSQL Injection#Security#MongoDB#Intermediate
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?