Skip to content
jshacks.dev
Security

Report CSP violations to an endpoint

Receive Content Security Policy violation reports at an endpoint with the report-to and report-uri directives, and parse what the browser sends.

1 min read
Summarize in AI

A new policy will break something you forgot. Collect the browser's reports first, in report-only mode, and enforce when the noise stops.

http
Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report
reports.jsJavaScript
app.post('/csp-report', express.json({ type: ['application/csp-report', 'application/json'] }), (req, res) => {
  const report = req.body['csp-report'] ?? {};
  console.log(report['violated-directive'], report['blocked-uri']);
  res.sendStatus(204);
});
Text
script-src-elem https://cdn.example.net/widget.js

With report-uri the browser POSTs a JSON body with a csp-report object that holds violated-directive, blocked-uri and document-uri. Always answer 204 and keep the handler cheap, because extensions generate many harmless reports. The newer report-to directive sends application/reports+json batches and needs a Reporting-Endpoints header. See the MDN CSP report reference.

report-uri is deprecated in favour of report-to, but browsers still support it and Firefox needs it. Rate limit the endpoint, since anyone can post to it.

Share

More snippets

Security

Sandbox untrusted code in a worker

Run untrusted code in a worker thread with limited memory and a kill timeout, and know what a worker does not isolate.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.