Security isn't optional. Here are essential practices to protect your web applications from common vulnerabilities.
Sanitize all user input:
// ❌ Dangerous
element.innerHTML = userInput
// ✅ Safe
element.textContent = userInput
// For React
function SafeComponent({ userContent }) {
return <div>{userContent}</div> // Auto-escaped
}
Use Content Security Policy:
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self' 'unsafe-inline'">
Always use parameterized queries:
// ❌ Vulnerable
const query = `SELECT * FROM users WHERE id = ${userId}`
// ✅ Safe (with parameterized query)
const query = 'SELECT * FROM users WHERE id = ?'
db.query(query, [userId])
// With an ORM
const user = await User.findOne({ where: { id: userId } })
Implement secure authentication:
// Password hashing with bcrypt
const bcrypt = require('bcrypt')
const saltRounds = 10
// Hashing
const hash = await bcrypt.hash(password, saltRounds)
// Verification
const match = await bcrypt.compare(password, hash)
Force HTTPS in production:
// Express middleware
app.use((req, res, next) => {
if (req.header('x-forwarded-proto') !== 'https') {
res.redirect(`https://${req.header('host')}${req.url}`)
} else {
next()
}
})
Implement CSRF tokens:
// Generate token
const csrfToken = crypto.randomBytes(32).toString('hex')
// In form
<input type="hidden" name="csrf" value={csrfToken} />
// Validate on server
if (req.body.csrf !== req.session.csrfToken) {
throw new Error('Invalid CSRF token')
}
Set security headers:
// Using helmet.js
const helmet = require('helmet')
app.use(helmet({
contentSecurityPolicy: true,
crossOriginEmbedderPolicy: true,
crossOriginOpenerPolicy: true,
crossOriginResourcePolicy: true,
originAgentCluster: true,
referrerPolicy: { policy: "no-referrer" }
}))
Validate all inputs:
const validator = require('validator')
// Email validation
if (!validator.isEmail(email)) {
throw new Error('Invalid email')
}
// Sanitize input
const cleanInput = validator.escape(userInput)
Prevent brute force attacks:
const rateLimit = require('express-rate-limit')
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests
})
app.use('/api/', limiter)
Security is a continuous process, not a one-time task. Regularly update dependencies, conduct security audits, and stay informed about new vulnerabilities. Your users trust you with their data—make security a priority.