appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Security for JavaScript developers

Lesson 4 of 412 minAdvanced

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 eval or new Function with user input.

Cookies, tokens and CSRF

  • Keep session identifiers in cookies marked HttpOnly; Secure; SameSite=Lax, so scripts cannot read them.
  • Tokens in localStorage can 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 the Origin header.

Dependencies and secrets

  • Run npm audit and 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.

1. Why is HttpOnly useful on a session cookie?
2. Is an API key placed in front-end JavaScript secret?
3. Which is the safest way to show a username in the page?

Key terms