-
Notifications
You must be signed in to change notification settings - Fork 265
Add security headers to Next.js config #1338
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
✅ Deploy Preview for docs-optimism ready!Built without sensitive environment variables
To edit notification comments on pull requests, go to your Netlify site configuration. |
📝 WalkthroughWalkthroughThe changes introduce a new asynchronous function named Sequence Diagram(s)sequenceDiagram
participant Client
participant NextJS_Server as "Next.js Server"
participant Config_Module as "Configuration Module"
Client->>NextJS_Server: Send HTTP request
NextJS_Server->>Config_Module: Call async headers()
Config_Module-->>NextJS_Server: Return header configuration array
NextJS_Server->>Client: Respond with custom headers
Suggested reviewers
✨ Finishing Touches
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (1)
next.config.mjs (1)
25-43
: Consider adding additional security headers for comprehensive protection.While the current headers provide good security, consider adding these additional headers for enhanced protection:
- Content-Security-Policy: To prevent XSS attacks
- Permissions-Policy: To control browser features
- Referrer-Policy: To control referrer information
Here's how to add these headers:
headers: [ // ... existing headers ... + { + key: 'Content-Security-Policy', + value: "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';" + }, + { + key: 'Permissions-Policy', + value: 'camera=(), microphone=(), geolocation=()' + }, + { + key: 'Referrer-Policy', + value: 'strict-origin-when-cross-origin' + } ],
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
next.config.mjs
(1 hunks)
🔇 Additional comments (2)
next.config.mjs (2)
21-25
: LGTM! Well-structured header configuration.The implementation follows Next.js best practices with proper async function declaration and applies headers globally using the correct source pattern.
31-33
: Consider strengthening HSTS configuration.While the current HSTS configuration is good, you can enhance it by adding the
preload
directive. This will allow the domain to be included in browsers' HSTS preload lists.{ key: 'Strict-Transport-Security', - value: 'max-age=31536000; includeSubDomains' + value: 'max-age=31536000; includeSubDomains; preload' }Note: Before adding
preload
, ensure you're prepared to maintain HTTPS for the entire domain and all subdomains indefinitely, as it's difficult to remove once set.✅ Verification successful
🌐 Web query:
What are the implications of enabling HSTS preload?
💡 Result:
Enabling HSTS preload enhances security but introduces significant operational commitments and risks. Here's a breakdown of the key implications: ## Security Benefits - **Protection against SSL stripping**: Preloading prevents man-in-the-middle attacks that exploit insecure initial HTTP connections by enforcing HTTPS from the first visit[2][5][8]. - **Eliminates accidental HTTP connections**: Browsers automatically redirect HTTP requests to HTTPS, even for typos or outdated links[2][3]. - **Improved user experience**: Seamless HTTPS enforcement avoids certificate warnings on first visits[2][5]. ## Operational Challenges - **Irreversible long-term commitment**: Once added to browser preload lists (e.g., Chrome’s HSTS list), removal can take months to propagate across browser versions[1][9]. - **Subdomain management**: All subdomains must support HTTPS indefinitely, including internal/non-public ones[7][9]. Example header requiring this: ```http Strict-Transport-Security: max-age=31536000; includeSubDomains; preload ``` Subdomains with broken HTTPS implementations will become inaccessible[1][7]. ## Maintenance Risks - **Inflexible policy adjustments**: The `max-age` value (typically 1 year) cannot be reduced retroactively – changes only take effect after expiration[1][7]. - **Certificate strictness**: Browsers block access if certificates expire or have errors, with no user override option[8][10]. ## Implementation Requirements 1. Full HTTPS coverage for all subdomains[7][8] 2. Valid SSL/TLS certificates without errors[7] 3. Permanent HTTP-to-HTTPS redirects on port 80[7] 4. Gradual `max-age` ramp-up before preloading (e.g., 5min → 1 week → 1 month)[7] ## Strategic Considerations - Preloading is recommended only for high-value targets where security outweighs maintenance costs[4][9]. - Alternatives like browser HTTPS-only modes provide partial protection without permanent commitments[4]. Enabling HSTS preload creates robust security but demands flawless HTTPS implementation across all infrastructure components and acceptance of reduced operational flexibility. Organizations should thoroughly audit subdomains and certificate management before submission[7][9]. Citations: - 1: https://www.techtarget.com/searchsecurity/answer/Why-is-preloading-HTTP-Strict-Transport-Security-risky - 2: https://sslinsights.com/what-is-the-hsts-preload-list-for-chrome/ - 3: https://pcicompliancehub.com/role-of-hsts-in-web-security/ - 4: https://blog.apnic.net/2023/07/26/hsts-preload-adoption-and-challenges/ - 5: https://www.splunk.com/en_us/blog/learn/hsts-http-strict-transport-security.html - 6: https://www.acunetix.com/blog/articles/what-is-hsts-why-use-it/ - 7: https://hstspreload.org - 8: https://www.ssl2buy.com/wiki/http-strict-transport-security-hsts-better-security-for-applications - 9: https://qwiet.ai/understanding-and-implementing-https-strict-transport-security-hsts/ - 10: https://https.cio.gov/hsts/
Strengthen HSTS with the "preload" Directive
The "preload" directive enhances security by ensuring browsers enforce HTTPS from the very first connection. However, enabling it commits you to full HTTPS support on all subdomains indefinitely, as removal from preload lists can take months to propagate.
• Adding "preload" is beneficial if you’re confident that every subdomain supports HTTPS and remains error-free.
• Ensure that your SSL/TLS certificates, HTTP-to-HTTPS redirection, and maintenance processes are robust before committing.With these implications in mind, the suggested change is valid and aligns with security best practices if operational readiness has been confirmed.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (1)
next.config.mjs (1)
25-38
: Consider adding Content-Security-Policy header.While not mentioned in the PR objectives, consider adding a Content-Security-Policy (CSP) header to provide an additional layer of security against XSS attacks.
Example addition:
headers: [ { key: 'X-DNS-Prefetch-Control', value: 'on' }, { key: 'Strict-Transport-Security', value: 'max-age=31536000; includeSubDomains; preload' }, { key: 'X-Content-Type-Options', value: 'nosniff' }, + { + key: 'Content-Security-Policy', + value: "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';" + } ],Note: The CSP value should be customized based on your application's specific needs.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
next.config.mjs
(1 hunks)
🔇 Additional comments (1)
next.config.mjs (1)
21-25
: LGTM! Well-structured headers configuration.The implementation follows Next.js best practices with an async function and applies headers site-wide using the correct source pattern.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
next.config.mjs
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
- GitHub Check: Redirect rules - docs-optimism
- GitHub Check: Header rules - docs-optimism
- GitHub Check: Pages changed - docs-optimism
🔇 Additional comments (1)
next.config.mjs (1)
21-25
: LGTM! Well-structured headers configuration.The implementation follows Next.js best practices with proper async function structure and comprehensive path coverage.
{ | ||
key: 'X-DNS-Prefetch-Control', | ||
value: 'on' | ||
}, | ||
{ | ||
key: 'Strict-Transport-Security', | ||
value: 'max-age=31536000; includeSubDomains; preload' | ||
}, | ||
{ | ||
key: 'X-Content-Type-Options', | ||
value: 'nosniff' | ||
}, | ||
{ | ||
key: 'X-Frame-Options', | ||
value: 'DENY' | ||
} | ||
], |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Consider adding additional security headers for enhanced protection.
While the current implementation covers essential security headers, consider adding these additional headers for comprehensive security:
headers: [
{
key: 'X-DNS-Prefetch-Control',
value: 'on'
},
{
key: 'Strict-Transport-Security',
value: 'max-age=31536000; includeSubDomains; preload'
},
{
key: 'X-Content-Type-Options',
value: 'nosniff'
},
{
key: 'X-Frame-Options',
value: 'DENY'
},
+ {
+ key: 'Content-Security-Policy',
+ value: "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';"
+ },
+ {
+ key: 'Referrer-Policy',
+ value: 'strict-origin-when-cross-origin'
+ },
+ {
+ key: 'Permissions-Policy',
+ value: 'camera=(), microphone=(), geolocation=()'
+ }
],
🌐 Web query:
What are the recommended security headers for Next.js applications?
💡 Result:
Next.js applications require robust security headers to mitigate common web vulnerabilities like cross-site scripting (XSS), clickjacking, and data leaks. Based on best practices from security experts and Next.js documentation[1][2][3][6], here are the essential security headers:
Core Security Headers
-
Strict-Transport-Security
(HSTS)
Enforces HTTPS-only connections with:
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
- Prevents SSL-stripping attacks[2][6]
- Automatically added by Vercel deployments[6]
-
Content-Security-Policy
(CSP)
Restricts content sources to prevent XSS:default-src 'self'; script-src 'self' https://trusted.cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:;
- Start with restrictive policies (
default-src 'self'
) and gradually expand[1][7] - Use tools like Google's CSP Evaluator to validate[1]
- Start with restrictive policies (
-
X-Content-Type-Options
Blocks MIME-type sniffing:
X-Content-Type-Options: nosniff
- Prevents browsers from misinterpreting file types[2][3]
-
X-Frame-Options
Mitigates clickjacking via:
X-Frame-Options: DENY
- Modern alternative: Use CSP's
frame-ancestors
directive[1]
- Modern alternative: Use CSP's
Additional Protections
-
Referrer-Policy
Controls referrer data leakage:
Referrer-Policy: origin-when-cross-origin
[3][5] -
Permissions-Policy
Restricts browser features:
Permissions-Policy: camera=(), geolocation=(), microphone=()
- Disables sensitive APIs by default[3][5]
-
Security Header Tools
Tool Purpose Nosecone Type-safe header configuration next-secure-headers Simplified setup Helmet General Node.js apps[1][4]
Implementation Guide
Configure via next.config.js
:
module.exports = {
async headers() {
return [
{
source: "/(.*)",
headers: [
{ key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" },
{ key: "X-Content-Type-Options", value: "nosniff" },
{ key: "X-Frame-Options", value: "DENY" }
]
}
];
}
};
For complex CSP configurations, use middleware with libraries like Nosecone or next-secure-headers[1][4].
Key Considerations
- Avoid deprecated headers like
X-XSS-Protection
[1] - Use
server-only
package to prevent server code leakage[1] - Never expose secrets via
NEXT_PUBLIC_
environment variables[1] - Validate headers using SecurityHeaders.com scanner[5]
These measures create a defense-in-depth strategy while maintaining compatibility with Next.js features like Static Site Generation and Server Components[7].
Citations:
- 1: https://blog.arcjet.com/next-js-security-checklist/
- 2: https://alerty.ai/blog/nextjs-security
- 3: https://blog.logrocket.com/using-next-js-security-headers/
- 4: https://github.com/jagaapple/next-secure-headers
- 5: https://alvinwanjala.com/blog/adding-security-headers-nextjs/
- 6: https://nextjs.org/docs/pages/api-reference/config/next-config-js/headers
- 7: https://nextjs.org/docs/app/building-your-application/configuring/content-security-policy
Enhanced Security Headers – Actionable Improvement Required
The current code correctly implements the core security headers. However, based on best practices for Next.js applications, you should consider adding additional headers to further harden security. For example, supplementing the existing configuration with headers such as Content-Security-Policy, Referrer-Policy, and Permissions-Policy can help mitigate risks like XSS, clickjacking, and data leakage. (Note: Some sources recommend a higher HSTS max-age value—ensure this aligns with your overall security strategy.)
Key locations for attention:
- File:
next.config.mjs
- Lines: 26-42 (the header configuration section)
Suggested diff:
headers: [
{
key: 'X-DNS-Prefetch-Control',
value: 'on'
},
{
key: 'Strict-Transport-Security',
- value: 'max-age=31536000; includeSubDomains; preload'
+ value: 'max-age=31536000; includeSubDomains; preload'
},
{
key: 'X-Content-Type-Options',
value: 'nosniff'
},
{
key: 'X-Frame-Options',
value: 'DENY'
},
+ {
+ key: 'Content-Security-Policy',
+ value: "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';"
+ },
+ {
+ key: 'Referrer-Policy',
+ value: 'strict-origin-when-cross-origin'
+ },
+ {
+ key: 'Permissions-Policy',
+ value: 'camera=(), microphone=(), geolocation=()'
+ }
],
Please review and consider incorporating these additional headers to ensure a more robust security posture.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
{ | |
key: 'X-DNS-Prefetch-Control', | |
value: 'on' | |
}, | |
{ | |
key: 'Strict-Transport-Security', | |
value: 'max-age=31536000; includeSubDomains; preload' | |
}, | |
{ | |
key: 'X-Content-Type-Options', | |
value: 'nosniff' | |
}, | |
{ | |
key: 'X-Frame-Options', | |
value: 'DENY' | |
} | |
], | |
{ | |
key: 'X-DNS-Prefetch-Control', | |
value: 'on' | |
}, | |
{ | |
key: 'Strict-Transport-Security', | |
value: 'max-age=31536000; includeSubDomains; preload' | |
}, | |
{ | |
key: 'X-Content-Type-Options', | |
value: 'nosniff' | |
}, | |
{ | |
key: 'X-Frame-Options', | |
value: 'DENY' | |
}, | |
{ | |
key: 'Content-Security-Policy', | |
value: "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';" | |
}, | |
{ | |
key: 'Referrer-Policy', | |
value: 'strict-origin-when-cross-origin' | |
}, | |
{ | |
key: 'Permissions-Policy', | |
value: 'camera=(), microphone=(), geolocation=()' | |
} | |
], |
Added essential security headers to enhance site protection:
These changes follow security best practices and improve the site's security posture without affecting existing functionality.