Configuration Methods
Configuring Content Security Policy (CSP) in Next.js can be achieved through two primary methods: one involves setting custom HTTP headers in the next.config.js file, and the other involves dynamically setting the CSP header in the _document.js file for pages.
Method One: Using next.config.js to Configure CSP
You can utilize the headers() function in the next.config.js file to add or modify HTTP headers, including the CSP header. This approach offers centralized management and easier maintenance. However, it applies to all pages and may lack flexibility.
javascript// next.config.js module.exports = { async headers() { return [ { // Applies to all URL paths source: '/(.*)', headers: [ { key: 'Content-Security-Policy', value: "default-src 'self'; img-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://trustedscripts.example.com; style-src 'self' https://trustedstyles.example.com;", }, ], }, ]; }, };
Method Two: Dynamically Setting CSP in _document.js
If you require different CSP policies for various pages, you can dynamically set CSP in the _document.js file. This method enables customization based on specific page requirements.
javascript// pages/_document.js import Document, { Html, Head, Main, NextScript } from 'next/document'; class MyDocument extends Document { render() { return ( <Html> <Head> <meta httpEquiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://trustedscripts.example.com; style-src 'self' https://trustedstyles.example.com;" /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); } } export default MyDocument;
Summary
The approach to configuring CSP depends on your specific needs. If your security policy can be uniformly applied across all pages, configure it in next.config.js for simplicity and ease of maintenance. If you need different configurations for various pages or components, dynamically set it in _document.js. Each method has its own applicable scenarios and advantages, and selecting the appropriate configuration can effectively enhance application security.