Web Security Essentials
The most common attacks and their fixes
| Attack | What happens | Defence |
|---|---|---|
| XSS (cross-site scripting) | an attacker's script runs in your page and steals data | use textContent, not innerHTML, for user content; frameworks escape by default; a Content-Security-Policy header |
| SQL injection | user input changes your SQL query | parameterised queries or an ORM, never string concatenation |
| CSRF | another site makes the user's browser send a request to your site | SameSite cookies, CSRF tokens |
| Broken access control | users reach data that isn't theirs | check permissions on the server; database RLS |
| Leaked secrets | API keys in front-end code or Git | environment variables, server-side calls, key rotation |
| Clickjacking | your site is hidden inside another page's frame | X-Frame-Options / CSP frame-ancestors |
Habits that prevent most problems
- HTTPS everywhere.
- Validate input on the server, every time.
- Use security headers (
helmetin Express sets many of them). - Keep dependencies updated (
npm audit, Dependabot). - Give each key and user only the permissions they need (least privilege).
- Don't show stack traces or database errors to users.
- Rate-limit logins and expensive endpoints.
💡 The OWASP Top 10 is the standard list of web security risks. Read it once; it's worth it.
Example
<!-- XSS demo: why textContent matters -->
<input id="comment" value='<img src=x onerror="alert('hacked')">' size="50" />
<button id="unsafe">Show with innerHTML ❌</button>
<button id="safe">Show with textContent ✅</button>
<div id="out" style="margin-top:12px; padding:8px; border:1px solid #ddd"></div>
<script>
const input = document.querySelector("#comment");
const out = document.querySelector("#out");
document.querySelector("#unsafe").onclick = () => {
out.innerHTML = input.value; // runs the attacker's code!
};
document.querySelector("#safe").onclick = () => {
out.textContent = input.value; // shown as harmless text
};
</script>
<!-- ▶️ Try it in the code editor's HTML mode -->