Start with the boundary
Choose CSRF defenses that fit a single-page app is easiest to get right when the boundary is named before the implementation begins. Decide which system owns the decision, which inputs are trusted, what the caller can observe, and what must remain private. That framing prevents a local optimization from quietly becoming an undocumented protocol.
A single-page interface does not automatically eliminate CSRF. If the browser sends an authentication cookie automatically, another origin may be able to induce a state-changing request even though it cannot read the response. The defense must match the credential transport and the browsers your users actually operate.
Model the system before choosing a tool
Classify each credential: cookie, bearer header, client certificate, or one-time code. SameSite cookies reduce cross-site exposure but are not a substitute for a complete policy across legacy browsers and navigation flows. For cookie-authenticated mutations, use a synchronizer token or a signed double-submit token and validate the request origin or referer where appropriate.
Write the model down as a small state diagram or table before selecting a library. Identify the durable state, the derived state, and the transitions that may be retried. This makes it easier to compare a managed service with an in-process implementation and to explain why a particular trade-off is acceptable for this workload.
Design for failure, misuse, and change
Watch for JSON-only assumptions when a form-encoded request can reach the endpoint, CORS configured as a credential grant for arbitrary origins, state-changing GET routes, and a token stored where an attacker can read it. A CSRF token that is not bound to the session or tenant can be replayed. Do not confuse CORS with CSRF protection.
A resilient design assumes that inputs are incomplete, dependencies are slow, operators make mistakes, and requirements will change. Put limits at the boundary, return errors that a caller can act on, and preserve enough context to distinguish a bad request from an unavailable dependency. Avoid broad fallbacks that make an unsafe state look successful.
Implementation example
Require a custom header or token for mutations and reject requests without the expected content type, origin, and authorization context. Set cookies with Secure, HttpOnly, and an intentional SameSite value. Keep login, logout, password changes, billing, and destructive actions under the same policy. For bearer-token SPAs, prevent tokens from being exposed to scripts or URLs unnecessarily.
Keep the first implementation narrow enough to review line by line. Make inputs, outputs, authorization context, and failure behavior explicit instead of hiding them behind a convenience helper. The example should be safe to run with synthetic data, emit a correlation identifier, and leave a durable artifact that another engineer can inspect after the request has finished.
POST /api/profile
Origin: https://pingflow.app
X-CSRF-Token: session-bound-tokenVerify and troubleshoot
Send cross-origin form, fetch, image, and navigation attempts against representative mutations. Test missing, stale, wrong-session, and wrong-origin tokens, as well as legitimate subdomain and mobile clients. Confirm preflight behavior does not create an accidental bypass and that a rejected request produces no state change.
Use a small test matrix that covers the ordinary path, an empty or missing input, a duplicate request, a timeout, a permission failure, and a version mismatch. Assert both the response and the side effects. When a test fails, compare the observed transition with the model rather than adding a retry or widening a timeout without evidence.
Operations and recovery
Monitor CSRF failures by route and origin, unexpected credentialed CORS requests, and mutations arriving through GET. Keep a documented exception process for integrations that cannot send the normal token. If a token leak is suspected, rotate the session or signing key and invalidate affected sessions rather than merely changing the UI.
Give the operator a bounded recovery action: replay a safe event, rebuild a derived view, rotate a credential, drain a queue, or roll back a compatible revision. Record the owner, retention period, alert threshold, and rollback condition next to the implementation. A runbook is useful only when it can be followed without reconstructing the design from production logs.
A practical decision guide
For a small service, prefer the design with the fewest hidden states that still meets the application security requirement. Add a managed dependency when it removes a failure mode you can measure, not simply because it is popular. Keep the interface replaceable by isolating provider-specific code behind a narrow adapter and by testing the behavior your users depend on.
Revisit the decision when traffic shape, data sensitivity, team ownership, or recovery objectives change. A design that is excellent for a single tenant or a low-volume internal tool can be the wrong design for a public multi-tenant path. Record the assumptions so the next change starts with evidence rather than folklore.
An implementation checklist
Before publishing a change related to choose csrf defenses that fit a single-page app, write down the input contract, authorization context, state transitions, limits, and user-visible errors. Identify the smallest synthetic dataset that demonstrates the normal path and the smallest dataset that demonstrates the dangerous path. Add a correlation ID to the example, make retries deliberate, and decide which artifacts can be retained for support without copying secrets or unnecessary personal data. This checklist is deliberately boring: repeatable release evidence is more valuable than a clever demo.
Use a disposable environment to exercise the implementation with realistic concurrency and a dependency failure. Compare the observed result with the contract, then record the measured latency, resource use, and recovery action. If a managed service or library is involved, pin its version and capture the relevant configuration. Ship behind a reversible change when the behavior is new, and schedule a follow-up review after real traffic reveals assumptions that a test fixture could not.
References and further reading
Use the OWASP CSRF Prevention Cheat Sheet, Fetch and cookie specifications, and the browser compatibility guidance for SameSite. Document the chosen credential transport and why the defense is sufficient for each client class.
Prefer primary protocol specifications, vendor security documentation, and measured behavior from a disposable environment. Read the failure and deprecation sections, not only the happy-path quick start. A short reference list attached to the code gives future maintainers a way to distinguish an intentional constraint from an accidental implementation detail.