Security for JavaScript developers
XSS, CSRF, dependencies and secrets: the habits that keep an app safe.
XSS (cross-site scripting)
XSS happens when an attacker's text is treated as code in your page. It can steal sessions and act as the user.
// Dangerous
el.innerHTML = `<p>Hello ${name}</p>`;
// Safe
el.textContent = `Hello ${name}`;- Prefer
textContent, frameworks that escape by default, and a sanitiser (for example DOMPurify) when you must allow some HTML. - Add a Content-Security-Policy header to limit where scripts can load from.
- Never use
evalornew Functionwith user input.
Cookies, tokens and CSRF
- Keep session identifiers in cookies marked
HttpOnly; Secure; SameSite=Lax, so scripts cannot read them. - Tokens in
localStoragecan be stolen by any XSS. Avoid them for long-lived credentials. - CSRF makes the victim's browser send a request with their cookies. Defend with
SameSite, CSRF tokens and checking theOriginheader.
Dependencies and secrets
- Run
npm auditand keep dependencies updated. Use a lockfile and review new packages: install scripts run code on your machine. - Anything shipped to the browser is public. API keys in front-end code are not secret.
- Keep real secrets on the server, in environment variables, never in Git.
CarefulValidate on the server as well. Browser checks improve usability, but an attacker can send any request directly.
NoteUse rel="noopener noreferrer" on links with target="_blank" to avoid the opened page controlling yours.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.