Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 39 ยท Beyond Fetch

AJAX Security

Protect AJAX apps: stop XSS from API data, defend against CSRF with SameSite cookies, avoid CORS mistakes, store tokens wisely and keep secrets off the client.

AJAX moves work to the browser, and the browser is the one place you do not control. Every user can open DevTools, edit your JavaScript, replay requests with different data and read everything your page receives. Security for AJAX applications therefore rests on one rule: the client is untrusted, and so is everything that arrives from the network, including responses from your own API, because that API may hold data written by other users.

This lesson walks through the five problems that cause most real-world incidents: cross-site scripting from API data, cross-site request forgery, CORS misconfiguration, token storage and secrets in front-end code. Each section shows how the attack works, why AJAX code is exposed to it and the practical defense. Most examples are read-only, because you must never run attacks against systems you do not own, but the escaping and validation demos run live and use inert, harmless strings.

XSS: when API data becomes code

Cross-site scripting (XSS) happens when text from outside your code is treated as HTML or JavaScript. Imagine a comments API. A visitor posts the comment <img src=x onerror="stealCookies()">. The server stores it faithfully, as it should. If your page then builds the list with innerHTML, the browser parses that string as markup, the image fails to load and the onerror handler runs as your site, with access to the page, its data and the user's session. One bad comment now attacks every person who views it.

flowchart LR
  A["Attacker posts<br/>a malicious comment"] --> B["API stores it<br/>as plain text"]
  B --> C["Victim page fetches<br/>the comments"]
  C --> D{"How is it rendered?"}
  D -->|"innerHTML"| E["Browser parses markup,<br/>script runs as your site"]
  D -->|"textContent"| F["Shown as harmless text"]

The data is identical in both branches; only the rendering method decides whether it is an attack.

The defenses, from most to least important:

  1. Render text as text. Use element.textContent = value or document.createTextNode(). Both treat the value as characters only. Prefer them over innerHTML, insertAdjacentHTML, outerHTML and document.write for anything that is not entirely under your control. The rendering lesson uses this approach throughout.
  2. Escape when you must build strings. If you really assemble HTML (for example with a template literal), escape the five characters that matter in HTML text and attribute values: &, <, >, " and '.
  3. Sanitize rich content. If users may write formatting (a blog comment with bold text), the HTML must pass through a maintained sanitizer library with an allow list of tags and attributes. Writing your own with regular expressions fails, because HTML parsing has too many edge cases. The browser's built-in Sanitizer API is still being rolled out, so check support before relying on it.
  4. Use a Content Security Policy. A Content-Security-Policy response header that forbids inline scripts limits the damage if an injection slips through. It is a second line of defense, not a replacement for escaping.
  5. Frameworks help, but have escape hatches. React, Vue and Angular escape text by default; the danger returns when you use dangerouslySetInnerHTML, v-html or [innerHTML] with untrusted data.

This demo shows what the browser would see if untrusted text were treated as HTML. It parses the string into an inert document with DOMParser, which never runs scripts or event handlers, and lists the elements and attributes that would have been created, then compares the safe textContent approach with an escapeHtml function.

What innerHTML would create

URLs are a special case. A value like javascript:doEvil() in an href runs code when clicked, and escaping HTML characters does not help. Whenever a link target comes from data, check the scheme with new URL() and an allow list:

JS Checking a link before using it

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The protocol check works because new URL() normalizes odd casing and hidden whitespace the same way the browser does. Note that a protocol-relative URL such as //evil.example/login is valid and passes this check; if links must stay on your own site, also compare url.origin with your origin.

CSRF: requests made in your name

Cross-site request forgery (CSRF) abuses the way browsers attach cookies automatically. If you are signed in to bank.example and then visit evil.example, a form or script on the evil page can make your browser send a request to bank.example. The browser adds your session cookie, so the bank sees what looks like a legitimate request from you. The attacker never reads the response, but a state-changing request ("transfer money", "change email") does not need a readable response.

sequenceDiagram
  participant V as Victim browser
  participant E as evil.example
  participant B as bank.example
  V->>E: visits the page
  E-->>V: hidden form targeting bank.example
  V->>B: POST /transfer (cookies attached by the browser)
  B-->>V: performs the action as the victim

CSRF works only when the browser attaches the victim's cookies to a request that another site triggered.

Defenses for cookie-based sessions:

  • SameSite cookies. Set SameSite=Lax (the default in modern browsers when the attribute is missing) or SameSite=Strict on the session cookie. The browser then withholds the cookie from cross-site POST requests and most other cross-site requests. SameSite=None (needed for embedded or third-party use) must be paired with Secure and brings the risk back.
  • CSRF tokens. The server issues a random value per session, the page sends it in a header such as X-CSRF-Token with every state-changing request, and the server rejects requests without a matching token. An attacker's page cannot read your page's token, because browsers block cross-origin reads. Many frameworks, including Laravel, do this for you.
  • Never change data with GET. Links and images trigger GET requests with no ceremony. Use POST, PUT, PATCH and DELETE for changes, as discussed in sending data.
  • Check Origin and Fetch-Metadata headers on the server as an extra layer: a state-changing request whose Sec-Fetch-Site is cross-site is suspicious.

Also set the HttpOnly flag on session cookies so JavaScript cannot read them (this limits what an XSS attack can steal) and Secure so they travel only over HTTPS.

CORS: the browser rule people disable by accident

CORS (covered in headers, auth and CORS basics) is a protection for users: it stops a random website from reading responses from an API the user is logged in to. Developers who hit a CORS error often "fix" it in the quickest way, and the quick fixes are dangerous:

  • Reflecting the Origin header. Code that copies whatever Origin arrives into Access-Control-Allow-Origin combined with Access-Control-Allow-Credentials: true lets every website read your users' private data. Allow a fixed list of origins you know.
  • Access-Control-Allow-Origin: * on private APIs. A wildcard is fine for public, unauthenticated data (browsers refuse to combine it with credentials, which is a safety net). It is wrong for anything personal.
  • Allowing the null origin. Sandboxed iframes and some local files send Origin: null; allowing it opens the same hole.
  • Treating CORS as authentication. CORS only affects browsers. Anyone can call your API with curl, so the server must still verify identity and permissions on every request.

Where to keep tokens

When a single-page app calls an API with a token (a JWT or an opaque access token), you must put the token somewhere. There is no perfect answer, only trade-offs:

Storage Read by JavaScript? Sent automatically? Main risk
localStorage or sessionStorage Yes No (you add the header) Any XSS can steal it
Memory (a variable) Yes No Lost on reload; XSS can still use it while the page runs
HttpOnly; Secure; SameSite cookie No Yes CSRF, which you counter with SameSite and CSRF tokens

Many security teams prefer the HttpOnly cookie, because XSS cannot read it, and counter CSRF with the defenses above. Other designs keep a short-lived access token in memory and a refresh token in an HttpOnly cookie. Whatever you choose, keep access tokens short-lived, never put them in URLs (URLs end up in logs, history and Referer headers) and never log them.

Secrets do not belong in the client

Everything you ship to the browser is public: JavaScript bundles, environment variables compiled into them, comments, source maps. An API key in front-end code is a published API key. If a third-party service gives you a secret key (payment, email, a paid AI model), call it from your own server, and let your page call your server. Your server can add the secret, enforce limits per user and cache results.

Some keys are meant to be public, such as a map tile key or an analytics ID, but good providers let you restrict them to your domains and cap their usage. If a provider's documentation says "never expose this key", believe it. And if a secret was ever committed to a public repository or shipped in a bundle, treat it as leaked and rotate it.

Validate what comes back

Authorization decisions belong on the server. A client-side check such as if (user.isAdmin) showAdminButton() only hides a button; anyone can still call the admin endpoint directly. The server must check on every request.

On the client, treat API responses as untrusted input: check types and shapes before using them (see validating JSON data), limit the size of what you accept, and never use response data to build code. Do not pass API strings to eval(), new Function(), setTimeout("string") or innerHTML. Parse JSON with JSON.parse() (never eval), and when merging parsed objects into others, be careful with keys such as __proto__, which attackers use for prototype pollution: copy only the fields you expect.

A short checklist

  • Render API text with textContent; escape or sanitize anything that must become HTML.
  • Validate link schemes before putting data into href or src.
  • Session cookies: HttpOnly, Secure, SameSite=Lax or Strict, plus CSRF tokens for state changes.
  • Allow only specific CORS origins; never reflect the Origin header on private APIs.
  • Keep tokens short-lived and out of URLs; prefer HttpOnly cookies where it fits.
  • No secrets in front-end code; proxy third-party calls through your server.
  • Authorize on the server for every request, and validate everything that arrives from the network.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A comments API returns the text <img src=x onerror=run()>. Which rendering code is safe?

    textContent treats the value as characters only. The other three parse it as markup, so the onerror handler would run.
  2. 2. Which cookie setting reduces the risk of CSRF?

    SameSite makes the browser withhold the cookie from most cross-site requests. HttpOnly protects against reading the cookie with JavaScript, which is a different problem.
  3. 3. Why is copying the request's Origin header into Access-Control-Allow-Origin (with credentials allowed) dangerous?

    Reflecting every origin effectively turns CORS off for credentialed requests, so a malicious site can read users' private data.
  4. 4. Where should a secret API key for a paid third-party service live?

    Anything delivered to the browser is public. A server-side proxy can keep the key private and limit usage.
  5. 5. A javascript: URL arrives in user.website. Which check helps before using it as a link?

    HTML escaping does not stop a dangerous scheme. An allow list of protocols does.

Summary

  • Treat the client and all network data as untrusted; the server decides who may do what.
  • Prevent XSS by rendering text with textContent, escaping or sanitizing when HTML is unavoidable, validating link schemes and adding a Content Security Policy.
  • Defend against CSRF with SameSite cookies, CSRF tokens and by never changing data through GET.
  • Configure CORS with an explicit list of origins; it protects users in browsers but is not authentication.
  • Prefer HttpOnly cookies for session credentials; keep other tokens short-lived and out of URLs.
  • Never ship secrets to the browser; proxy through your server and validate incoming data.

Next: Debugging Network Requests shows how to find out what really went over the wire.