Table of Contents & Menu
Navigation

CSP compatibility

CSP compatibility for Hyvä developers primarily involves two restrictions: avoiding JavaScript expressions in Alpine bindings and preventing inline script injection at runtime.

No unsafe-eval

When unsafe-eval is disallowed in a Content Security Policy (CSP), dynamic JavaScript code creation and execution are blocked.

  • Using eval() is forbidden
  • Programmatically creating functions with the Function constructor is forbidden

Standard Alpine.js relies on unsafe-eval to dynamically create functions for evaluating attribute expressions. This means it won't work with strict CSPs that prohibit unsafe-eval.

How does Hyvä work without unsafe-eval?

Hyvä's Alpine CSP-compatible version avoids unsafe-eval by disallowing JavaScript expressions in Alpine bindings. Instead, only bindings that refer directly to Alpine component properties are permitted. All attribute bindings are converted into functions on the Alpine components. For more details, refer to the Hyvä Alpine CSP documentation.

No unsafe-inline

Disallowing unsafe-inline prevents the execution of unauthorized <script> tags, protecting against injected scripts. Scripts are authorized either by a SHA256 hash of their content in the CSP header or by a matching nonce attribute.

Additionally, inline event handlers (e.g., <a href="..." onclick='this.target="_blank"'>) are forbidden without unsafe-inline.

How does Hyvä work without unsafe-inline?

Hyvä handles unsafe-inline by using nonces for uncached pages and SHA hashes for cached pages. To authorize an inline script, add the following line immediately after its closing tag:

</script>
<?php $hyvaCsp->registerInlineScript() ?>

The $hyvaCsp instance is a readily available template variable in Hyvä themes, similar to $block and $viewModels.

Important!

The $hyvaCsp->registerInlineScript() has to be called directly after the closing script tag!
There must be no other HTML in between.

For pages with multiple inline scripts, $hyvaCsp->registerInlineScript() must be called after each script.

$hyvaCsp availability

The $hyvaCsp template variable is available in all Hyvä theme and Admin theme templates.
On Luma based storefronts the variable is not defined.

In modules, be sure to only reference it in frontend templates declared in a hyva_* layout handle to avoid errors in Luma themes.