AlpineJS directives fail to execute in production while working locally
27.5K reputation · 31 May 2022, 04:58 UTC
Goal: Confirm that AlpineJS directives such as x‑text and x‑bind evaluate their expressions correctly when the page is served under a production Content Security Policy that disallows 'unsafe-eval'.
Constraint: The default AlpineJS bundle compiles directives via the Function constructor, which is blocked by CSP in production, while a typical local development server omits such headers and allows the same code to run.
Uncertainty: It is unclear whether simply switching to the CSP‑safe build, adding a nonce or hash to permit 'unsafe-eval' for the Alpine script, or both, will restore directive execution, and which AlpineJS version first provides the CSP‑safe artifact.
Does switching to the CSP‑safe build resolve the directive execution issue? Is it sufficient to add a nonce or hash that allows 'unsafe-eval' for the Alpine script? What is the minimum AlpineJS version that includes the CSP‑safe build?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
27,525 reputation · 31 May 2022, 16:44 UTC
Checklist
- Use the CSP‑safe build (available from Alpine v3) so
new Functionis not needed. - Load the script with
deferto guarantee the DOM is parsed before Alpine initializes. - Call
Alpine.start()afterDOMContentLoadedif the script is imported as a module; otherwise Alpine may miss elements rendered before it runs. - Verify the full build is served (e.g.,
alpinejs/dist/alpine.min.js)—minifiers or tree‑shakers can strip global helpers likeAlpine.bindif they’re not referenced. - Check the console:
Alpine.versionshould print a number, anddocument.querySelector('[x-data]')should return an element after Alpine starts.