Turn on CSP reporting without flooding your own API
Point Content-Security-Policy violation reports at a small collector that runs apart from your API. Start with the Report-Only header, and count reports by directive, blocked origin and page instead of storing each one.
If the reports go to a route on your main API instead, most of what you log there is noise.
Why the reports pile up
Every visitor’s browser sends a report for each violation on each page load. Block one third-party script on checkout, and every checkout visit sends a report.
Then there are extensions. Password managers, ad blockers and translators inject scripts and styles into the page, and a strict policy reports those too. Reports cut a non-HTTP URL down to its scheme, so these arrive with a blocked URL of just chrome-extension, moz-extension or safari-web-extension, and there’s nothing on your side to fix.
If the report URL is a route on your main API, all of those POSTs land next to real traffic. They count toward rate limits, fill the request logs and show up in any alert that watches call volume per route.
Two headers, two formats
The current way is the report-to directive plus a Reporting-Endpoints header that maps a name to a URL. The browser sends reports through the Reporting API as application/reports+json, each with "type": "csp-violation" and a body in camelCase (effectiveDirective, blockedURL, documentURL).
The older way is report-uri, which posts application/csp-report with a csp-report object in kebab-case (effective-directive, blocked-uri, document-uri).
MDN’s report-to page says browsers that support report-to ignore report-uri, and marks report-to as “Baseline 2026, newly available”, which leaves older browsers on report-uri. So send both for now, and make the collector read both:
Reporting-Endpoints: csp="https://csp-reports.example.com/r"
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' https://js.payments.example; report-uri https://csp-reports.example.com/r; report-to csp
The -Report-Only header reports violations without blocking anything, so it’s safe to deploy right away.
The collector
It runs on its own host or as an edge function, never as a route on the main API. It answers 204 straight away, reads both formats, skips extension reports and keeps counts:
// csp-collector.mjs: a small CSP report endpoint that runs apart from your API.
import { createServer } from "node:http";
// Reports cut non-HTTP(S) URLs down to the bare scheme ("chrome-extension"), so the colon is optional.
const EXTENSION = /^(chrome|moz|safari-web)-extension(:|$)/;
const CORS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Headers": "Content-Type",
};
const seen = new Map(); // "directive blocked page" -> count in this window
function normalize(r) {
// Reporting API (report-to): { type: "csp-violation", body: {...} }
if (r.type === "csp-violation") {
const b = r.body;
return { directive: b.effectiveDirective, blocked: b.blockedURL, page: b.documentURL, source: b.sourceFile };
}
// Legacy report-uri: { "csp-report": {...} }
const c = r["csp-report"];
if (c) return { directive: c["effective-directive"] ?? c["violated-directive"], blocked: c["blocked-uri"], page: c["document-uri"], source: c["source-file"] };
return null;
}
function keyOf(v) {
const page = URL.canParse(v.page) ? new URL(v.page).pathname : v.page;
const blocked = URL.canParse(v.blocked) ? new URL(v.blocked).origin : v.blocked;
return `${v.directive} ${blocked} ${page}`;
}
createServer((req, res) => {
// report-to deliveries are CORS requests with a non-simple Content-Type, so the browser asks first.
if (req.method === "OPTIONS") return res.writeHead(204, CORS).end();
if (req.method !== "POST") return res.writeHead(405).end();
let body = "";
req.on("data", (c) => { if ((body += c).length > 64_000) req.destroy(); });
req.on("end", () => {
res.writeHead(204, CORS).end();
let parsed;
try { parsed = JSON.parse(body); } catch { return; }
for (const r of [].concat(parsed)) {
const v = normalize(r);
if (!v || EXTENSION.test(v.blocked ?? "") || EXTENSION.test(v.source ?? "")) continue;
const k = keyOf(v);
seen.set(k, (seen.get(k) ?? 0) + 1);
}
});
}).listen(process.env.PORT ?? 8787);
setInterval(() => {
for (const [k, n] of seen) console.log(`${n}\t${k}`);
seen.clear();
}, Number(process.env.FLUSH_MS ?? 60_000));
I posted hand-built reports to it with curl: three in the Reporting API format for a blocked tracker on checkout, one for an extension script (blocked URL chrome-extension) and one legacy report for an image. The flush printed this (made-up hosts, real output):
3 script-src-elem https://cdn.tracker.example /checkout
1 img-src http://images.example /
No extension line, and the three checkout reports are one line with a 3.
Two details in there come from the specs. The Reporting API sends a JSON list of reports, while report-uri sends one object, hence [].concat(parsed). And it sends them in cors mode with an application/reports+json body, so a collector on another origin gets an OPTIONS preflight first. Answer it with the CORS headers, or the browser never sends the reports.
Keep the URLs short on purpose
keyOf keeps the page path and the blocked origin and throws away query strings. That’s partly to make the counts readable. It’s also because documentURL is the full page URL, and query strings carry things you don’t want sitting in a log: reset tokens, emails, order ids.
Rolling it out
- Ship
Content-Security-Policy-Report-Onlywith the policy you want, pointed at the collector. - Read the counts for a week. Lines from your own pages and your own origins are real gaps: allow the source or fix the inline script. Lines from origins you don’t recognize need a look before you allow anything: some are extensions the regex doesn’t catch, some are a third party loading another one.
- When the real lines stop, switch the header to
Content-Security-Policyand keepreport-uriandreport-toon it. Keep the collector running. It tells you when a deploy adds a script the policy doesn’t allow.
Put a rate limit in front of the collector too. A single page with a broken policy can send a report on every load, and you don’t want the collector backing up because of one page.