Day 86 Security Best Practices
Web security ko ignore karna dangerous hai. XSS, CSRF, injection attacks — yeh sab real threats hain. Har developer ko basic security samajhni chahiye taake users ka data safe rahe.
Common Vulnerabilities
XSS, CSRF, injection attacks aur prevention.
// npm install helmet express-rate-limit
const helmet = require("helmet");
const rateLimit = require("express-rate-limit");
const xss = require("xss");
// Helmet — security headers
app.use(helmet());
// Sets: X-Content-Type-Options, X-Frame-Options,
// Content-Security-Policy, etc.
// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100,
message: "Too many requests — please try later",
standardHeaders: true,
legacyHeaders: false
});
app.use(limiter);
// XSS prevention — sanitize user input
function sanitize(input) {
return xss(input); // script tags remove ho jaenge
}
// ❌ SQL/NoSQL Injection example
// User.find({ email: userInput }) — dangerous!
// If userInput = { $gt: "" } — all users exposed!
// ✅ Safe — validate input type
function getUser(email) {
if (typeof email !== "string") throw new Error("Invalid input");
return User.findOne({ email: email.toLowerCase().trim() });
}
// CSRF — use csrf middleware or SameSite cookies
// Environment variables — secrets kabhi hardcode mat karo!
// ❌ const SECRET = "mysecretkey123";
// ✅ const SECRET = process.env.JWT_SECRET;
🎯 Practice Challenge
API pe Helmet, rate limiting, input sanitization, aur environment variables lagao. OWASP Top 10 padho aur checklist banao.