Security and hardening · Advanced · 26 min
Set a strict Content Security Policy with nonces
By Padding · Updated 18 Nov 2026
Node.js 26.13 (node:26) · Playwright 1.65.1 (Chromium) · nginx
You will serve a Node.js page under a nonce-based strict Content Security Policy, roll it out in report-only mode with your own report collector, fix the inline handler it flags, add Trusted Types and cover a static nginx site with hashes.
On this page
A Content Security Policy (CSP) tells the browser which scripts it may run. Its job is to catch the cross-site scripting bug you have not found yet: if an attacker's markup does reach your page, the browser refuses to run it.
Most policies in the wild do not manage that. They are allow-lists: script-src 'self' https://cdn.example.com https://analytics.example.net. Every allowed host is trusted with everything it serves, and large CDNs and analytics hosts serve JSONP endpoints and old library versions that run whatever code an attacker names in a URL. Google's 2016 study of real policies found most allow-list policies could be bypassed this way, and many also carried 'unsafe-inline', which lets any injected <script> run.
A strict policy trusts scripts instead of hosts. Each response gets a fresh random nonce; the server puts it in the header and on each <script> it wrote. Injected markup cannot know the nonce, so it does not run. 'strict-dynamic' then lets a trusted script load further scripts, so you do not have to list every bundle.
In this tutorial you build a small orders page in Node.js 26 with no framework, put it under a strict policy in report-only mode, collect the reports, fix what they show, switch to enforcement, add Trusted Types for DOM sinks in Chromium, and finish with hashes for a static site on nginx. Headless Chromium, driven by Playwright 1.65, shows you which scripts ran and which were blocked.
The page contains one deliberate XSS flaw so you can watch the policy stop it. Run it only on 127.0.0.1, and never try injected markup on sites you do not own.
Step 1 · Build the orders page
Create a project folder with a package.json that uses ES modules:
mkdir -p ~/csp-demo/public
cd ~/csp-demo
cat > package.json <<'JSON'
{
"name": "csp-demo",
"private": true,
"type": "module",
"scripts": {
"start": "node server.js"
}
}
JSONThe page template already gives each script tag it writes a nonce attribute. On its own the attribute does nothing; it only matters once a policy names the same value. The note parameter is printed without escaping on purpose: it stands in for the injection bug a real app might still have.
cd ~/csp-demo
cat > page.js <<'JS'
// Renders the orders page. `note` is printed without escaping ON PURPOSE:
// it stands in for an XSS bug you have not found yet. Never do this in real code.
export function renderPage({ nonce, note }) {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Orders</title>
<script nonce="${nonce}">
window.appConfig = { locale: 'en-NG', currency: 'NGN' }
</script>
<script nonce="${nonce}" src="/app.js" defer></script>
</head>
<body>
<h1>Orders</h1>
<p id="note">${note}</p>
<button id="refresh" type="button" onclick="document.querySelector('#status').textContent = 'Refreshed'">Refresh</button>
<p id="status">Not refreshed</p>
<p id="widget">Widget not loaded</p>
<ul id="orders"></ul>
</body>
</html>`
}
JSpublic/app.js lists two orders in naira and then loads a second script, the way an analytics snippet or chat widget would:
cd ~/csp-demo
cat > public/app.js <<'JS'
const orders = [
{ id: 'A-1001', item: 'Solar lamp', total: 18500 },
{ id: 'A-1002', item: 'Phone charger', total: 6200 },
]
const money = new Intl.NumberFormat(window.appConfig.locale, {
style: 'currency',
currency: window.appConfig.currency,
})
document.querySelector('#orders').innerHTML = orders
.map((o) => `<li>${o.id}: ${o.item}, ${money.format(o.total)}</li>`)
.join('')
const widget = document.createElement('script')
widget.src = '/widget.js'
document.head.append(widget)
JS
cat > public/widget.js <<'JS'
document.querySelector('#widget').textContent = 'Widget loaded'
JSThe server makes a new nonce for every page response and asks csp.js which headers to send. It also has a /csp-reports endpoint that writes violation reports to reports.ndjson; it stays idle until step 2. For now csp.js returns no headers:
cd ~/csp-demo
cat > csp.js <<'JS'
// Step 2 replaces this file with the real policy.
export function cspHeaders() {
return {}
}
JS
cat > server.js <<'JS'
import { createServer } from 'node:http'
import { randomBytes } from 'node:crypto'
import { readFile, appendFile } from 'node:fs/promises'
import { renderPage } from './page.js'
import { cspHeaders } from './csp.js'
const port = Number(process.env.PORT ?? 3100)
const origin = process.env.PUBLIC_ORIGIN ?? `http://127.0.0.1:${port}`
const scripts = new Set(['/app.js', '/widget.js'])
const reportsFile = new URL('./reports.ndjson', import.meta.url)
// Turns both report formats into one shape: the Reporting API
// (application/reports+json) and the older report-uri (application/csp-report).
function toEntries(type, data) {
const keep = (r) => ({
at: new Date().toISOString(),
disposition: r.disposition,
directive: r.directive,
blocked: r.blocked,
sample: String(r.sample ?? '').slice(0, 200),
page: r.page,
})
if (type.startsWith('application/reports+json') && Array.isArray(data)) {
return data
.filter((r) => r.type === 'csp-violation' && r.body)
.map(({ body: b }) => keep({ disposition: b.disposition, directive: b.effectiveDirective,
blocked: b.blockedURL, sample: b.sample, page: b.documentURL }))
}
if (type.startsWith('application/csp-report') && data?.['csp-report']) {
const r = data['csp-report']
return [keep({ disposition: r.disposition, directive: r['effective-directive'] ?? r['violated-directive'],
blocked: r['blocked-uri'], sample: r['script-sample'], page: r['document-uri'] })]
}
return []
}
const server = createServer(async (req, res) => {
const url = new URL(req.url, origin)
const reading = req.method === 'GET' || req.method === 'HEAD'
if (reading && url.pathname === '/') {
const nonce = randomBytes(16).toString('base64')
for (const [name, value] of Object.entries(cspHeaders(nonce, origin))) res.setHeader(name, value)
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.setHeader('Cache-Control', 'no-store')
res.end(renderPage({ nonce, note: url.searchParams.get('note') ?? 'No note' }))
return
}
if (reading && scripts.has(url.pathname)) {
res.setHeader('Content-Type', 'text/javascript; charset=utf-8')
res.end(await readFile(new URL(`./public${url.pathname}`, import.meta.url)))
return
}
if (req.method === 'POST' && url.pathname === '/csp-reports') {
let body = ''
for await (const chunk of req) {
body += chunk
if (body.length > 64 * 1024) return res.writeHead(413).end()
}
let data
try {
data = JSON.parse(body)
} catch {
return res.writeHead(400).end()
}
const entries = toEntries(req.headers['content-type'] ?? '', data)
if (entries.length) await appendFile(reportsFile, entries.map((e) => JSON.stringify(e) + '\n').join(''))
return res.writeHead(204).end()
}
res.writeHead(404).end('Not found')
})
server.listen(port, '127.0.0.1', () => console.log(`Orders on ${origin}`))
JSStart it in your second terminal:
cd ~/csp-demo
npm startCheck it worked
The terminal running the app prints Orders on http://127.0.0.1:3100. In your first terminal, fetch the page and its headers:
cd ~/csp-demo
curl -s http://127.0.0.1:3100/ | grep '<h1>'
curl -sI http://127.0.0.1:3100/ > headers.txt
if grep -qi '^content-security-policy' headers.txt; then echo "unexpected CSP header"; false; else echo "no CSP header yet"; fiYou see <h1>Orders</h1> and no CSP header yet. If you are working on a desktop machine, open http://127.0.0.1:3100/?note=<b>hello</b> in your browser: "hello" is bold, which shows the note goes into the page as markup. On a headless server, forward the port from your laptop first with ssh -L 3100:127.0.0.1:3100 you@your-server and open the same address in your laptop's browser.
Step 2 · Send a strict policy in report-only mode
Replace csp.js with the real policy. Two environment variables choose how strict to be, so you can roll the policy out without editing code: CSP_MODE is report-only or enforce, and CSP_TRUSTED_TYPES (used in step 6) is off, report or enforce.
cd ~/csp-demo
cat > csp.js <<'JS'
const mode = process.env.CSP_MODE ?? 'report-only'
const trustedTypes = process.env.CSP_TRUSTED_TYPES ?? 'off'
if (!['report-only', 'enforce'].includes(mode)) throw new Error(`Unknown CSP_MODE: ${mode}`)
if (!['off', 'report', 'enforce'].includes(trustedTypes)) throw new Error(`Unknown CSP_TRUSTED_TYPES: ${trustedTypes}`)
if (trustedTypes === 'report' && mode !== 'enforce') {
throw new Error('CSP_TRUSTED_TYPES=report needs CSP_MODE=enforce')
}
export function cspHeaders(nonce, origin) {
const reportUrl = `${origin}/csp-reports`
// Chromium only takes Reporting-Endpoints from an HTTPS page, so report-to
// is added only when the public origin is HTTPS.
const reportingApi = origin.startsWith('https://')
const reporting = [`report-uri ${reportUrl}`, ...(reportingApi ? ['report-to csp'] : [])]
const strict = [
// Modern browsers use the nonce and 'strict-dynamic' and ignore the last two;
// very old browsers fall back to them.
`script-src 'nonce-${nonce}' 'strict-dynamic' 'report-sample' 'unsafe-inline' https:`,
"object-src 'none'",
"base-uri 'none'",
]
const tt = ["require-trusted-types-for 'script'", 'trusted-types orders']
const main = [...strict, ...(trustedTypes === 'enforce' ? tt : []), ...reporting].join('; ')
const headers = {
[mode === 'enforce' ? 'Content-Security-Policy' : 'Content-Security-Policy-Report-Only']: main,
}
if (reportingApi) headers['Reporting-Endpoints'] = `csp="${reportUrl}"`
if (trustedTypes === 'report') {
headers['Content-Security-Policy-Report-Only'] = [...tt, ...reporting].join('; ')
}
return headers
}
JSWhat each part does:
'nonce-…'trusts only script tags carrying this response's nonce. Once a nonce is present, CSP Level 3 browsers ignore'unsafe-inline', so inline event handlers and injected<script>tags stop being allowed.'strict-dynamic'passes trust on: a script the nonce allowed may create more script elements and they run. Under it, host sources such ashttps:and'self'are ignored, which removes the allow-list weakness completely.'report-sample'asks the browser to include the first 40 characters of a blocked inline script in the report, so you can find it.object-src 'none'blocks plugins, an old way to run code that sidestepsscript-src.base-uri 'none'stops an injected<base href>from quietly pointing your relative script URLs, such as/app.js, at another server.report-urisends each violation to/csp-reportsasapplication/csp-report.report-to cspnames the endpoint in theReporting-Endpointsheader, the newer Reporting API. Browsers that support it ignorereport-uriwhen both are present. Chromium only acceptsReporting-Endpointsfrom an HTTPS page, socsp.jsadds the two only when the public origin starts withhttps://. Onhttp://127.0.0.1you getreport-urialone; behind HTTPS, start the app withPUBLIC_ORIGIN=https://your-domainand you get both.
A nonce only works if it is unpredictable and never reused. That is why the server makes 16 random bytes per response and sends Cache-Control: no-store: a CDN or service worker that caches the HTML would serve the same nonce to everyone.
Stop the app with Ctrl+C in the second terminal and start it in report-only mode:
CSP_MODE=report-only npm startCheck it worked
Save one response's headers and body, then compare the nonce in each:
cd ~/csp-demo
curl -s -D headers.txt -o page.html http://127.0.0.1:3100/
grep -i '^content-security-policy-report-only:' headers.txt
grep -o "nonce-[^']*" headers.txt
grep -o 'nonce="[^"]*"' page.htmlThe policy line starts script-src 'nonce- and ends with report-uri http://127.0.0.1:3100/csp-reports. The nonce after nonce- in the header is the same 24-character value as both nonce="…" attributes in the page. Now request the page twice and compare:
cd ~/csp-demo
first=$(curl -sI http://127.0.0.1:3100/ | grep -o "nonce-[^']*")
second=$(curl -sI http://127.0.0.1:3100/ | grep -o "nonce-[^']*")
echo "$first"
echo "$second"
test "$first" != "$second" && echo "nonces differ"Two different values print, followed by nonces differ.
To see the headers an HTTPS deployment gets, call cspHeaders with an HTTPS origin (orders.example.com stands in for your domain):
cd ~/csp-demo
node -e "import('./csp.js').then((m) => console.log(m.cspHeaders('example-nonce', 'https://orders.example.com')))"The output has a Reporting-Endpoints entry of csp="https://orders.example.com/csp-reports" and a policy ending report-uri https://orders.example.com/csp-reports; report-to csp.
Step 3 · Watch the policy in headless Chromium
Report-only mode blocks nothing. The browser runs the page as before and reports what the policy would have blocked. To see those reports, drive Chromium with Playwright. Install it and its browser:
cd ~/csp-demo
npm install --save-dev playwright@1.65.1
npx playwright install --with-deps chromiumcheck.mjs opens the page, records every securitypolicyviolation event the browser fires, clicks Refresh, and prints what happened. With --wait-for-reports it keeps the browser open until the collector has written a new report. report-uri reports usually arrive within a second; Reporting API reports on an HTTPS site are batched and can take a minute or more.
cd ~/csp-demo
cat > check.mjs <<'JS'
import { chromium } from 'playwright'
import { readFile } from 'node:fs/promises'
const base = process.env.BASE_URL ?? 'http://127.0.0.1:3100'
const waitForReports = process.argv.includes('--wait-for-reports')
const note = process.argv.slice(2).find((arg) => !arg.startsWith('--'))
const url = note ? `${base}/?note=${encodeURIComponent(note)}` : `${base}/`
const reportsFile = new URL('./reports.ndjson', import.meta.url)
async function countReports() {
try {
return (await readFile(reportsFile, 'utf8')).split('\n').filter(Boolean).length
} catch {
return 0
}
}
const before = await countReports()
const browser = await chromium.launch()
const page = await browser.newPage()
const errors = []
page.on('pageerror', (error) => errors.push(error.message))
await page.addInitScript(() => {
window.__violations = []
document.addEventListener('securitypolicyviolation', (e) => {
window.__violations.push([e.disposition, e.effectiveDirective, e.blockedURI, e.sample].join(' ').trim())
})
})
await page.goto(url)
await page.waitForLoadState('networkidle')
await page.click('#refresh')
await page.waitForTimeout(500)
const result = await page.evaluate(() => ({
title: document.title,
status: document.querySelector('#status').textContent,
widget: document.querySelector('#widget').textContent,
orders: document.querySelectorAll('#orders li').length,
violations: window.__violations,
}))
console.log(`page: ${url}`)
console.log(`title: ${result.title}`)
console.log(`status: ${result.status}`)
console.log(`widget: ${result.widget}`)
console.log(`orders: ${result.orders}`)
if (result.violations.length === 0) console.log('violations: none')
else console.log(`violations:\n${result.violations.map((v) => ` ${v}`).join('\n')}`)
for (const message of errors) console.log(`page error: ${message}`)
if (waitForReports) {
let received = 0
for (let i = 0; i < 90 && received === 0; i++) {
await new Promise((resolve) => setTimeout(resolve, 1000))
received = (await countReports()) - before
}
console.log(received ? `reports received: ${received}` : 'no reports received within 90 seconds')
if (!received) process.exitCode = 1
}
await browser.close()
JS
node check.mjs --wait-for-reports | tee /tmp/csp-check-1.txtLook at what the collector stored:
cd ~/csp-demo
cat reports.ndjson
grep -q '"directive":"script-src-attr"' reports.ndjson && echo "collector has the inline handler report"Now try the deliberate flaw with a harmless marker that only changes the page title:
cd ~/csp-demo
node check.mjs "<script>document.title='csp-marker'</script>" | tee /tmp/csp-check-2.txtCheck it worked
The first run prints status: Refreshed, widget: Widget loaded, orders: 2 and one violation line starting report script-src-attr inline, followed by the start of the onclick code. That is the inline event handler on the Refresh button: the policy would block it, but report-only let it run. The widget is not listed, because app.js carried the nonce and 'strict-dynamic' passed trust to the script it created. The run ends with reports received: 1 or more, and reports.ndjson holds a line with "disposition":"report" and "directive":"script-src-attr".
The marker run prints title: csp-marker and a line starting report script-src-elem inline: in report-only mode the injected script still runs. You will block it in step 5.
Reports are sent from your visitors' devices, on their data. The Reporting API batches them, and a clean policy sends none, but during a noisy roll-out cap what the collector accepts and turn reporting on for a sample of pages rather than every view, especially if many of your users are on prepaid mobile data.
Step 4 · Replace the inline event handler
A strict policy has no safe way to allow onclick="…" attributes, javascript: links or code strings passed to eval and new Function. Move that code into a script the nonce already trusts. Rewrite the template without the onclick attribute:
cd ~/csp-demo
cat > page.js <<'JS'
// Renders the orders page. `note` is printed without escaping ON PURPOSE:
// it stands in for an XSS bug you have not found yet. Never do this in real code.
export function renderPage({ nonce, note }) {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Orders</title>
<script nonce="${nonce}">
window.appConfig = { locale: 'en-NG', currency: 'NGN' }
</script>
<script nonce="${nonce}" src="/app.js" defer></script>
</head>
<body>
<h1>Orders</h1>
<p id="note">${note}</p>
<button id="refresh" type="button">Refresh</button>
<p id="status">Not refreshed</p>
<p id="widget">Widget not loaded</p>
<ul id="orders"></ul>
</body>
</html>`
}
JSAdd the click handler to public/app.js:
cd ~/csp-demo
cat > public/app.js <<'JS'
const orders = [
{ id: 'A-1001', item: 'Solar lamp', total: 18500 },
{ id: 'A-1002', item: 'Phone charger', total: 6200 },
]
const money = new Intl.NumberFormat(window.appConfig.locale, {
style: 'currency',
currency: window.appConfig.currency,
})
document.querySelector('#orders').innerHTML = orders
.map((o) => `<li>${o.id}: ${o.item}, ${money.format(o.total)}</li>`)
.join('')
document.querySelector('#refresh').addEventListener('click', () => {
document.querySelector('#status').textContent = 'Refreshed'
})
const widget = document.createElement('script')
widget.src = '/widget.js'
document.head.append(widget)
JSapp.js is read from disk on each request, but page.js is loaded once, so restart the app (Ctrl+C, then the same command) and clear the old reports:
CSP_MODE=report-only npm startcd ~/csp-demo
rm -f reports.ndjson
node check.mjs | tee /tmp/csp-check-3.txtCheck it worked
The output shows status: Refreshed and violations: none. The button still works, and the policy has nothing left to complain about. On a real site, leave report-only running for a few days and read reports.ndjson until only noise from browser extensions remains before you enforce.
Step 5 · Enforce the policy
Switch the header from Content-Security-Policy-Report-Only to Content-Security-Policy. Restart the app with:
CSP_MODE=enforce npm startConfirm the header name changed, then run the page check without and with the marker:
cd ~/csp-demo
curl -sI http://127.0.0.1:3100/ | grep -i '^content-security-policy'
node check.mjs | tee /tmp/csp-check-4.txt
node check.mjs "<script>document.title='csp-marker'</script>" | tee /tmp/csp-check-5.txtCheck it worked
curl prints a single Content-Security-Policy: line with no -Report-Only. The plain run shows violations: none, orders: 2 and widget: Widget loaded. The marker run shows title: Orders, not csp-marker, and a violation starting enforce script-src-elem inline: the injected script reached the page and the browser refused to run it.
The flaw is still there. The policy limits the damage; escaping the note, as in the output-encoding tutorial, removes it.
Step 6 · Lock down DOM sinks with Trusted Types
A nonce stops injected markup in the HTML, but not your own script writing an attacker's string into innerHTML or a script's src. Trusted Types closes that gap: with require-trusted-types-for 'script', those sinks refuse plain strings and only accept values produced by a policy you name. Chromium enforces it; browsers without support ignore the directive, so it adds protection without breaking them. Check MDN's compatibility table for the browsers your users have.
Roll it out the same way: keep the main policy enforced and send the Trusted Types directives in a separate report-only header. Restart with:
CSP_MODE=enforce CSP_TRUSTED_TYPES=report npm startcd ~/csp-demo
node check.mjs | tee /tmp/csp-check-6.txtYou see violations starting report require-trusted-types-for trusted-types-sink, something like one for the innerHTML assignment and one for the widget's src. Fix both in app.js. The orders do not need HTML at all, so build them with textContent. The widget URL goes through a policy called orders, the only name the trusted-types orders directive allows, and that policy accepts nothing but your own known script paths:
cd ~/csp-demo
cat > public/app.js <<'JS'
const orders = [
{ id: 'A-1001', item: 'Solar lamp', total: 18500 },
{ id: 'A-1002', item: 'Phone charger', total: 6200 },
]
const money = new Intl.NumberFormat(window.appConfig.locale, {
style: 'currency',
currency: window.appConfig.currency,
})
// No HTML needed: build elements and set text, which is not a Trusted Types sink.
const list = document.querySelector('#orders')
for (const o of orders) {
const li = document.createElement('li')
li.textContent = `${o.id}: ${o.item}, ${money.format(o.total)}`
list.append(li)
}
document.querySelector('#refresh').addEventListener('click', () => {
document.querySelector('#status').textContent = 'Refreshed'
})
// The one place a script URL is created. Anything not on the list throws.
const allowedScripts = new Set(['/widget.js'])
const policy = window.trustedTypes
? window.trustedTypes.createPolicy('orders', {
createScriptURL(value) {
const url = new URL(value, location.origin)
if (url.origin === location.origin && allowedScripts.has(url.pathname)) return url.href
throw new TypeError(`Script URL not allowed: ${value}`)
},
})
: { createScriptURL: (value) => value }
const widget = document.createElement('script')
widget.src = policy.createScriptURL('/widget.js')
document.head.append(widget)
JS
node check.mjs | tee /tmp/csp-check-7.txtWith no reports left, move Trusted Types into the enforced policy:
CSP_MODE=enforce CSP_TRUSTED_TYPES=enforce npm startcd ~/csp-demo
curl -sI http://127.0.0.1:3100/ | grep -i '^content-security-policy'
node check.mjs | tee /tmp/csp-check-8.txtCheck it worked
After the rewrite, the report-only run shows violations: none. With enforcement on, curl prints one Content-Security-Policy: line that now contains require-trusted-types-for 'script'; trusted-types orders, and the check still shows orders: 2, widget: Widget loaded and violations: none. From here, any new code that assigns a string to innerHTML or a script src throws in Chromium instead of quietly creating an injection point.
Stop the app with Ctrl+C.
Step 7 · Use hashes for a static site on nginx
Run this step on the same Ubuntu 26.04 machine as steps 1 to 6: it reuses ~/csp-demo, its Playwright install and Chromium. If you followed steps 1 to 6 on macOS, copy the ~/csp-demo folder to the server (for example scp -r ~/csp-demo you@your-server:~/), then on the server run cd ~/csp-demo && npm install && npx playwright install --with-deps chromium before you continue.
A static site served by nginx has no code running per request, so it cannot make a fresh nonce. Use a hash instead: the policy lists the SHA-256 of each inline script's exact text, and the browser runs only inline scripts that match. Keep the inline part to one small loader and let 'strict-dynamic' trust the files it loads.
Create the site:
mkdir -p ~/csp-demo/site
cd ~/csp-demo
cat > site/index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Static CSP demo</title>
<script>
const main = document.createElement('script')
main.src = '/main.js'
document.head.append(main)
</script>
</head>
<body>
<p id="out">Loader did not run</p>
</body>
</html>
HTML
cat > site/main.js <<'JS'
const show = () => {
document.querySelector('#out').textContent = 'Loaded by the hashed loader'
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', show)
else show()
JShash-inline.mjs prints the CSP hash source for every inline <script> (one with no attributes) in a file. The hash covers every character between the tags, including spaces and line breaks, so run it again after any edit:
cd ~/csp-demo
cat > hash-inline.mjs <<'JS'
import { readFile } from 'node:fs/promises'
import { createHash } from 'node:crypto'
const html = await readFile(process.argv[2], 'utf8')
for (const [, body] of html.matchAll(/<script>([\s\S]*?)<\/script>/g)) {
console.log(`'sha256-${createHash('sha256').update(body, 'utf8').digest('base64')}'`)
}
JS
node hash-inline.mjs site/index.htmlCopy the site into place and write an nginx server block with the hash in its policy. The heredoc is unquoted so the shell fills in $HASHES. By default nginx only inherits add_header lines from the outer level when a block has none of its own, so if you add headers inside a location, repeat the policy there (Nginx 1.29.3 and later can change this with add_header_inherit merge;, see /tutorials/add-security-headers-in-nginx):
cd ~/csp-demo
sudo install -d /var/www/csp-static
sudo cp site/index.html site/main.js /var/www/csp-static/
HASHES=$(node hash-inline.mjs site/index.html | tr '\n' ' ')
sudo tee /etc/nginx/conf.d/csp-static.conf > /dev/null <<EOF
server {
listen 127.0.0.1:8081;
root /var/www/csp-static;
index index.html;
add_header Content-Security-Policy "script-src ${HASHES}'strict-dynamic'; object-src 'none'; base-uri 'none'" always;
}
EOF
cat /etc/nginx/conf.d/csp-static.conf
sudo nginx -tsudo systemctl reload nginxCheck the header and the page in Chromium:
cd ~/csp-demo
curl -sI http://127.0.0.1:8081/ | grep -i '^content-security-policy:'
cat > static-check.mjs <<'JS'
import { chromium } from 'playwright'
const browser = await chromium.launch()
const page = await browser.newPage()
await page.addInitScript(() => {
window.__violations = []
document.addEventListener('securitypolicyviolation', (e) => {
window.__violations.push(`${e.disposition} ${e.effectiveDirective} ${e.blockedURI}`)
})
})
await page.goto('http://127.0.0.1:8081/')
await page.waitForLoadState('networkidle')
console.log(`out: ${await page.textContent('#out')}`)
const violations = await page.evaluate(() => window.__violations)
console.log(violations.length ? `violations:\n ${violations.join('\n ')}` : 'violations: none')
await browser.close()
JS
node static-check.mjs | tee /tmp/csp-static.txtCheck it worked
sudo nginx -t reports syntax is ok and test is successful. curl shows Content-Security-Policy: script-src 'sha256-…' 'strict-dynamic'; object-src 'none'; base-uri 'none', with the same hash hash-inline.mjs printed. The browser check prints out: Loaded by the hashed loader and violations: none: the loader matched its hash, and main.js ran because the loader created it. If you change a single character in the inline script and copy the file again without updating the header, the loader is blocked and the page keeps saying "Loader did not run". Make hashing part of your build so the header and the HTML never drift apart.
Step 8 · Clean up
These commands delete the demo site, its nginx server block and the ~/csp-demo folder with its reports. Check you have copied anything you want to keep, then make sure the Node.js app is stopped (Ctrl+C in the second terminal) and run:
sudo rm /etc/nginx/conf.d/csp-static.conf
sudo nginx -tsudo systemctl reload nginxnpx playwright uninstall removes the Chromium build this project downloaded; skip it if other projects on this machine use the same Playwright version.
sudo rm -rf /var/www/csp-static
cd ~/csp-demo
npx playwright uninstall
cd ~
rm -rf ~/csp-demoCheck it worked
Both of these print their "removed" message:
if curl -fs -o /dev/null http://127.0.0.1:8081/; then echo "static site still served"; false; else echo "static site removed"; fi
if [ -d ~/csp-demo ]; then echo "csp-demo still there"; false; else echo "csp-demo removed"; fiNext steps
- Fix the injection itself with escaping by default, and see where a policy fits as a backstop: /tutorials/stop-xss-with-output-encoding-and-a-content-security-policy
- Add the rest of the security headers to a site served by nginx: /tutorials/add-security-headers-in-nginx
- Load modules in the browser without a bundler, and keep them working under a strict policy: /tutorials/load-browser-modules-without-a-bundler-using-import-maps
Related tutorials
- Write custom Fail2ban jails and filters for your own appsYou will have Fail2ban 1.1 banning repeated failed sign-ins to your own app and to an nginx basic-auth area, with filters you tested against sample logs, your own addresses allow-listed, and longer bans for repeat offenders.
- Validate file uploads before you store or serve themYou will take a FastAPI image upload route that trusts everything the browser sends, prove its flaws with pytest, and rebuild it with size limits, type checks from the file's own bytes, Pillow re-encoding, random storage names and safe download headers.
- Use SSH certificates instead of copying keys to every serverYou will run a small SSH certificate authority with ssh-keygen, log in to an Ubuntu 26.04 server with an eight-hour user certificate, give the server a host certificate so clients stop asking about fingerprints, and revoke a certificate the server then refuses.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials