Skip to content

Web Security Basics

Learn web security fundamentals — XSS, CSRF, HTTPS, and Content Security Policy.

What you'll learn

  • The OWASP Top 10 and the most common web vulnerabilities
  • XSS (Cross-Site Scripting): how it works and how to prevent it
  • CSRF (Cross-Site Request Forgery) and SameSite cookie defense
  • How HTTPS, CSP, and security headers protect your application

Concept

Web Security Basics

Web security is about protecting your users and your application from attackers. The web is a hostile environment — any public site is probed by automated bots within minutes of going live. You do not need to be a security expert to build safe web apps, but you must understand the most common attacks and their defenses. The OWASP Top 10 lists the ten most critical web vulnerabilities; we cover the ones every developer must know.

XSS (Cross-Site Scripting)

XSS happens when an attacker injects malicious JavaScript into your page, and the browser executes it. This can steal cookies, redirect users, or deface the page. The primary defense is never insert untrusted data as HTML. Use textContent instead of innerHTML. If you must render HTML from user input, sanitize it with a library like DOMPurify first. XSS is the most common web vulnerability — and the most preventable.

CSRF (Cross-Site Request Forgery)

CSRF tricks the user's browser into making a request to your site while the user is logged in, performing an action they did not intend (like transferring money). The browser automatically sends the user's session cookie, so the request looks legitimate. Defenses: use SameSite=Strict cookies (the modern, simplest defense), require a CSRF token for state-changing requests, or check the Origin or Referer header. SameSite cookies have made CSRF much less common, but it is still a risk on older browsers.

HTTPS and TLS

HTTPS encrypts traffic between the browser and server. Without it, anyone on the network can read passwords, cookies, and personal data. HTTPS is now the default — browsers flag HTTP sites as "Not Secure," and many features (service workers, geolocation) require it. Use Let's Encrypt for free certificates, redirect all HTTP to HTTPS, and set the Strict-Transport-Security header to enforce HTTPS in the future. There is no reason to use plain HTTP in production.

Content Security Policy (CSP)

CSP is an HTTP header that restricts what the browser is allowed to load and execute — scripts, styles, images, connections. A strong CSP is the most effective XSS mitigation because even if an attacker injects a <script> tag, the browser will not execute it if the CSP does not allow inline scripts. A basic CSP:

Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'

This says: only load resources from the same origin. No inline scripts, no third-party CDNs (unless you add them to the allowlist). CSP is powerful but requires careful configuration — start with report-only mode to find violations before enforcing.

Security Headers

Beyond CSP, several headers harden your app: X-Content-Type-Options: nosniff (prevents MIME sniffing), X-Frame-Options: DENY (prevents clickjacking), Referrer-Policy: strict-origin-when-cross-origin (limits referrer leakage). Tools like securityheaders.com audit your headers and tell you what is missing.

Example

              // Defense 1: Prevent XSS — never use innerHTML with user data
function renderComment(userInput) {
  const div = document.createElement("div");
  // SAFE: textContent treats input as plain text
  div.textContent = userInput;
  // DANGEROUS: div.innerHTML = userInput; // NEVER do this!
  return div;
}

// Defense 2: Sanitize if you must render HTML
// import DOMPurify from 'dompurify';
function renderRichText(userInput) {
  const div = document.createElement("div");
  div.innerHTML = DOMPurify.sanitize(userInput);
  return div;
}

// Defense 3: CSRF token for state-changing requests
async function transferMoney(amount, toAccount) {
  const csrfToken = document.querySelector("meta[name=csrf-token]").content;
  const response = await fetch("/api/transfer", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-CSRF-Token": csrfToken  // server verifies this
    },
    credentials: "include",
    body: JSON.stringify({ amount, toAccount })
  });
  return response.json();
}
            

renderComment uses textContent to safely display user input as text. renderRichText sanitizes with DOMPurify before setting innerHTML — necessary for rich text but never raw. transferMoney includes a CSRF token header that the server verifies, preventing forged requests. Together these defend against XSS and CSRF.

Try it

  • HTML Entity Encoder

    Encoding HTML entities is a key XSS defense — encode user content before display.

  • Hash Generator

    CSRF tokens are often random hashes — generate one to see how they work.

  • JWT Decoder

    Understand JWT structure — a secure alternative to storing auth state in cookies.

Common mistakes

The mistake

Using innerHTML with user input, creating an XSS vulnerability.

The fix

Use textContent for all user-provided text — it renders as plain text, not HTML. If you need rich text, sanitize with DOMPurify or a similar library before setting innerHTML. Never concatenate user input into HTML strings.

The mistake

Serving a site over HTTP in production or not redirecting HTTP to HTTPS.

The fix

Use HTTPS everywhere in production. Get free certificates from Let's Encrypt, redirect all HTTP traffic to HTTPS, and set the Strict-Transport-Security header so the browser always uses HTTPS for your domain.

Related Guides

Practice Web Security Basics

7 exercises

Practice Web Security Basics

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors