Security
-
Security in Node.js includes hashing passwords with bcrypt and protecting APIs from unauthorized access.
Password Hashing with bcrypt
Password hashing is the process of converting a plain-text password into a secure, irreversible string. bcrypt is a popular Node.js library used for hashing passwords before saving them to a database.
Why Hash Passwords?
Protect user credentials
Prevent password theft even if database is compromised
Follow industry best practices for authentication
Install bcrypt
npm install bcrypt
- Example – Hashing a Password
Password Hashing with bcrypt
Uses bcrypt to securely hash plain-text passwords before storing them, protecting user credentials even if the database is compromised.
const bcrypt = require("bcrypt");
const plainPassword = "mySecretPassword";
// Generate salt and hash password
bcrypt.hash(plainPassword, 10, (err, hash) => {
if (err) throw err;
console.log("Hashed Password:", hash);
});
Explanation:
10 → number of salt rounds (complexity)
hash is stored in database instead of plain password
Example – Verifying Password
Password Verification with bcrypt
Uses bcrypt.compare() to verify a user’s entered password against the hashed password stored in the database.
const storedHash = "$2b$10$abc..."; // From DB
bcrypt.compare("mySecretPassword", storedHash, (err, result) => {
if (result) {
console.log("Password is correct");
} else {
console.log("Invalid password");
}
});
Securing APIs
API security ensures that only authorized users can access backend routes, preventing data leaks or unauthorized modifications.
Key Practices for Securing APIs:
Use JWT or session-based authentication
Validate all incoming requests
Hash and salt passwords
Limit rate of requests (rate-limiting)
Use HTTPS for encrypted communication
Sanitize user input to prevent injections
Example – Protecting Routes with JWT
Securing APIs with JWT
Protects backend routes using JWT authentication, ensuring only authorized users can access APIs and sensitive data.
const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();
const SECRET_KEY = "jwtSecret";
function authenticateToken(req, res, next) {
const token = req.headers["authorization"];
if (!token) return res.status(403).send("Token required");
jwt.verify(token, SECRET_KEY, (err, user) => {
if (err) return res.status(401).send("Invalid token");
req.user = user;
next();
});
}
app.get("/dashboard", authenticateToken, (req, res) => {
res.send(`Welcome ${req.user.email}`);
});
🔹 Additional Security Tips
Rate Limiting
const rateLimit = require("express-rate-limit");
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 mins
max: 100, // max requests
message: "Too many requests, try later"
});
app.use("/api/", limiter);
Data Sanitization – prevent SQL/NoSQL injections
Helmet Middleware – adds security headers
const helmet = require("helmet");
app.use(helmet());