murtaza1904's avatar

How to set Content Security Policy for Laravel bundle assets using spatie

I am using spatie/laravel-csp package for setting up CSP for my web app. I bundle my JS and call them in the layout this this.

@vite('resources/js/app.js')

Before bundling it was working fine but after bundling my assets I got errors from Spatie package These are the two errors

Refused to load the script 'http://[::1]:5173/@vite/client' because it violates the following Content Security Policy directive: "script-src 'self' 'nonce-h8NpfGFc7bxb1WLH74Mxzkoa3wMQ0umA' http://127.0.0.1:5173/resources/js/app.js". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
Refused to load the script 'http://[::1]:5173/resources/js/app.js' because it violates the following Content Security Policy directive: "script-src 'self' 'nonce-h8NpfGFc7bxb1WLH74Mxzkoa3wMQ0umA' http://127.0.0.1:5173/resources/js/app.js". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

This is my guest layout policy class

$this
            ->addDirective(Directive::STYLE, 'https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css')
            ->addDirective(Directive::STYLE, 'https://fonts.googleapis.com/css2')
            ->addDirective(Directive::DEFAULT, 'https://fonts.googleapis.com/css2')
            ->addDirective(Directive::DEFAULT, 'https://fonts.gstatic.com/')
            ->addDirective(Directive::STYLE, 'https://cdnjs.cloudflare.com/ajax/libs/boxicons/2.1.0/css/boxicons.min.css')
            ->addDirective(Directive::DEFAULT, 'https://cdnjs.cloudflare.com/')
            ->addDirective(Directive::IMG, 'data:');

How do I define policy for vite bundle?

0 likes
2 replies
DimitarV's avatar
DimitarV
Best Answer
Level 12

Maybe is to late to answer but anyway, I had the same Issue and the problem was the host variable in vite.config.js:

server: {
        host: process.env.VITE_SERVER_HOST,
    } 

value in the env was empty and the host was set by default to 127.0.0.1:5173 after I set the variable to localhost and changed the policy to be:

 <meta http-equiv="Content-Security-Policy" content="script-src 'self' localhost:*">

the issue was fixed and the vite scripts were loaded properly.

1 like

Please or to participate in this conversation.