A Content Security Policy (CSP) is a browser security mechanism that helps prevent XSS and other code injection attacks by specifying which sources of content are allowed. In SvelteKit, CSP can be implemented via HTTP headers or meta tags.
If you are using a server adapter (like adapter-node), you can set CSP headers in hooks or your server configuration.
For fully static sites using adapter-static, you can add a <meta> tag in your app.html file to enforce CSP.
If your app uses {@html} or inline scripts/styles, you may need to add 'unsafe-inline' to your CSP, but this reduces security. A safer approach is to sanitize HTML and avoid inline scripts whenever possible.
Use 'self' to allow only same-origin scripts, styles, and media.
Avoid 'unsafe-inline' unless absolutely necessary.
Sanitize dynamic HTML rendered via {@html} to prevent XSS.
Test CSP in reporting mode first (Content-Security-Policy-Report-Only) to ensure nothing breaks.
Combine CSP with Svelte's default HTML escaping for robust security.