Securing a Node.js app means protecting it from common attacks, data leaks, and misuse while keeping performance stable.
1. Use HTTPS (SSL/TLS)
Always serve your app over HTTPS.
- Encrypts data between client and server
- Prevents man-in-the-middle attacks
2. Secure Authentication (JWT / Sessions)
- Use strong authentication (JWT or sessions)
- Keep tokens short-lived
- Store tokens securely (prefer httpOnly cookies)
3. Hash Passwords
Never store plain passwords.
const bcrypt = require("bcrypt");
const hashedPassword = await bcrypt.hash(password, 10);
👉 Protects user data even if DB is compromised
4. Use Security Middleware
In apps, middleware helps secure headers and requests.
const helmet = require("helmet");
app.use(helmet());
👉 Protects against common vulnerabilities
5. Prevent SQL Injection / NoSQL Injection
- Always validate and sanitize inputs
- Use parameterized queries
// Bad
db.query(`SELECT * FROM users WHERE email = '${email}'`);
// Good
db.query("SELECT * FROM users WHERE email = ?", [email]);
6. Enable CORS Properly
const cors = require("cors");
app.use(cors({
origin: "https://yourdomain.com"
}));
👉 Prevents unauthorized domains from accessing your API
7. Rate Limiting
Protect against brute-force and DDoS attacks.
const rateLimit = require("express-rate-limit");
app.use(rateLimit({
windowMs: 15 * 60 * 1000,
max: 100
}));
8. Validate User Input
Use libraries like:
- Joi
- express-validator
👉 Prevents invalid or malicious data
9. Avoid Blocking Code
- Don’t use sync functions (
fs.readFileSync) - Prevent event loop blocking
👉 Helps avoid DoS attacks
10. Keep Dependencies Updated
- Regularly update npm packages
- Fix known vulnerabilities
npm audit fix
11. Hide Sensitive Information
- Don’t expose stack traces in production
- Use environment variables for secrets
process.env.JWT_SECRET
12. Logging & Monitoring
- Log suspicious activity
- Monitor errors and traffic
👉 Helps detect attacks early
13. Use Proper Authorization
- Role-based access control (RBAC)
- Protect admin routes
app.get("/admin", verifyToken, isAdmin);
Real-world Example
Login system security:
- Password hashed with bcrypt
- JWT issued with expiry
- Middleware verifies token
- Rate limiting prevents brute-force
- Helmet secures headers
Key Takeaway
Securing a Node.js app is about layered protection—authentication, validation, encryption, and monitoring. No single solution is enough; combining these practices ensures your application stays safe, reliable, and production-ready.