Sub topic 3
Enabling Shared Memory in Browsers with Cross-Origin Isolation
The previous chapter showed that posting a SharedArrayBuffer to a worker shares memory instead of copying it. If you run that code from an ordinary web page, it often fails before it starts: SharedArrayBuffer is undefined, or the worker never gets the buffer. Browsers only give a page shared memory after the page proves it is cross-origin isolated. This chapter explains why that rule exists, which headers satisfy it, and how to fix the breakage those headers can cause.
This chapter assumes you know basic HTTP response headers, what an origin is (scheme, host, and port), and how to load a Web Worker. It also assumes you can run a small Node.js script.
Why Browsers Lock Shared Memory Away
The Spectre problem
In early 2018, researchers disclosed Spectre, a family of CPU attacks. Speculative execution can leave traces in the CPU cache, and an attacker who can time memory accesses precisely can read data from the same process. In a browser, that data might come from another site's resources loaded into your page, such as a cross-origin image or script.
Browsers responded by lowering the precision of performance.now(). SharedArrayBuffer gets around that defence. One worker spins in a loop incrementing a shared integer, and another thread reads that integer as a clock with nanosecond-scale resolution. Browsers disabled SharedArrayBuffer everywhere for this reason.
The fix: keep other sites' data out of the process
The browsers brought SharedArrayBuffer back under one condition. The page must guarantee that no cross-origin data enters its process unless that data's owner agreed to it. Without unconsented secrets in the process, a precise timer has nothing to steal. Two response headers make that guarantee, and together they make the page cross-origin isolated.
The Two Headers
Serve the top-level document with both of these:
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corpCross-Origin-Opener-Policy (COOP)
COOP controls which windows can share a browsing context group with your page. A browsing context group is the set of windows that can hold references to each other through window.opener or the return value of window.open(). With same-origin, any cross-origin window that opens your page, or that your page opens, goes into a separate group. The browser can then put your page in its own process.
| COOP value | Effect | Counts toward isolation? |
|---|---|---|
| `unsafe-none` (default) | Shares the group with openers and popups | No |
| `same-origin-allow-popups` | Keeps references to popups the page opens itself | No |
| `same-origin` | Cuts every cross-origin opener and popup link | Yes |
Cross-Origin-Embedder-Policy (COEP)
COEP controls what your page may load. With require-corp, every subresource (scripts, images, fonts, iframes, worker scripts) must be one of these:
- Same-origin with the page.
- Loaded with CORS, for example
<img crossorigin src="...">from a server that returnsAccess-Control-Allow-Origin. - Served with a
Cross-Origin-Resource-Policy(CORP) header that allows it, such asCross-Origin-Resource-Policy: cross-origin.
The browser blocks anything else. A third-party image without CORP fails to load, and the DevTools console reports it as blocked by COEP.
A second value, credentialless, also counts toward isolation in Chromium-based browsers and Firefox. It loads cross-origin no-CORS resources without cookies or other credentials, so they need no CORP header. Because the requests carry no credentials, the responses are public data and are safe to load. Check current support tables before you rely on it in Safari.
Detecting Isolation at Runtime
The crossOriginIsolated global tells you whether the current context qualifies. It exists on windows and in workers, so check it before you create shared memory:
if (!globalThis.crossOriginIsolated) {
console.warn('SharedArrayBuffer is unavailable: page is not cross-origin isolated');
}If the check fails, fall back to plain message passing, or show a clear error. Testing typeof SharedArrayBuffer also works in current browsers, but crossOriginIsolated states the actual requirement and is clearer to anyone reading your code.
A Working Local Setup
localhost counts as a secure context, but the headers are still required. Opening the HTML file directly through file:// will not work. This Node.js server sends both headers on every response, worker scripts included:
// server.js — run with: node server.js
const http = require('node:http');
const fs = require('node:fs/promises');
const path = require('node:path');
const ROOT = __dirname;
const TYPES = { '.html': 'text/html', '.js': 'text/javascript' };
http.createServer(async (req, res) => {
const urlPath = req.url === '/' ? '/index.html' : req.url.split('?')[0];
const file = path.join(ROOT, path.normalize(urlPath));
if (!file.startsWith(ROOT)) {
res.writeHead(403).end();
return;
}
try {
const body = await fs.readFile(file);
res.writeHead(200, {
'Content-Type': TYPES[path.extname(file)] ?? 'application/octet-stream',
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
});
res.end(body);
} catch {
res.writeHead(404).end('Not found');
}
}).listen(8080, () => console.log('Open http://localhost:8080'));Put these two files next to server.js:
<!-- index.html -->
<!doctype html>
<title>Isolation check</title>
<script type="module">
console.log('isolated:', crossOriginIsolated);
const sab = new SharedArrayBuffer(4);
const view = new Int32Array(sab);
const worker = new Worker('worker.js');
worker.onmessage = () => console.log('value:', Atomics.load(view, 0));
worker.postMessage(sab);
</script>// worker.js
self.onmessage = (event) => {
const view = new Int32Array(event.data);
Atomics.store(view, 0, 7);
self.postMessage('done');
};The console should print isolated: true and then value: 7. Remove the COOP header and reload: crossOriginIsolated becomes false and the constructor call throws a ReferenceError.
If you use Vite, add the same two headers under server.headers in vite.config.js. Most other dev servers have an equivalent setting.
Edge Cases and Gotchas
Workers and iframes
- Dedicated workers inherit isolation from the page that creates them. Send COEP on worker scripts anyway. Some browsers check the worker response's own policy, and the header does no harm.
- Shared workers and service workers do not inherit isolation. Their script responses need their own COEP header.
- Iframes must also be served with COEP, and a cross-origin iframe needs CORP or CORS to load at all. Cross-origin iframes also need the
cross-origin-isolatedpermission delegated throughallow="cross-origin-isolated"before they getSharedArrayBufferthemselves.
Things that break
| Symptom | Cause | Fix |
|---|---|---|
| Third-party images or fonts disappear | Their servers send no CORP header | Add `crossorigin` if they support CORS, ask the vendor for CORP, self-host the files, or try `credentialless` |
| OAuth or payment popup cannot talk back | COOP `same-origin` cut `window.opener` | Move that flow to a page without COOP, or redirect instead of using a popup |
| Embedded video player iframe is blank | The iframe document lacks COEP and CORP | Ask the provider for isolation-compatible embeds, or drop isolation on that page |
| Headers set but still not isolated | A CDN or proxy removed them, or they are only on subresources | Check the document response in the DevTools Network tab |
| `document.domain` assignments stop working | Isolated pages cannot relax same-origin checks | Use `postMessage` between frames |
Rolling out safely
Turning on require-corp in production can quietly break embeds. Deploy Cross-Origin-Embedder-Policy-Report-Only: require-corp first, plus a Report-To or Reporting-Endpoints header. The browser then reports which resources it would block, without blocking them. COOP has a matching Cross-Origin-Opener-Policy-Report-Only header.
Exercises
Exercise
A page sends Cross-Origin-Embedder-Policy: require-corp but no COOP header. What does crossOriginIsolated report, and what still changes?
Show answer
It reports false, because isolation needs both headers, so SharedArrayBuffer stays unavailable. COEP is still enforced, though, so cross-origin subresources without CORS or CORP are blocked even though the page gains nothing from it.
Exercise
After you enable both headers, a logo loaded from https://cdn.example.net/logo.png stops showing. Name two fixes that keep the page isolated.
Show answer
Have the CDN send Cross-Origin-Resource-Policy: cross-origin, or load the image with the crossorigin attribute from a CDN that returns Access-Control-Allow-Origin. Self-hosting the image or switching COEP to credentialless also works.
Exercise
Why does SharedArrayBuffer count as a security risk while a regular ArrayBuffer does not?
Show answer
Shared memory lets one thread increment a counter that another thread reads, which builds a high-resolution timer. Spectre-style attacks need that timer to read cross-origin data from the process. A regular ArrayBuffer is copied or transferred, never accessed by two threads at once, so it cannot build that timer.