Skip to content

    Frontend System Design

    CSRF and Clickjacking Defenses

    Learn why other sites can trigger requests that carry your cookies, and how SameSite, tokens, Origin and Fetch Metadata checks and frame-ancestors stop them.

    By Published 12 min read

    • frontend-system-design
    • csrf
    • clickjacking
    • browser-security
    Share

    Standard lessonintermediateTypeScript labFrontend System Design

    Before this: Cross-Site Scripting (XSS) and Its Defenses, Cookies and Web Storage in Depth

    What you'll learn: By the end of this lesson you will be able to explain why a browser sends your session cookie on a request another site caused, compare the main CSRF defenses (SameSite cookies, synchronizer and double-submit tokens, Origin and Referer checks, Fetch Metadata), say which attacks each stops and which it misses, explain why CORS is not a CSRF defense, and decide who may frame your page with frame-ancestors and X-Frame-Options. A TypeScript lab runs ten requests against eleven defenses.

    A hotel key card opens your door for whoever holds it, and the lock does not ask who is holding it. Imagine a stranger who cannot steal your card but can steer your hand: "press that button". That is cross-site request forgery (CSRF): the browser holds your key card (your cookies), attaches it to every request to the site that issued it, and does not check which page asked. Clickjacking is a cousin: a transparent sheet over a form, so you think you press "play" while your finger lands on "confirm".

    The running example is a shop at https://shop.example with POST /transfer, which sends store credit to another account. Attackers run https://evil.example. Three illustrations run through the lesson: a minimal example (a hidden form on the attacker's page), a realistic example (the shop with layered defenses) and a failure example (a sibling subdomain that same-site rules still trust). It builds on Cross-Site Scripting (XSS) and Its Defenses and the Same-Origin Policy and CORS.

    The core idea

    1. CSRF exists because cookies are attached automatically. MDN: the attacker tricks the user or browser into making a request to the target site from a malicious site, the request includes the user's credentials, and the server acts as if the user intended it.
    2. Each defense answers one question: did the request come from my page (a token), where did it come from (Origin, Referer, Fetch Metadata), should the cookie be attached at all (SameSite)? None is complete alone, so layer them.
    3. Clickjacking is a framing problem. The request is real, so tokens and origin checks pass. Control who may frame the page.

    How a forged request works

    MDN says an attack is possible when a site changes state with HTTP requests, validates the user only by cookies, and uses only parameters an attacker can predict. The attacker's page holds a hidden form aimed at /transfer and submits it on load. The browser sends it and, because the cookie belongs to shop.example, attaches it.

    Figure 1. A forged request carries the real cookie

    The attacker's page makes the victim's browser send a request to the shop, and the browser attaches the shop's session cookieAttacker's page to Victim's browser (hidden form); Cookie jar to Victim's browser (cookie added); Victim's browser to Shop server (POST /transfer)Attacker's page: evil.exampleAttacker'spageevil.exampleVictim's browser: has the cookieVictim'sbrowserhas the cookieCookie jar: session cookieCookie jarsession cookieShop server: shop.exampleShop servershop.examplehidden formcookie addedPOST /transfer

    How to read this: the attacker never sees the cookie or a response. The browser sends, and the cookie arrives because it matches the destination.

    Figure 2. The same request in time order

    sequenceDiagram accTitle: A cross-site forged request accDescr: The victim is signed in to the shop and opens the attacker's page. The page submits a hidden form to the shop. The browser adds the shop's cookie. The server carries out the transfer unless a defense rejects it. participant V as Victim's browser participant A as evil.example participant S as shop.example Note over V,S: signed in, session cookie stored V->>A: opens a page A-->>V: page with a hidden form V->>S: POST /transfer + session cookie alt no defense S-->>V: transfer carried out else a defense rejects it S-->>V: rejected, nothing happens end

    How to read this: the whole attack is the middle arrow. Every defense below removes the cookie from it or fails a check at the server.

    Two rules come first. Never change state on a safe method: MDN's checklist and OWASP both say so, because a GET needs no form (an image is enough) and most defenses skip safe methods. And XSS defeats every defense here, says OWASP, because script on your origin can read the token. Fix XSS first.

    MDN gives three values. Strict sends the cookie only for requests from the same site that set it. Lax also sends it cross-site for a top-level navigation (the address bar URL changes: a link, a form submission) that uses a safe method, which excludes fetch(), images, frames, POST, PUT and DELETE. None sends it always and requires Secure. Some browsers default to Lax when the attribute is absent, in a more permissive form that also sends the cookie on POST requests within two minutes of it being set. "Same site" includes the scheme.

    Figure 3. Is the cookie sent?

    flowchart TD accTitle: Deciding whether a SameSite cookie is sent accDescr: If the request is same-site or user-initiated, the cookie is sent. Otherwise None sends it, Strict does not, and Lax sends it only for a top-level navigation with a safe method. Q{"Same-site or typed
    by the user?"} -->|"yes"| Y["Cookie sent"] Q -->|"no, cross-site"| V{"Cookie's
    SameSite value"} V -->|"None"| Y V -->|"Strict"| N["Cookie not sent"] V -->|"Lax"| L{"Top-level navigation
    and safe method?"} L -->|"yes"| Y L -->|"no"| N

    How to read this: the lab's first table runs this chart for six cookie settings and seven situations. A cross-site form POST, image or fetch() gets no Lax cookie, but a link click does.

    It is cheap and strong, but MDN calls it not a complete defense: an attacker can trigger a top-level navigation, and it works on the site, not the origin, so you must trust every subdomain. OWASP says to treat it as defense in depth. In the lab, a form posted from a sibling subdomain (scenario H) gets the cookie under both Lax and Strict.

    Tokens: prove the request came from your page

    A synchronizer token is a random value the server stores with the session and puts in each page. State-changing requests send it back, preferably in a header (OWASP: more secure than a hidden field), and the server compares it with the stored one. OWASP says tokens should be unique per session, secret and unpredictable. An attacker's page cannot read yours, so it cannot learn the token.

    Figure 4. The synchronizer token

    sequenceDiagram accTitle: Synchronizer token pattern accDescr: The server creates a token and stores it with the session. The page includes the token. The browser sends it back with the state-changing request. The server accepts only on a match. A forged request has the cookie but no token and is rejected. participant B as Browser (shop page) participant S as Server S->>S: create token, store with session S-->>B: page containing the token B->>S: POST /transfer + session cookie + token S->>S: compare with stored token S-->>B: accepted if equal Note over B,S: a forged request has the cookie but no token: rejected

    How to read this: the cookie proves who the user is, the token proves which page sent the request. The attacker gets the first for free and cannot get the second.

    To avoid per-session server state there is the double-submit cookie: the token is also a cookie and the server checks the two match. OWASP's naive version is "for reference only" and open to cookie injection: an attacker who controls a subdomain can plant a cookie with a value they know and submit the same value. The signed version binds the token to the session with an HMAC, so a token the attacker legitimately got for their own session fails for the victim (the lab's scenario I). A custom header alone also works for AJAX endpoints, since a cross-origin request with one needs a preflight.

    Where did it come from: Origin, Referer and Fetch Metadata

    Some headers cannot be set by script. Origin is added to cross-origin requests and to same-origin POST, PUT, PATCH, DELETE and OPTIONS (MDN), and is null for an opaque origin such as a sandboxed frame. OWASP: verify it against trusted origins, fall back to Referer, reject when neither is trusted, and never allow-list null.

    Fetch Metadata adds Sec-Fetch-Site: same-origin, same-site, cross-site or none (user-initiated), a forbidden header name per MDN. OWASP calls it the primary signal and says falling back to origin verification is mandatory. The web.dev policy: allow when the header is missing (older browsers get no protection), allow same-origin, same-site and none, allow a top-level GET navigation whose destination is not object or embed, reject the rest, typically with 403. Two choices matter: allowing same-site lets a sibling subdomain through (scenario H), and allowing top-level GET navigations means a state-changing GET is still forged (scenario C).

    CORS is not a CSRF defense

    CORS relaxes the same-origin policy for reading responses; it does not stop a request being sent. MDN says a site is exposed to an origin if its response to a state-changing request carries Access-Control-Allow-Origin for that origin together with Access-Control-Allow-Credentials. A JSON API is protected in practice because application/json or a custom header needs a preflight that the server does not approve (scenario E, never sent). A simple content type such as text/plain is sent without one (scenario F), so check a token, header or origin as well. See CORS in Practice.

    Clickjacking: who may frame this page?

    Two headers say who may embed a page, and both must be HTTP headers: a meta element has no effect. Content-Security-Policy: frame-ancestors takes 'none', 'self' or a list of origins; it checks every ancestor and does not fall back to default-src (MDN), so default-src 'none' still lets anyone embed the page. X-Frame-Options is older: DENY blocks all framing, SAMEORIGIN allows it only if all ancestors share the page's origin, and ALLOW-FROM is obsolete and ignored by modern browsers. When both are sent, OWASP quotes the CSP specification: X-Frame-Options must be ignored. OWASP recommends 'none' unless framing is needed.

    Figure 5. May this page be framed?

    flowchart TD accTitle: Deciding whether a page may be framed accDescr: A page that is not in a frame always loads. A policy from a meta element is ignored. If frame-ancestors is present every ancestor must match it and X-Frame-Options is ignored. Otherwise DENY blocks, SAMEORIGIN needs same-origin ancestors, and anything else allows framing. S{"Is the page
    in a frame?"} -->|"no"| L["Loads"] S -->|"yes"| M{"Policy sent as an
    HTTP header?"} M -->|"no, meta element"| A["Anyone may frame it"] M -->|"yes"| F{"frame-ancestors
    present?"} F -->|"yes"| C["Every ancestor must match
    (X-Frame-Options ignored)"] F -->|"no"| X{"X-Frame-Options"} X -->|"DENY"| B["Blocked"] X -->|"SAMEORIGIN"| SO["Allowed only if every
    ancestor is same-origin"] X -->|"other or none"| A

    How to read this: it is the lab's mayFrame function, run on ten header combinations and five embedding situations, including a trusted page nested inside an attacker's.

    OWASP adds three points. Frame-busting JavaScript is supplementary and less reliable, with published bypasses. SameSite keeps cookies out of cross-site framed requests but does not stop framing. DoubleClickjacking targets a top-level window, so framing headers do not stop it; for sensitive actions OWASP recommends server-side transaction authorization.

    Choosing

    Defense Stops Misses
    SameSite=Lax or Strict Cross-site forms, images, fetch() Same-site attackers; link GETs (Lax)
    Synchronizer or signed token Any request without the token XSS
    Origin and Referer check Other origins Missing headers, if allowed
    Fetch Metadata Cross-site requests at the edge Old browsers; same-site if allowed
    frame-ancestors Clickjacking Forged requests

    Build it: ten requests, eleven defenses

    Goal. Predict, then see, which of ten requests (one real user, nine forgeries) each of eleven defenses lets through, and which header combinations let a page be framed.

    Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm) and models the browser's cookie and header rules and the server's checks on a virtual network. Nothing is sent.

    cd examples/frontend
    pnpm install
    cd labs/csrf-defenses-model
    pnpm test          # 53 tests
    node src/demo.ts

    Steps.

    1. In section 1, the Lax row is sent for a link click and not for a form POST, image or fetch().
    2. In section 2, row C (a link to a state-changing GET) stays FORGED even under layered: no check runs on a safe method. Row E is . everywhere because it is never sent.
    3. Rows H and I are the same-site attacks: compare fm with fm-same for H, and naive with signed for I. Section 3 prints the reason for the cells that teach something.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01, the lab's demo, node src/demo.ts):

    CSRF and clickjacking defences: who gets the cookie, who passes the check, who may frame
    
    === 1. SameSite: is the cookie sent? (target https://shop.example, cookie Secure)
    cookie               same-site POST typed URL      link, GET      form, POST     iframe, GET    img, GET       fetch, POST
    Strict               sent           sent           -              -              -              -              -
    Lax                  sent           sent           sent           -              -              -              -
    None; Secure         sent           sent           sent           sent           sent           sent           sent
    None (no Secure)     -              -              -              -              -              -              -
    unset, default Lax   sent           sent           sent           -              -              -              -
    unset, default None  sent           sent           sent           sent           sent           sent           sent
    
    === 2. Ten requests against eleven defences (the victim is logged in to shop.example)
    Each column turns on one defence; the session cookie is SameSite=None except where the column says otherwise.
    A  REAL USER  user's own form, with the token
    B  forgery    other site auto-submits a form (POST)
    C  forgery    other site links to a state-changing GET
    D  forgery    other site embeds it as an image (GET)
    E  forgery    other site: fetch, JSON body, credentials
    F  forgery    other site: fetch, text/plain body (simple)
    G  forgery    sandboxed frame on other site submits a form
    H  forgery    sibling subdomain submits a form
    I  forgery    sibling subdomain plants a csrf cookie, then submits
    J  forgery    other site, browser without Fetch Metadata
    
       none    lax     strict  origin  fm      fm-same sync    naive   signed  header  layered
    A  ok      ok      ok      ok      ok      ok      ok      ok      ok      ok      ok
    B  FORGED  .       .       .       .       .       .       .       .       .       .
    C  FORGED  FORGED  .       FORGED  FORGED  FORGED  FORGED  FORGED  FORGED  FORGED  FORGED
    D  FORGED  .       .       FORGED  .       .       FORGED  FORGED  FORGED  FORGED  .
    E  .       .       .       .       .       .       .       .       .       .       .
    F  FORGED  .       .       .       .       .       .       .       .       .       .
    G  FORGED  .       .       .       .       .       .       .       .       .       .
    H  FORGED  FORGED  FORGED  .       FORGED  .       .       .       .       .       .
    I  FORGED  FORGED  FORGED  .       FORGED  .       .       FORGED  .       .       .
    J  FORGED  .       .       .       FORGED  FORGED  .       .       .       .       .
    ok: the real user's request went through. FORGED: the server carried out the forgery. .: stopped (the reason is in section 3).
    
    === 3. Why, for the cells that teach something
    B x lax      stopped at "no session cookie": the browser did not attach the session cookie, so the server sees a logged-out request
    C x lax      FORGED at "executed": no server-side check
    C x layered  FORGED at "executed": safe method, not checked
    D x lax      stopped at "no session cookie": the browser did not attach the session cookie, so the server sees a logged-out request
    E x none     stopped at "not sent": cross-origin preflight; the server grants no CORS access
    F x header   stopped at "rejected by the server": x-csrf-protect missing
    G x origin   stopped at "rejected by the server": Origin is null (opaque origin)
    H x lax      FORGED at "executed": no server-side check
    H x fm       FORGED at "executed": Sec-Fetch-Site: same-site (allowed by this policy)
    H x fm-same  stopped at "rejected by the server": Sec-Fetch-Site: same-site
    I x naive    FORGED at "executed": token equals the csrf cookie
    I x signed   stopped at "rejected by the server": MAC is not valid for this session
    J x fm       FORGED at "executed": no Sec-Fetch-Site header (older browser): allowed
    
    === 4. Origin and Referer verification (trusted: https://shop.example)
    Origin is the shop                   allow   Origin https://shop.example is trusted
    Origin is another site               reject  Origin https://evil.example is not trusted
    Origin is a lookalike host           reject  Origin https://shop.example.evil.example is not trusted
    Origin is the shop over http         reject  Origin http://shop.example is not trusted
    Origin is null                       reject  Origin is null (opaque origin)
    no Origin, Referer is the shop       allow   no Origin; Referer origin https://shop.example is trusted
    no Origin, Referer is a lookalike    reject  no Origin; Referer origin https://shop.example.evil.example is not trusted
    neither header                       reject  neither Origin nor Referer
    
    === 5. Fetch Metadata resource isolation policy
    Sec-Fetch-Site  mode      dest      method  same-site allowed  same-origin only
    same-origin     cors      empty     POST    allow              allow
    none            navigate  document  GET     allow              allow
    same-site       navigate  document  POST    allow              reject
    cross-site      navigate  document  GET     allow              allow
    cross-site      navigate  document  POST    reject             reject
    cross-site      navigate  embed     GET     reject             reject
    cross-site      no-cors   image     GET     reject             reject
    cross-site      cors      empty     POST    reject             reject
    (missing)                           POST    allow              allow
    
    === 6. Clickjacking: may this page be framed? (page https://shop.example/checkout)
    policy                                    top-level        own page         partner          evil             own page in evil
    no header                                 loads            loads            loads            loads            loads
    X-Frame-Options: DENY                     loads            BLOCKED          BLOCKED          BLOCKED          BLOCKED
    X-Frame-Options: SAMEORIGIN               loads            loads            BLOCKED          BLOCKED          BLOCKED
    X-Frame-Options: ALLOW-FROM partner       loads            loads            loads            loads            loads
    frame-ancestors 'none'                    loads            BLOCKED          BLOCKED          BLOCKED          BLOCKED
    frame-ancestors 'self'                    loads            loads            BLOCKED          BLOCKED          BLOCKED
    frame-ancestors 'self' partner            loads            loads            loads            BLOCKED          BLOCKED
    frame-ancestors 'none' + XFO SAMEORIGIN   loads            BLOCKED          BLOCKED          BLOCKED          BLOCKED
    default-src 'none' only                   loads            loads            loads            loads            loads
    XFO DENY in a meta element                loads            loads            loads            loads            loads
    
    never        Content-Security-Policy: frame-ancestors 'none'
                 X-Frame-Options: DENY
                 both headers say the same thing
    same-origin  Content-Security-Policy: frame-ancestors 'self'
                 X-Frame-Options: SAMEORIGIN
                 both headers say the same thing
    allow        Content-Security-Policy: frame-ancestors 'self' https://partner.example
                 X-Frame-Options: (none can express this)
                 X-Frame-Options cannot name another origin (ALLOW-FROM is obsolete), so a browser without frame-ancestors gets no protection

    What the lab does not show. No browser and no network. The cookie rules follow MDN and ignore details such as the two-minute window for defaulted Lax. Frame-ancestors matching is simplified, and the signed token is a plain HMAC with a made-up secret. The matrix shows what the model predicts, not what every browser version does.

    Break it. In a scratch copy of src/defenses.ts, make checkSignedDoubleSubmit return the naive result without checking the HMAC. Scenario I then succeeds under signed and its test fails. Throw the copy away.

    Stretch. Add the two-minute defaulted-Lax window to the cookie model.

    In practice: sending store credit from a shop

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    The shop's front end calls POST /transfer. The session cookie has no SameSite attribute and there is no token. The company also runs blog.shop.example, where members post comments with limited HTML, owned by another team. Five engineers own the shop.

    Starting architecture

    Figure 6. Cookie only, and a neighbour in the same site

    Starting architecture: one cookie authenticates the transfer, and the blog subdomain is the same site as the shopBlog to Member's browser (can submit forms); Other sites to Member's browser (can submit forms); Member's browser to Shop API (POST /transfer + cookie)Blog: blog.shop.exampleBlogblog.shop.exampleOther sites: evil.exampleOther sitesevil.exampleMember's browser: has the cookieMember'sbrowserhas the cookieShop API: cookie onlyShop APIcookie onlycan submit formscan submit formsPOST /transfer + cookie

    How to read this: nothing at the shop asks where a request came from or whether the page meant to send it.

    Options considered

    Option What it fixes Risk
    SameSite=Lax only Cross-site forms, images, fetch() The blog is still trusted
    Add a synchronizer token Requests without the page's token XSS on the shop defeats it
    Fetch Metadata (same-origin only) with an Origin fallback Other sites and the blog Old browsers rely on the fallback

    The decision

    Field Decision record
    Context Cookie-only authentication, a same-site neighbour that accepts user HTML, and a transfer action.
    Decision SameSite=Lax, a synchronizer token in a header for non-safe methods, a Fetch Metadata policy allowing only same-origin and none (plus top-level GETs) with an Origin fallback, no state change on GET, and frame-ancestors 'none' on pages with actions.
    Consequences, good Several independent checks must fail together; the blog can no longer act as the user.
    Consequences, bad Every API client must send the token; a framing partner needs a specific list.
    Revisit when A partner must frame a page.

    Rollout and verification

    1. Log before blocking: run the token, Fetch Metadata and Origin checks in report-only mode and count what they would reject.
    2. Ship the token to the front end first, then enforce it.
    3. Test real flows: a link from an email into the shop is a top-level GET and must still work with Lax.

    The 2 a.m. failure

    Support reports store credit leaving the accounts of members who read one post on the blog. A comment there holds a form that submits itself to /transfer when the post opens. The shop had SameSite=Lax and a policy that allows same-site, and the blog is the same site, so both let it in. The token check was still in report-only mode.

    First three checks: (1) read the report-only log of the token check, which shows forged requests with no token and the blog's origin; (2) confirm the cookie was attached; (3) find where else user HTML is hosted under the shop's site. Mitigation: switch the token check to enforcing and allow only same-origin in Fetch Metadata. Follow-up: treat every subdomain that accepts user content as an attacker, sanitize the blog's HTML as in the XSS lesson, and add the lab's row H to the tests.

    Architect's notes

    • Layer independent defenses: cookie attribute, token, origin check and no state change on GET should each be able to stop the attack alone.
    • Trust origins, not sites, if any subdomain hosts user content.
    • Send framing headers on every page with an action.

    Common mistakes

    • Relying on SameSite alone, including the browser's default.
    • Changing state on GET.
    • A naive double-submit cookie where a subdomain can set cookies.
    • Treating CORS as protection, or checking only the content type.
    • Trusting Origin: null or a missing header, or comparing origins by prefix.
    • Framing headers in a meta element, or ALLOW-FROM.

    Key takeaways

    • CSRF works because the browser attaches the cookie whichever page caused the request.
    • SameSite stops the cookie cross-site (Lax still allows top-level GETs) but trusts the whole site.
    • Tokens prove the request came from your page; the signed version survives cookie injection.
    • Origin, Referer and Sec-Fetch-Site say where a request came from; never trust null or a missing header without a fallback.
    • CORS is not a defense, and frame-ancestors (with X-Frame-Options) stops clickjacking, as headers, not meta.
    • Never change state on GET, and fix XSS first.

    Practice exercises

    Exercise 1 — Starter (45 min): For each lab scenario, predict the layered column before reading it, then explain row C in one sentence.

    Exercise 2 — Intermediate (2 hours): Add a scenario where the attacker is a sibling subdomain and the shop uses fm-same plus a token, and test it.

    Exercise 3 — Advanced (half day): Audit an application you know: list each state-changing endpoint, its method, how it authenticates and which defenses apply.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments