0 day streak
javascript / intermediate
Snippet

Configuring Content Security Policy Headers

Setting a Content Security Policy (CSP) in next.config.js helps mitigate security risks like Cross-Site Scripting (XSS) by restricting where resources can be loaded from.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/** @type {import('next').NextConfig} */
const nextConfig = {
async headers() {
return [
{
source: '/(.*)',
headers: [
{
key: 'Content-Security-Policy',
value: "default-src 'self'; script-src 'self' 'unsafe-inline';",
},
],
},
];
},
};
module.exports = nextConfig;
nextjs
Breakdown
1
async headers() {
A configuration method in Next.js to define custom HTTP response headers for specific routes.
2
value: "default-src 'self'; ...",
The CSP policy string that restricts content loading to the origin domain ('self').