Web Development · Module 12 · Lesson 11 min read

Web Security Essentials

The most common attacks and their fixes

AttackWhat happensDefence
XSS (cross-site scripting)an attacker's script runs in your page and steals datause textContent, not innerHTML, for user content; frameworks escape by default; a Content-Security-Policy header
SQL injectionuser input changes your SQL queryparameterised queries or an ORM, never string concatenation
CSRFanother site makes the user's browser send a request to your siteSameSite cookies, CSRF tokens
Broken access controlusers reach data that isn't theirscheck permissions on the server; database RLS
Leaked secretsAPI keys in front-end code or Gitenvironment variables, server-side calls, key rotation
Clickjackingyour site is hidden inside another page's frameX-Frame-Options / CSP frame-ancestors

Habits that prevent most problems

  • HTTPS everywhere.
  • Validate input on the server, every time.
  • Use security headers (helmet in 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

HTML
<!-- XSS demo: why textContent matters -->
<input id="comment" value='<img src=x onerror="alert(&#39;hacked&#39;)">' 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 -->