Netlify 07 ๐ Custom Headers & Security โ Configuring _headers, CSP, CORS, and basic authentication
Security headers are the silent guardians of your web application. They are instructions sent by the server (Netlify) to the browser, defining how the site should behave in terms of safety, privacy, and data transfer. While often overlooked, configuring these correctly is the difference between a hardened, professional-grade application and one vulnerable to Cross-Site Scripting (XSS), Clickjacking, or unauthorized asset loading.
Netlify provides a powerful file-based configuration system through the _headers file, allowing you to define these security policies alongside your source code. Beyond standard security headers, this file also manages Cross-Origin Resource Sharing (CORS) for your APIs and basic authentication for private site environments. By defining these at the edge, you ensure that every requestโregardless of whether it hits a static file or a dynamic functionโis secured before the browser even parses the content.
This chapter details the syntax of the _headers file, the critical security headers you should be using in production, and how to implement access control using basic authentication for staging or password-protected deployments. We will walk through the configuration of Content-Security-Policy (CSP) to block malicious scripts and CORS rules to control how external domains interact with your resources.
Key point: HTTP headers are applied to the response before it reaches the browser; the _headers file provides a declarative way to secure your entire site from the root, ensuring consistent security posture across every page and asset.
Why X exists
The XSS/Clickjacking problem. Browsers are trusting by default. If your site doesn’t tell the browser “don’t let other sites embed me in an iframe” or “only run scripts from these domains,” attackers can hijack your page layout or execute malicious code in your users’ browsers. Security headers exist to explicitly restrict these browser capabilities.
The CORS vulnerability. When your frontend makes requests to a different domain, browsers enforce Cross-Origin Resource Sharing (CORS) policies. Without proper header configuration, the browser blocks these requests. Headers provide the “permission slip” for cross-domain interactions.
The staging access control requirement. Sometimes, you need to share a draft of your site with a client or team member, but you don’t want the public to see it. While Netlify has authentication tools, a simple layer of Basic Authentication via headers can be a lightweight way to gate access to early-stage deployments.
The “Infrastructure-as-Code” need. Configuring headers in a GUI dashboard is a manual, error-prone task that can’t be audited in Git. The _headers file allows security policies to be versioned, reviewed, and deployed as part of your standard pull request workflow, ensuring the security of your app evolves with your code.
The trade-off. The trade-off is the risk of “breaking the site.” A too-restrictive Content-Security-Policy can accidentally block your own legitimate scripts, fonts, and images. Because these headers are enforced by the browser, a misconfiguration can result in a completely unusable site until a new deployment overrides the faulty header.
a. Essential Security Headers
The _headers file uses a simple syntax: the path or wildcard path, followed by a list of header key-value pairs. Applying headers to /* ensures they are inherited by every single page, image, and script on your site.
# _headers
/*
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
Referrer-Policy: strict-origin-when-cross-origin
- X-Frame-Options: DENY: Prevents your site from being loaded in an iframe, stopping clickjacking attacks.
- X-Content-Type-Options: nosniff: Prevents the browser from “sniffing” the MIME type, which can be exploited to execute malicious files.
- HSTS (Strict-Transport-Security): Forces the browser to connect to your site only via HTTPS, preventing downgrade attacks.
b. Content-Security-Policy (CSP) and CORS
A Content-Security-Policy (CSP) is the single most effective way to prevent XSS. It defines a “whitelist” of sources from which scripts, styles, and images can be loaded. If an attacker manages to inject a <script> tag, the browser will check it against your CSP and block it if it isn’t from a trusted domain.
# Strict CSP Example
/*
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com; object-src 'none';
CORS, conversely, is for incoming requests. If your site is hosted at myapp.com and you want api.myapp.com to be able to read its resources, you must configure the Access-Control-Allow-Origin header.
# Enable CORS for API routes
/api/*
Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Methods: GET, POST, OPTIONS
c. Basic Authentication
Netlify allows you to gate your site behind basic authentication directly via headers. This is a common pattern for staging environments where you want to password-protect the site without building a complex login system. It is implemented by adding the Basic-Auth header to your _headers file.
# Password protect the entire site
/*
Basic-Auth: user:password-hash
Note that the password must be hashed using the platform-specific requirements. This is a simple, effective way to ensure that only people who know the credentials can browse your site. It is not a replacement for enterprise-grade authentication but is perfectly suited for internal previews or team-only environments.
Complete Example Session
# ============================================
# PART 1: GLOBAL SECURITY HEADERS
# ============================================
# Applied to all files (/*)
/*
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
# ============================================
# PART 2: CONTENT-SECURITY-POLICY
# ============================================
/*
Content-Security-Policy: default-src 'self'; script-src 'self' https://js.stripe.com; frame-ancestors 'none';
# ============================================
# PART 3: CORS FOR API
# ============================================
/api/*
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
# ============================================
# PART 4: CACHING CONTROL (FOR PERFORMANCE)
# ============================================
# Cache images for 1 year
/assets/*.png
Cache-Control: public, max-age=31536000, immutable
# ============================================
# PART 5: BASIC AUTH (STAGING)
# ============================================
# Only apply to staging env (usually handled via Netlify dashboard,
# but can be header-forced if needed)
/internal/*
Basic-Auth: team:p@ssw0rd123
# ============================================
# PART 6: PRE-FLIGHT OPTIONS HANDLING
# ============================================
# Explicitly allow OPTIONS for CORS pre-flight
/api/*
Access-Control-Allow-Methods: GET, POST, OPTIONS
# ============================================
# PART 7: COOKIE SECURITY
# ============================================
/*
Set-Cookie: __Host-session=...; Secure; HttpOnly; SameSite=Strict
# ============================================
# PART 8: DEPLOYMENT VERIFICATION
# ============================================
# curl -I https://yoursite.com/
# Check for 'X-Content-Type-Options: nosniff'
# ============================================
# PART 9: TROUBLESHOOTING CSP
# ============================================
# If scripts fail to load, check Browser Console:
# "Refused to load script... violates CSP"
# Adjust CSP header accordingly
# ============================================
# PART 10: AUTOMATION
# ============================================
# Keep _headers in public/ or dist/ folder
# Ensure your framework build step doesn't ignore it
The steps cover securing the entire site, handling API CORS, optimizing assets with Cache-Control, and password protection.
Quick Reference
Essential Security Headers
| Header | Purpose | Setting |
|---|---|---|
X-Frame-Options | Clickjacking | DENY |
X-Content-Type | MIME sniffing | nosniff |
HSTS | HTTPS enforcement | max-age=... |
Referrer-Policy | Privacy | strict-origin-when-cross-origin |
CORS Configuration
| Header | Purpose |
|---|---|
Access-Control-Allow-Origin | Allowed domains |
Access-Control-Allow-Methods | Allowed HTTP verbs |
Access-Control-Allow-Headers | Allowed request headers |
Basic Auth
| Setting | Purpose |
|---|---|
Basic-Auth | user:password-hash |
| Scope | Apply to path or /* |
Best Practices
โ Do This:
# Use DENY for X-Frame-Options unless embedding // โ
# Always include HSTS for production // โ
# Whitelist only necessary domains in CSP // โ
# Test CORS with a tool like Postman // โ
# Use immutable Cache-Control for fingerprinted assets // โ
โ Don’t Do This:
# Set Access-Control-Allow-Origin: * on sensitive APIs // โ
# Use unsafe-inline in CSP if possible // โ
# Put credentials in cleartext in _headers // โ
# Ignore CSP console errors during dev // โ
# Assume headers apply to Netlify Functions // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Broken CSS/JS | Too strict CSP | Add script source to CSP |
| API blocked | Missing CORS headers | Add Access-Control headers |
| Frame error | X-Frame-Options active | Change to SAMEORIGIN |
| Basic Auth fail | Wrong hash/syntax | Verify password hash |
| Header ignored | File not in build root | Move to public/ folder |
Real-World Examples
1. Hardened Production
Applying all standard security headers to /*.
2. Stripe Integration
Whitelisting https://js.stripe.com in CSP for payment pages.
3. API Subdomain
Allowing requests from app.yoursite.com to api.yoursite.com.
4. Staging Access
Basic auth on /staging/* for team reviews.
5. Fingerprinted Asset Cache
Caching .js and .css files forever with immutable.
6. Clickjacking Defense
Preventing an iframe-based widget from loading on other sites.
7. Privacy Mode
Setting Referrer-Policy: no-referrer for sensitive pages.
8. Secure Cookies
Enforcing SameSite=Strict on session cookies.
9. HSTS Preload
Setting max-age to 2 years with preload flag.
10. Developer API
Allowing OPTIONS requests to avoid pre-flight errors.
Visual
Header Application Hierarchy
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ USER REQUEST โ
โ โ โ
โ โผ โ
โ [ Netlify Edge ] โโโโบ Applies _headers โ
โ โ โ
โ โผ โ
โ BROWSER (Parses headers) โ
โ - Blocks IFRAME? โ
โ - Blocks Unsafe Scripts? โ
โ - Enforces HTTPS? โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The CSP “Safety Net”
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ATTACKER INJECTION โ
โ ( <script src="evil.com/xss.js"> ) โ
โ โ โ
โ โผ โ
โ BROWSER (Checks CSP) โ
โ - Is 'evil.com' in whitelist? NO โ
โ - BLOCK EXECUTION โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Primary File | _headers |
| Core Security | X-Frame, X-Content-Type |
| Script Security | CSP |
| Cross-Domain | CORS |
| Staging Gate | Basic-Auth |
| Placement | Build Output Root |
Key takeaways:
- Headers are global guards. They are applied at the network edge, providing a consistent layer of security that wraps your entire application, not just the HTML.
- CSP is your primary defense. A well-crafted Content-Security-Policy is the single most effective way to neutralize XSS attacks.
- CORS requires care. Avoid
Access-Control-Allow-Origin: *on private or authenticated APIs; always be as specific as possible. - Version control your security. Keeping
_headersin Git ensures your security policy is audited, peer-reviewed, and deployed alongside your feature code. - Test in production-like environments. Security headers can easily break site functionality; always verify your CSP and CORS settings in a staging environment before pushing to production.
Remember: Security is not a “set it and forget it” task. Headers allow you to be proactive. By defaulting to the most restrictive settings and only relaxing them when necessary, you build a fortress around your application that is managed, transparent, and resilient.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!