Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SEC
Authentication & Security
0/10 completed
Beginner
Authentication vs authorizationHashing passwords
Intermediate
Sessions and cookiesJSON Web TokensOAuth 2.0 and OpenID ConnectMulti-factor authentication and passkeys
Advanced
The OWASP Top 10XSS, CSRF and CORSSecrets management and encryption
Pro
Security in practice
Tracks / Authentication & Security / Advanced

XSS, CSRF and CORS

Browsers run code from many websites side by side, and they automatically attach your cookies to requests. Three topics come from that: XSS (an attacker's script running inside your site), CSRF (another site making requests as you), and CORS (the rules for when one site may read another site's responses).

Cross-site scripting (XSS)

XSS happens when user-controlled text ends up in a page as HTML or JavaScript instead of as text. Then the attacker's script runs with the full power of your site: it can read the page, make requests as the user, steal tokens from localStorage, or rewrite the login form.

Type How the script gets in
Stored Saved in the database (a comment, a username) and shown to every visitor
Reflected Comes from the URL and is echoed into the response (/search?q=<script>…)
DOM-based Client-side JavaScript writes untrusted data into the page (element.innerHTML = location.hash)
Node.js · editable

In v1 the browser would create an <img> whose onerror handler sends the visitor's cookies to the attacker. In v2 the user sees the text itself, harmlessly.

Defences

  1. Let your framework escape output. React, Vue, Angular, Django templates, Jinja, Thymeleaf and EJS's <%= %> escape by default. The danger is the escape hatches: dangerouslySetInnerHTML, v-html, |safe, <%- %>, innerHTML.
  2. Escape for the right context. HTML text, HTML attributes, URLs, JavaScript strings and CSS each need different encoding. Never put untrusted data inside <script> blocks or event-handler attributes.
  3. Sanitise rich text (when users may submit HTML, such as in a blog editor) with a proven library such as DOMPurify, which keeps safe tags and removes scripts.
  4. Validate URLs: a link to javascript:alert(1) is XSS. Allow only http: and https:.
  5. Content Security Policy (CSP): a response header telling the browser which scripts may run. Even if an attacker injects a <script>, the browser refuses it:
http
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
  1. HttpOnly cookies so an XSS can't read session cookies (it can still act as the user, which is why escaping comes first).

helmet() sets a strict CSP and other protective headers in Express:

Node.js · editable

Cross-site request forgery (CSRF)

CSRF abuses the fact that browsers attach cookies to requests wherever they come from. While you're logged in to your bank, an evil page can submit a hidden form to the bank; your session cookie rides along.

CSRF only matters when authentication is automatic: cookies or HTTP Basic auth. APIs that require an Authorization: Bearer header are immune, because another site can't make your browser add that header.

Defences

  1. SameSite cookies (Lax is the browser default for cookies without the attribute in Chrome, but set it explicitly). Cross-site POSTs then arrive without the session cookie.
  2. CSRF tokens: a random token stored in the session and included in every form; the server rejects state-changing requests without the matching token. Django, Rails, Laravel and Spring Security do this automatically.
  3. Check where requests come from: modern browsers send Sec-Fetch-Site and Origin headers.
Node.js · editable

CORS

The browser's same-origin policy stops JavaScript on one origin (scheme + host + port, like https://shop.example) from reading responses from another origin. That's what keeps evil.example from reading your webmail with your cookies.

But your own frontend at https://shop.example legitimately needs to call your API at https://api.shop.example. CORS (Cross-Origin Resource Sharing) lets the API say which origins are allowed, with response headers:

http
Access-Control-Allow-Origin: https://shop.example
Access-Control-Allow-Credentials: true

For "non-simple" requests (JSON bodies, custom headers, PUT/DELETE), the browser first sends a preflight OPTIONS request asking for permission:

Node.js · editable

For evil.example there's no Access-Control-Allow-Origin header, so the browser blocks the real request.

Common CORS mistakes

  • Access-Control-Allow-Origin: * with credentials: browsers forbid it, so people "fix" it by reflecting any Origin back, which lets every website make authenticated requests and read the answers. Use an allow-list.
  • Matching origins with sloppy patterns: origin.endsWith('shop.example') also allows evilshop.example.
  • Thinking CORS protects the server. It's enforced by browsers; curl and attackers' servers ignore it. CORS decides who may read responses in a browser, not who may call your API. Authentication and authorization do that.

Practice

  1. Add a third comment containing "><script>alert(1)</script> and confirm v2 escapes it.
  2. Configure helmet's CSP to also allow images from https://images.shop.example.
  3. Explain why an API that only accepts Authorization: Bearer tokens doesn't need CSRF tokens.
✎ Check your understanding

1.What is the most important defence against XSS?

2.Why does CSRF work at all?

3.What does CORS control?

← The OWASP Top 10