How do you set security related HTTP headers, such as Content Security Policy, in a Next.js application?
Short answer
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…
Advertisement
AModel answer
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.
Likely follow-ups
- What does the X-Frame-Options header actually protect against?
- How restrictive should a Content Security Policy be for a typical application?
Related topics