Search code examples
corssveltesveltekit

Set crossOriginIsolated Svelte and SvelteKit


I'm new in Svelte and SvelteKit and I'm getting this error when trying to execute a worker:

Uncaught DOMException: Failed to execute 'postMessage' on 'Worker': SharedArrayBuffer transfer requires self.crossOriginIsolated.

I know I need to set the headers (I'm moving from React to Svelte), but how/where do I set the headers?


Solution

  • So the solution was setting Vite's "configureServer" in the "svelte.config.js" (here's a link to Vite documentation). The implementation looks like this:

    import adapter from '@sveltejs/adapter-auto';
    
    /** @type {import('vite').Plugin} */
    const viteServerConfig = {
        name: 'log-request-middleware',
        configureServer(server) {
            server.middlewares.use((req, res, next) => {
                res.setHeader("Access-Control-Allow-Origin", "*");
                res.setHeader("Access-Control-Allow-Methods", "GET");
                res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
                res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
                next();
            });
        }
    };
    
    /** @type {import('@sveltejs/kit').Config} */
    const config = {
        kit: {
            adapter: adapter(),
            vite: {
                plugins: [viteServerConfig]
            }
        }
    };
    
    export default config;