Skip to content

Configuring CSP in Magento

Currently Hyvä CSP is unreleased

This is a documentation preview.
Please watch the #update-notifications channel in Slack to be notified when it is available.

Removing unsafe-eval and unsafe-inline

In Magento, when developing an Alpine component (or any JavaScript code) so it works with strict CSP, it is best to set up the development environment accordingly.

After this change, all code relying on unsafe-eval or unsafe-inline will cause a stack trace in the browser console.
Be sure to enable the "Warning" log level in the browser dev console to see helpful information from Alpine indicating the expression and the element causing the issue.

Disabling unsafe-eval forces alpine-csp

If unsafe-eval is disabled, Hyvä automatically uses the Alpine CSP build instead of regular Alpine.

Disabling unsafe-inline breaks scripts in CMS content

Be aware that using scripts in CMS content is not possible once unsafe-inline is disabled!

Manual configuration

One way to do so is to add the following configuration to the app/etc/env.php file:

    'system' => [
        'default' => [
            'csp' => [
                'mode' => [
                    'storefront' => [
                        'report_only' => 0,
                    ]
                ],
                'policies' => [
                    'storefront' => [
                        'scripts' => [
                            'eval' => 0,
                            'inline' => 0,
                        ]
                    ]
                ]
            ]
        ]
    ]

Then run bin/magento app:config:import.

CLI configuration

If you are using the popular Magerun tool, this can be done with the following commands:

n98-magerun config:env:set system/default/csp/policies/storefront/scripts/inline 0
n98-magerun config:env:set system/default/csp/policies/storefront/scripts/eval 0
n98-magerun config:env:set system/default/csp/mode/storefront/report_only 0
bin/magento app:config:import

Forcing strict CSP on specific routes

Magento allows enabling of disabling specific policies on a route basis.
The following example can be found in the etc/config.xml file of the Magento_Checkout module.
It enables strict mode and disables unsafe-inline for the checkout_index_index route.

    <csp>
        <mode>
            <storefront_checkout_index_index>
                <report_only>0</report_only>
            </storefront_checkout_index_index>
        </mode>
        <policies>
            <storefront_checkout_index_index>
                <scripts>
                    <inline>0</inline>
                    <event_handlers>1</event_handlers>
                </scripts>
            </storefront_checkout_index_index>
        </policies>
    </csp>