web-workerhttp-status-code-304sharedarraybuffercross-origin-embedder-policycross-origin-resource-policy

304 ERR_BLOCKED_BY_RESPONSE for web worker file after enabling same-origin CORS to allow SharedArrayBuffer


I'm looking to do some multithreading for my web application to improve performance and I've stumbled upon a head-scratcher. I'm currently developing on localhost (vite server) on Chrome.

Basically I have spawned a web worker. Then I created a SharedArrayBuffer.

At first, the SharedArrayBuffer was getting an error that it wasn't defined. I found out it is disabled unless you specify that you only want to allow same-origin on cors. So I added these headers to my vite server:

        'Cross-Origin-Embedder-Policy': 'require-corp',
        'Cross-Origin-Opener-Policy': 'same-origin',

It solved the problem with SharedArrayBuffer. But then, I started getting 304 errors for my worker

GET http://localhost:5001/js/searchWorker.js net::ERR_BLOCKED_BY_RESPONSE 304

If I allow cross origin with a wildcard, the web worker works, but the shared array buffer does not. And vice versa. I don't really understand as well because shouldn't it allow searchWorker.js because it's at the same origin (localhost)?

I don't really understand how to fix this issue!

Thanks!


Solution

  • An origin is defined by the combination of scheme (protocol) + hostname (domain) + port of the URL.

    I haven't used vite in a while, but I think that your web page and web worker are served on different ports (8080 and 5001 maybe?), so they are on different origins. That would explain why the web worker works if you add a wildcard.

    On the other hand, using a wildcard to allow cross-origin fetches prevents you from achieving the status of cross-origin isolation, which is a requirement if you want to use SharedArrayBuffer.

    Since the web worker script is a cross-origin resource, fetching it is a cross-origin fetch, which is blocked by cross-origin isolation unless you explicitly opt-in (i.e. you tell the browser that is ok to fetch that resource).

    From the article Making your website "cross-origin isolated" using COOP and COEP:

    For a document or a worker served with COEP: require-corp, cross-origin subresources loaded without CORS must set the Cross-Origin-Resource-Policy: cross-origin header to opt into being embedded. For example, this applies to <script>, importScripts, <link>, <video>, <iframe>, etc.

    I think the solution is to configure the vite dev server to add a Cross-Origin-Resource-Policy: cross-origin response header to the worker script.

    See also these links: