kit
kit copied to clipboard
Unable to set response headers for SharedArrayBuffer
Describe the bug
I have a project which depends on a library which uses SharedArrayBuffer, but I can't get it to work, and always get this error:
ReferenceError: SharedArrayBuffer is not defined
What I need to do
Set
-
Cross-Origin-Opener-Policy
header tosame-origin
-
Cross-Origin-Embedder-Policy
torequire-corp
What I have tried:
- setting headers in
vite.config.js
export default defineConfig({
server: {
headers: {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Embedder-Policy": "require-corp",
},
},
plugins: [sveltekit()],
});
- Writing a hooks.js file to use custom headers
- Using a middleware in
vite.config.js
to set headers
Reproduction
Smallest possible repro: Live example Repo
Logs
No response
System Info
1.60.125 Chromium: 119.0.6045.199 (Official Build) (64-bit)
Severity
blocking all usage of SvelteKit
Additional Information
No response
I've also noticed a strange bug, where SharedArrayBuffer
is defined for a split second or something in the example repro:
@Rich-Harris I'm sorry for the ping, but can you take a look at this?
Got the same problem, a custom middleware for Vite helped:
function crossOriginIsolationMiddleware(_, response, next) {
response.setHeader("Cross-Origin-Opener-Policy", "same-origin");
response.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
response.setHeader("Cross-Origin-Resource-Policy", "cross-origin");
next();
}
const crossOriginIsolation = {
name: 'cross-origin-isolation',
configureServer: server => { server.middlewares.use(crossOriginIsolationMiddleware); },
configurePreviewServer: server => { server.middlewares.use(crossOriginIsolationMiddleware); },
};
/** @type {import('vite').UserConfig} */
const config = {
plugins: [
// Other plugins,
crossOriginIsolation
]
};
Source: https://www.reddit.com/r/sveltejs/comments/zc1199/sveltekitvite_deployment_is_preview_acceptable/
I have a similar issue when trying to use web workers alongside the cross-origin policy HTTP headers. If I set them in a src/hooks.server.ts
, they are not returned when loading the web workers. And no HTTP headers I set in vite.config.ts
using Vite's recommended configuration seem to show up when inspecting the response, not just the cross-origin policy ones.
The workaround @pk992 shared did work though.