Alpine adds a new build to work with Content Security Policies
Last updated on by Eric L. Barnes
Caleb Porzio announced that Alpine.js now has a CSP build that will work with environments where CSP is required:
In order for Alpine to be able to execute plain strings from HTML attributes as JavaScript expressions, for example x-on:click="console.log()", it needs to rely on utilities that violate the "unsafe-eval" Content Security Policy that some applications may enforce for security purposes.
In order to accommodate environments where this CSP is necessary, Alpine offer's an alternate build that doesn't violate "unsafe-eval", but has a more restrictive syntax.
One thing to note with this new build is you must use Alpine.data:
Since Alpine can no longer interpret strings as plain JavaScript, it has to parse and construct JavaScript functions from them manually.
Due to this limitation, you must use Alpine.data to register your x-data objects, and must reference properties and methods from it by key only.
This new build is available as a CDN or via npm install @alpinejs/csp
See the official documentation for complete details and for instructions.
Note: When asked about Livewire support, Caleb says, "Not yet unfortunately because there is one or two places Livewire relies on eval (wire:click="something('one', 'two')")
kinda thing"
Eric is the creator of Laravel News and has been covering Laravel since 2012.