Search code examples
node.jsvitesveltecontent-security-policysveltekit

Prevent svelte build from including inline script as it violates CSP


I have a svelte + typescript app. I build the app with node-adapter and hosted it with the node+express+ts backend (which also uses helmet). The build produced by Svelte contains inline script, which results in a Content Security Policy violation. This is the error shown in the browser console:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-owsofOMZa3ZfSXXALEDxpXu6L/jonHMy8m+0p2OoBQM='), or a nonce ('nonce-...') is required to enable inline execution.

I found a similar issue on github, which provided a solution with sentry which I don't know anything about. It also talks about hooks, but I am not using hooks in my project.

I am lost here, and I don't know how to solve it other than using 'unsafe-inline'.

My svelte.config.json :

import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';

/** @type {import('@sveltejs/kit').Config} */
const config = {
    preprocess: vitePreprocess(),

    kit: {
        adapter: adapter()
    }
};

export default config;

I also have set prerender = true in root +layout.ts.


Solution

  • If you define the CSP in SvelteKit, I think it should work:

    SvelteKit will augment the specified directives with nonces or hashes (depending on mode) for any inline styles and scripts it generates.