Web security for frontend

5 concepts · 10 practice questions

Cross-site scripting (XSS)

XSS is attacker-controlled input running as script in your page, where it can do anything the user can. It comes from data stored on the server, reflected from the URL, or written into the DOM by client code. Frameworks escape text by default, so the risk sits in the escape hatches: innerHTML, dangerouslySetInnerHTML, v-html, and URLs from users placed in href or src, where javascript: runs code. Sanitize HTML you must render with a maintained sanitizer and allow only http and https URLs.

// Safe: rendered as text
<p>{comment.body}</p>

// Needs sanitizing
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(comment.html) }} />

function safeUrl(raw: string) {
  const url = new URL(raw, location.origin);
  return url.protocol === "https:" || url.protocol === "http:" ? url.href : "#";
}

Also covered

Content Security Policy and framing
CSRF and SameSite cookies
CORS
Storing auth tokens

Sign in to read the rest and take the 10-question test.

Sign in to continue