Skip to content

SRI for Statically Generated Sites

SRI is enabled by default for statically generated sites. This means that if it encounters JavaScript scripts or CSS stylesheets then it will automatically calculate their respective SRI hashes and set them into the integrity attribute of <script>, <style> and <link> tags.

Here you can see some examples of how code is transformed by Astro-Shield.

It will transform this

<script>console.log("Hello World!")</script>

into

<script integrity="sha256-TWupyvVdPa1DyFqLnQMqRpuUWdS3nKPnz70IcS/1o3Q=">console.log("Hello World!")</script>

Generating SRI hashes module for external scripts

In some cases, you may need some external scripts to access the generated SRI hashes (e.g. to configure the headers of a CDN). You can do this by setting the sri.hashesModule property with the path of the module that will export the generated hashes.

Example:

import { resolve } from 'node:path'
import { defineConfig } from 'astro/config'
import { shield } from '@kindspells/astro-shield'
const rootDir = new URL('.', import.meta.url).pathname
const modulePath = resolve(rootDir, 'src', 'generated', 'sriHashes.mjs')
export default defineConfig({
integrations: [
shield({
sri: { hashesModule: modulePath },
}),
],
})

Once you run astro build, the generated module will look like this:

// Do not edit this file manually
export const inlineScriptHashes = /** @type {string[]} */ ([])
export const inlineStyleHashes = /** @type {string[]} */ ([
'sha256-VC84dQdO3Mo7nZIRaNTJgrqPQ0foHI8gdp/DS+e9/lk=',
])
export const extScriptHashes = /** @type {string[]} */ ([
'sha256-+aSouJX5t2z1jleTbCvA9DS7+ag/F4e4ZpB/adun4Sg=',
])
export const extStyleHashes = /** @type {string[]} */ ([
'sha256-iwd3GNfA+kImEozakD3ZZQSZ8VVb3MFBOhJH6dEMnDE=',
])
export const perPageSriHashes =
/** @type {Record<string, { scripts: string[]; styles: string [] }>} */ ({
'index.html': {
scripts: [
'sha256-+aSouJX5t2z1jleTbCvA9DS7+ag/F4e4ZpB/adun4Sg=',
],
styles: [
'sha256-VC84dQdO3Mo7nZIRaNTJgrqPQ0foHI8gdp/DS+e9/lk='
],
},
'about.html': {
scripts: [
'sha256-+aSouJX5t2z1jleTbCvA9DS7+ag/F4e4ZpB/adun4Sg=',
],
styles: [
'sha256-iwd3GNfA+kImEozakD3ZZQSZ8VVb3MFBOhJH6dEMnDE=',
],
},
})
export const perResourceSriHashes = {
scripts: /** @type {Record<string,string>} */ ({
'/code.js': 'sha256-+aSouJX5t2z1jleTbCvA9DS7+ag/F4e4ZpB/adun4Sg=',
}),
styles: /** @type {Record<string,string>} */ ({
'/_astro/index.BA1ZV6fH.css':
'sha256-iwd3GNfA+kImEozakD3ZZQSZ8VVb3MFBOhJH6dEMnDE=',
}),
}

Disabling SRI for Statically Generated Sites

If you want to disable SRI for statically generated sites, you can do so by setting the sri.enableStatic option to false in your Astro config file.

import { defineConfig } from 'astro/config'
import { shield } from '@kindspells/astro-shield'
export default defineConfig({
integrations: [
shield({
sri: { enableStatic: false },
}),
],
})