Essential security best practices for every Node.js developerādonāt ship your app without these!
šØ The Hack That Almost Happenedā¦
Picture this: My Node.js app was live. Users were happy. I was sipping chai.
Then BAM š„ ā someone tried a NoSQL injection on one of my routes.
One missing line of code couldāve exposed every userās data.
Letās talk about that one line, and several others, that every developer must know to avoid common attacks.
ā The One Line That Saved My App
app.use(helmet());
This lineājust one lineāinstantly adds 10+ security headers to your app. It defends against:
- Cross-site scripting (XSS)
- Clickjacking
- MIME-sniffing attacks
- Cache poisoning
- And more…
š§ Whatās helmet()
and Why Itās a Lifesaver?
Helmet is a middleware for Express that sets HTTP headers designed to secure your app. Itās like a shield between your server and the internet.
npm install helmet
const helmet = require('helmet');
app.use(helmet());
And boom! You just leveled up your app’s security. šÆ
š Other Node.js Security Essentials
1. š Sanitize User Input to Prevent Injection Attacks
Donāt trust any inputāsanitize it before using it.
ā Vulnerable code:
const user = await db.find({ username: req.body.username });
ā Safer code with express-validator:
const { body, validationResult } = require('express-validator');
app.post('/login', [
body('username').isAlphanumeric().trim().escape(),
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });
const user = await db.find({ username: req.body.username });
});
2. š Donāt Hardcode SecretsāUse Environment Variables
Never put your API keys, database passwords, or JWT secrets in your codebase.
ā Wrong:
const JWT_SECRET = "mySuperSecret123";
ā Right:
const JWT_SECRET = process.env.JWT_SECRET;
Use a .env
file and the dotenv
package:
npm install dotenv
require('dotenv').config();
3. š§Ŗ Use Rate Limiting to Prevent Brute Force Attacks
Donāt let someone hit your login route 10,000 times a second.
npm install express-rate-limit
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
});
app.use(limiter);
4. š« Disable X-Powered-By Header
This tells hackers youāre using Express. Hide it.
app.disable('x-powered-by');
5. š§± Use CORS the Right Way
Control who can access your API.
npm install cors
const cors = require('cors');
const corsOptions = {
origin: ['https://yourfrontend.com'], // whitelist your domains
optionsSuccessStatus: 200
};
app.use(cors(corsOptions));
6. š Secure Your Cookies
If you’re using sessions or cookies, mark them as secure and HTTP-only.
res.cookie('token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict'
});
š§¾ Recap: Security Checklist
Feature | Code/Package |
---|---|
HTTP headers | app.use(helmet()) |
Input sanitization | express-validator |
Rate limiting | express-rate-limit |
Hide Express info | app.disable('x-powered-by') |
Use CORS | cors package |
Secure cookies | httpOnly , secure , sameSite |
Env variables | dotenv + .env |