CSP nonce for {{ no_cache }} javascript #8513
-
Using 4.13.2, I have full caching enabled and spatie/laravel-csp configured to add CSP headers. I have created a tag {{ nonce }} that I can add in any templates and Vite is successfully generating a nonce for all styles. This is working really well except for the "small snippet of JavaScript will be injected just before the closing tag" that appears when using the {{ no_cache}} tag. Can someone point me in the direction of how I can add a nonce to this snippet of javascript? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Answering my own question in case someone is ever looking for this. In the /*
|--------------------------------------------------------------------------
| Replacers
|--------------------------------------------------------------------------
|
| Here you may define replacers that dynamically replace content within
| the response. Each replacer must implement the Replacer interface.
|
*/
'replacers' => [
\Statamic\StaticCaching\Replacers\CsrfTokenReplacer::class,
//\Statamic\StaticCaching\Replacers\NoCacheReplacer::class,
\App\Support\MyNoCacheReplacer::class,
], In your custom class you can add the generated CSP nonce to the script in the private function modifyFullMeasureResponse(Response $response)
{
$cacher = app(Cacher::class);
if (! $cacher instanceof FileCacher) {
return;
}
$contents = $response->getContent();
if ($cacher->shouldOutputJs()) {
$js = $cacher->getNocacheJs();
$contents = str_replace('</body>', '<script nonce="'.app('csp-nonce').'" type="text/javascript">'.$js.'</script></body>', $contents);
}
$contents = str_replace('NOCACHE_PLACEHOLDER', $cacher->getNocachePlaceholder(), $contents);
$response->setContent($contents);
} |
Beta Was this translation helpful? Give feedback.
Answering my own question in case someone is ever looking for this.
In the
/config/statamic/static_caching.php
file there is a 'replacers' section where you can add your own class.