Fundamentals
Core principles every developer needs to build safer web applications
Overview
Web security is about protecting your application, its data, and its users from attackers. The two guiding ideas are "never trust user input" and "defense in depth" — assume any input can be malicious and layer multiple protections so one failure does not compromise everything. Most real-world breaches come from a handful of well-understood mistakes, so learning the fundamentals prevents the majority of problems.
Syntax / Usage
Validate and sanitize input on the server, and always encode output for the context it lands in. Client-side checks improve UX but can be bypassed, so the server is the real gatekeeper.
// Never trust the client — re-validate on the server
function createUser(req, res) {
const { email, age } = req.body;
if (typeof email !== "string" || !email.includes("@")) {
return res.status(400).json({ error: "Invalid email" });
}
const parsedAge = Number(age);
if (!Number.isInteger(parsedAge) || parsedAge < 0 || parsedAge > 150) {
return res.status(400).json({ error: "Invalid age" });
}
// Proceed only with validated, well-typed values
db.users.insert({ email, age: parsedAge });
res.status(201).json({ ok: true });
}
Examples
Fail closed — deny access by default and only allow what you explicitly permit:
function canAccess(user, resource) {
if (!user) return false; // default deny
return resource.ownerId === user.id || user.isAdmin;
}
Use the principle of least privilege for credentials and tokens:
// A read-only report job should not use an admin database account
const reportDb = connect({ user: "reporter", permissions: ["SELECT"] });
Common Mistakes
- Trusting client-side validation and skipping server-side checks
- Exposing detailed error messages or stack traces to users
- Running services or database accounts with more privileges than needed
- Storing secrets (API keys, passwords) in source code or committing
.envfiles - Assuming "we're too small to be targeted" — automated scanners hit everyone
See Also
web-security-owasp-top-ten web-security-authentication web-security-https-tls