Reporting Content Security Policy Violations
Illustrate the setup for a Content Security Policy reporting mechanism using the report-uri directive in Next.js 14.
const reportCSPViolation = async (report) => {
const res = await fetch('/api/report-csp-violation', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(report['csp-report']),
});
if (res.ok) {
console.log('CSP violation reported successfully');
} else {
console.error('Failed to report CSP violation');
}
};
A JavaScript function to report Content Security Policy (CSP) violations. It takes a violation report object as an argument, formats the data, and sends it to a specified server-side API endpoint ('/api/report-csp-violation') using the fetch API.
document.addEventListener('DOMContentLoaded', () => {
document.addEventListener('securitypolicyviolation', (e) => {
reportCSPViolation({
'csp-report': {
'document-uri': e.documentURI,
'referrer': e.referrer,
'blocked-uri': e.blockedURI,
'violated-directive': e.violatedDirective,
'original-policy': e.originalPolicy,
},
});
});
});
An event listener is added to the DOMContentLoaded event. When the DOM is fully loaded, another listener is added to listen for securitypolicyviolation events. If such an event occurs, the reportCSPViolation function is called with the necessary event details to report the violation.
export async function getServerSideProps(context) {
// Define Content Security Policy
const csp = `default-src 'self'; script-src 'self'; style-src 'self'; report-uri /api/report-csp-violation`;
// Send CSP headers
context.res.setHeader('Content-Security-Policy', csp);
// ... other server-side logic ...
return {
props: {}, // your page props
};
}
In the context of a Next.js page, this server-side function, getServerSideProps, sets the Content Security Policy for that page. The CSP includes a `report-uri` directive that points to the server-side API endpoint which handles the violations. The CSP header is then set on the response, instructing the browser to enforce the specified policy.