Skip to content
← Blog

Content Security Policy in Laravel with Vite Nonces

Burak Berk Şama · · 5 min read · Software Development

In short: The cleanest way to set up a Content Security Policy (CSP) in Laravel is a nonce generated on every request. It takes three pieces:

  • a call to Vite::useCspNonce() in a middleware
  • nonce="{{ Vite::cspNonce() }}" on inline scripts
  • a script-src 'self' 'nonce-…' header on the response

This post shares the policy I use on my own site, the trade-offs I made for Alpine.js and Filament panels, and why.

When I scanned 117 business websites in Denizli, 97% had no CSP. CSP isn't mandatory. But if someone manages to run a malicious script on the site, say through a comment field or a compromised plugin, it is the last line of defence that lets the browser block it.

The policy

This is the policy on this site's public pages:

default-src 'self';
script-src 'self' 'nonce-…' 'unsafe-eval';
style-src 'self' 'unsafe-inline';
img-src 'self' data:;
font-src 'self';
connect-src 'self';
frame-src 'none';
manifest-src 'self';
frame-ancestors 'self';
base-uri 'self';
object-src 'none';
form-action 'self'

In short:

  • Everything loads only from the site's own domain.
  • Inline scripts run only if they carry the nonce for that request.
  • The site can't be framed inside another site.
  • Forms can only be submitted to the site itself.

The policy can be this strict because the site loads nothing from outside. Fonts, images and scripts all live on its own server. A site using Google Fonts, external analytics or chat widgets has to add each of those sources to the policy.

The Laravel side: middleware

Laravel has built-in nonce support for files built with Vite. When Vite::useCspNonce() is called, Laravel generates a random value for that request and adds it to every <script> and <link> tag that @vite outputs.

public function handle(Request $request, Closure $next): Response
{
    // The Vite dev server loads from another port, so no strict policy locally
    $strict = ! $this->isPanel($request) && ! Vite::isRunningHot();

    if ($strict) {
        Vite::useCspNonce();
    }

    $response = $next($request);

    $response->headers->set('Content-Security-Policy', implode('; ', $strict ? $this->policy() : self::BASE));

    return $response;
}

The middleware is added to all requests in bootstrap/app.php. The nonce has to be enabled before the response is built; otherwise it doesn't exist yet when the views render.

Wherever an inline script is needed, it uses the same value:

<script nonce="{{ Vite::cspNonce() }}">document.documentElement.classList.add("js");</script>

<script type="application/ld+json"> tags for structured data aren't executed code, so they don't need a nonce.

The trade-offs I made

A good CSP has to fit how the site actually works. My policy has three deliberate trade-offs.

1. 'unsafe-eval' for Alpine.js

The site's interface uses Alpine.js. Alpine evaluates expressions like x-data="{ open: false }" in the HTML at runtime, which needs 'unsafe-eval'.

This permission does not run scripts without a nonce. A <script> tag injected from outside, or added without a nonce, is still blocked. It only allows code already loaded on the page to evaluate text.

There is a stricter alternative: Alpine's CSP-compatible build. But that build doesn't allow expressions in the HTML; each component must be defined separately. With dozens of small interactions on this site, I haven't switched for now.

2. style-src 'unsafe-inline' for inline styles

Pages set values such as bar chart widths and animation order through style="" attributes. Style injection is a far more limited risk than script injection, so I left this permission for styles.

3. A basic policy for admin panels

Filament and Livewire add their own inline scripts without a nonce. So /admin, /demo and Livewire requests get only the basic restrictions:

frame-ancestors 'self'; base-uri 'self'; object-src 'none'; form-action 'self'

The panels are only available to signed-in users. Public pages, where visitors can add content, get the full policy.

The development environment

While npm run dev is running, Vite serves files from a different port (such as localhost:5173) and injects its own client code. A strict policy blocks that. So the middleware detects the dev server with Vite::isRunningHot() and switches to the basic policy locally.

One consequence: to see the strict policy locally, build with npm run build and delete public/hot. I do that before each release and check the console for CSP errors.

Tests

A change that breaks the policy usually arrives quietly: someone adds a <script> without a nonce and that feature stops working in production. So I check these with tests:

  • Do public pages have default-src 'self' and a nonce-based script-src?
  • Does the admin panel have frame-ancestors but no script-src?
  • Has the X-Powered-By header been removed?

Watch out in production

Some hosts add their own CSP header to responses. This site's server, for example, sends a second header containing upgrade-insecure-requests. When there are several CSP headers, the browser applies all of them together. One header can't loosen another, only tighten it further. After going live, it is a good habit to check the headers that actually arrive in the browser's developer tools.

Caching is another issue. The nonce changes on every request. A system that caches whole pages would send the same nonce to everyone, which weakens the protection. If you use full-page caching, consider a different method, such as hashes, instead of a nonce.

You can check whether your site has a CSP and other security headers with the site check tool.

Frequently asked questions

How do I use a CSP nonce in Laravel?

Call Vite::useCspNonce() in a middleware and add a Content-Security-Policy header containing the nonce to the response. Files added with @vite get the nonce automatically. Add nonce="{{ Vite::cspNonce() }}" to inline scripts by hand.

Does Alpine.js work with CSP?

The standard Alpine build needs 'unsafe-eval' to evaluate expressions in the HTML. If you don't want to allow that, use Alpine's CSP-compatible build, which requires defining components separately.

Can I add a CSP to a Filament panel?

Basic restrictions (frame-ancestors, base-uri, object-src, form-action) can be added without problems. Filament and Livewire add inline scripts without a nonce, so a strict script-src may break the panel.

Is CSP mandatory?

No. CSP isn't a legal requirement; it is an extra layer of security. It is recommended because it gives browser-level protection against malicious code injection.

Why does CSP throw errors with the Vite dev server?

The dev server serves files from a different port and injects its own client code into the page. A strict policy blocks that. Detect the dev environment with Vite::isRunningHot() and relax the policy there.

Laravel PHP Web