如何在 Next.js 中配置 Content-Security-Policy(CSP)头?
解读
该问题考察候选人对Next.js中HTTP安全头配置的理解,特别是Content-Security-Policy(CSP)的实现方式。CSP是防御XSS、数据注入等攻击的核心机制,需结合Next.js的框架特性(如SSR/SSG)和实际业务场景(如第三方资源调用)进行配置。在中文开发场景中,还需注意国内网络环境下资源加载的合规性要求。
知识点
- Next.js中CSP配置的三种主要方式:next.config.js、中间件、自定义头
- CSP头核心指令:script-src、style-src、img-src、connect-src等
- 静态资源加载策略:使用nonce、hash、unsafe-inline等关键字的合理配置
- SSR/SSG模式下的CSP差异:动态内容与静态内容的策略适配
- 安全与功能的平衡:避免过度限制导致页面异常
答案
在Next.js中配置CSP需通过以下步骤实现:
1. 基础配置(next.config.js)
// next.config.js
module.exports = {
webpack: (config, { isServer }) => {
if (!isServer) {
config.headers = {
'Content-Security-Policy': [
"default-src 'self'",
"script-src 'self' https://example.com:443",
"style-src 'self' https://example.com:443",
"img-src 'self' data: https://example.com:443",
"connect-src 'self' https://example.com:443",
"frame-src 'none'"
].join('; ')
}
}
return config
}
}
2. 中间件动态配置
// middleware.js
export const config = {
matcher: '/:path*',
};
export function middleware(req, res) {
res.setHeader('Content-Security-Policy',
"script-src 'self' https://example.com:443; style-src 'self' https://example.com:443; img-src 'self' data: https://example.com:443");
return NextResponse.next();
}
3. 自定义头配置(适用于API路由)
// pages/api/example.js
export default function handler(req, res) {
res.setHeader('Content-Security-Policy',
"script-src 'self' https://example.com:443; style-src 'self' https://example.com:443");
res.status(200).json({ message: 'CSP configured' });
}
配置时需注意:
- 使用
'self'限制资源来源 - 通过
unsafe-inline允许内联脚本(需谨慎使用) - 对第三方资源(如CDN、统计代码)需明确指定域名
- 在SSG模式下需确保静态资源路径匹配
- 使用
nonce或hash实现动态脚本加载时,需配合Webpack插件生成对应值
拓展思考
在中文开发场景中,需额外注意:
- 国内CDN资源(如阿里云、腾讯云)的域名需添加到CSP策略中
- 对于需要加载的本地资源(如
/public目录下的文件),应使用'self'或绝对路径 - 若使用
unsafe-inline,需配合report-uri指令上报违规行为 - 在SSR模式下,需确保CSP头在服务器端渲染时正确注入
- 对于国际化站点,需通过
connect-src配置多语言服务端地址 - 使用
img-src时,需考虑数据URI编码的兼容性问题 - 配置完成后需通过
curl -I [url]验证头是否正确发送 - 在开发阶段建议使用
report-uri收集违规报告,逐步优化策略