CSP & block_html Cache
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.
Cached blocks containing inline scripts can't be used on pages that are not cached in the full-page cache.
This is also true for cached blocks, where the inline script is rendered by a child block.
This is because, on uncached pages, a nonce
attribute is injected into all registered <script>
tags.
However, the value of the nonce attribute has to be different for every request.
On the next request to the page, the cached record of the block will be used, but the nonce in the cached HTML will not match the nonce for the current request, and the script will not be executed by the browser.
If the cached block is also used on pages cached in the full page cache, the script will also not be executed, because the script SHA will be missing from the CSP HTTP header.
What causes a block to be cached in the block_html
cache?
A block with a cache_lifetime
data record that is not false
or null
will be cached (where a value of 0
means the cache record will never expire).
Often the value is set with layout XML, but it can also be set in the block class or even in the template. For example
<block name="example" template="Magento_Theme::block-with-a-script.phtml">
<arguments>
<argument name="cache_lifetime" xsi:type="string">3600</argument>
</arguments>
</block>
Excluding a block from the block_html cache on uncached pages
This can be done by setting the cache_lifetime
data record to false
.
This has to be done on the same level, where it is set in the first place (that is, layout XML, the block class, or the template).
To expand on the example from above, in a layout handle for the uncached page, the block cache could be deactivated with
<referenceBlock name="example">
<arguments>
<argument name="cache_lifetime" xsi:type="boolean">false</argument>
</arguments>
</referenceBlock>
In PHP, determining if the page will be stored in the full page cache can be done via the layout instance using $this->layout->isCacheable()
.
The top-menu navigation block
One such cached block that is used on all pages is the top menu.
If you have custom uncached pages in your store, be sure to exclude it from the block_html
cache on those routes using.