Next.js › Security Best Practices in Next.js
How do you set security related HTTP headers, such as Content Security Policy, in a Next.js application?
IntermediateAnswer
You add a headers function inside your next.config.js file, defining custom response headers like Content-Security-Policy or X-Frame-Options that apply across your application, helping protect against attacks like clickjacking and restricting which sources of content the browser is allowed to load.
// next.config.js
module.exports = {
async headers() {
return [
{
source: '/(.*)',
headers: [
{ key: 'X-Frame-Options', value: 'DENY' },
{ key: 'Content-Security-Policy', value: "default-src 'self'" }
]
}
];
}
};Real-world example A banking application adds strict security headers across its entire site, preventing it from being embedded in a hidden frame on a malicious website that could trick users into clicking something unintended.