CORS & Security Headers
CORS (Express)
import cors from 'cors';
// Restrictive (recommended)
app.use(cors({
origin: ['https://myapp.com', 'https://admin.myapp.com'],
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
maxAge: 86400, // Preflight cache: 24h
}));
// Dynamic origin
app.use(cors({
origin: (origin, callback) => {
const allowed = ALLOWED_ORIGINS.includes(origin!) || !origin; // !origin = same-origin
callback(null, allowed ? origin : false);
},
credentials: true,
}));
Security Headers (Helmet.js)
import helmet from 'helmet';
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'", 'https://cdn.example.com'],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", 'data:', 'https:'],
connectSrc: ["'self'", 'https://api.example.com'],
frameSrc: ["'none'"],
objectSrc: ["'none'"],
},
},
hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
}));
CSRF Protection
import csrf from 'csurf';
// For server-rendered forms (session-based apps)
app.use(csrf({ cookie: true }));
app.get('/form', (req, res) => {
res.render('form', { csrfToken: req.csrfToken() });
});
// For SPAs: use SameSite cookies + custom header
// No csrf library needed — rely on:
// 1. SameSite=Strict/Lax cookies
// 2. Check Origin/Referer header matches
// 3. Custom header requirement (X-Requested-With)
Secure Cookies
app.use(session({
cookie: {
httpOnly: true, // No JS access
secure: true, // HTTPS only
sameSite: 'lax', // CSRF protection
maxAge: 24 * 60 * 60 * 1000,
domain: '.myapp.com', // Shared across subdomains
},
}));
Spring Boot Security Headers
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.cors(cors -> cors.configurationSource(corsConfig()))
.headers(headers -> headers
.contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'self'"))
.referrerPolicy(ref -> ref.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN))
.frameOptions(frame -> frame.deny())
)
.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))
.build();
}
@Bean
CorsConfigurationSource corsConfig() {
var config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://myapp.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowCredentials(true);
var source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
Key Headers Reference
| Header |
Purpose |
Recommended Value |
Strict-Transport-Security |
Force HTTPS |
max-age=31536000; includeSubDomains |
Content-Security-Policy |
Restrict resource loading |
default-src 'self' + specifics |
X-Content-Type-Options |
Prevent MIME sniffing |
nosniff |
X-Frame-Options |
Prevent clickjacking |
DENY |
Referrer-Policy |
Control referrer info |
strict-origin-when-cross-origin |
Permissions-Policy |
Restrict browser features |
camera=(), microphone=() |
Anti-Patterns
| Anti-Pattern |
Fix |
Access-Control-Allow-Origin: * with credentials |
Specify exact origins |
| No CSP header |
Add Content-Security-Policy |
| CSRF token in URL query params |
Use header or hidden form field |
SameSite=None without Secure |
Always pair SameSite=None with Secure |
| Missing HSTS |
Enable with long max-age and preload |
Production Checklist
1---2name: cors-security-headers3description: |4 CORS configuration and HTTP security headers. CORS middleware, preflight5 requests, Content-Security-Policy, CSRF protection, Helmet.js, and6 secure cookie configuration.78 USE WHEN: user mentions "CORS", "cross-origin", "CSP", "Content-Security-Policy",9 "CSRF", "security headers", "Helmet", "preflight", "Access-Control"1011 DO NOT USE FOR: authentication tokens - use `jwt` or `oauth2`;12 encryption - use `cryptography`13allowed-tools: Read, Grep, Glob, Write, Edit14metadata:15 source: https://skillmd.com/skills/claude-dev-suite/cors-security-headers16---1718# CORS & Security Headers1920## CORS (Express)2122```typescript23import cors from 'cors';2425// Restrictive (recommended)26app.use(cors({27 origin: ['https://myapp.com', 'https://admin.myapp.com'],28 methods: ['GET', 'POST', 'PUT', 'DELETE'],29 allowedHeaders: ['Content-Type', 'Authorization'],30 credentials: true,31 maxAge: 86400, // Preflight cache: 24h32}));3334// Dynamic origin35app.use(cors({36 origin: (origin, callback) => {37 const allowed = ALLOWED_ORIGINS.includes(origin!) || !origin; // !origin = same-origin38 callback(null, allowed ? origin : false);39 },40 credentials: true,41}));42```4344## Security Headers (Helmet.js)4546```typescript47import helmet from 'helmet';4849app.use(helmet({50 contentSecurityPolicy: {51 directives: {52 defaultSrc: ["'self'"],53 scriptSrc: ["'self'", "'unsafe-inline'", 'https://cdn.example.com'],54 styleSrc: ["'self'", "'unsafe-inline'"],55 imgSrc: ["'self'", 'data:', 'https:'],56 connectSrc: ["'self'", 'https://api.example.com'],57 frameSrc: ["'none'"],58 objectSrc: ["'none'"],59 },60 },61 hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },62 referrerPolicy: { policy: 'strict-origin-when-cross-origin' },63}));64```6566## CSRF Protection6768```typescript69import csrf from 'csurf';7071// For server-rendered forms (session-based apps)72app.use(csrf({ cookie: true }));73app.get('/form', (req, res) => {74 res.render('form', { csrfToken: req.csrfToken() });75});7677// For SPAs: use SameSite cookies + custom header78// No csrf library needed — rely on:79// 1. SameSite=Strict/Lax cookies80// 2. Check Origin/Referer header matches81// 3. Custom header requirement (X-Requested-With)82```8384## Secure Cookies8586```typescript87app.use(session({88 cookie: {89 httpOnly: true, // No JS access90 secure: true, // HTTPS only91 sameSite: 'lax', // CSRF protection92 maxAge: 24 * 60 * 60 * 1000,93 domain: '.myapp.com', // Shared across subdomains94 },95}));96```9798## Spring Boot Security Headers99100```java101@Bean102SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {103 return http104 .cors(cors -> cors.configurationSource(corsConfig()))105 .headers(headers -> headers106 .contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'self'"))107 .referrerPolicy(ref -> ref.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN))108 .frameOptions(frame -> frame.deny())109 )110 .csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()))111 .build();112}113114@Bean115CorsConfigurationSource corsConfig() {116 var config = new CorsConfiguration();117 config.setAllowedOrigins(List.of("https://myapp.com"));118 config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));119 config.setAllowCredentials(true);120 var source = new UrlBasedCorsConfigurationSource();121 source.registerCorsConfiguration("/**", config);122 return source;123}124```125126## Key Headers Reference127128| Header | Purpose | Recommended Value |129|--------|---------|------------------|130| `Strict-Transport-Security` | Force HTTPS | `max-age=31536000; includeSubDomains` |131| `Content-Security-Policy` | Restrict resource loading | `default-src 'self'` + specifics |132| `X-Content-Type-Options` | Prevent MIME sniffing | `nosniff` |133| `X-Frame-Options` | Prevent clickjacking | `DENY` |134| `Referrer-Policy` | Control referrer info | `strict-origin-when-cross-origin` |135| `Permissions-Policy` | Restrict browser features | `camera=(), microphone=()` |136137## Anti-Patterns138139| Anti-Pattern | Fix |140|--------------|-----|141| `Access-Control-Allow-Origin: *` with credentials | Specify exact origins |142| No CSP header | Add Content-Security-Policy |143| CSRF token in URL query params | Use header or hidden form field |144| `SameSite=None` without `Secure` | Always pair SameSite=None with Secure |145| Missing HSTS | Enable with long max-age and preload |146147## Production Checklist148149- [ ] CORS: specific origins, no wildcard with credentials150- [ ] Helmet.js (or equivalent) for all security headers151- [ ] CSP configured and tested152- [ ] HSTS with preload153- [ ] Secure, HttpOnly, SameSite cookies154- [ ] CSRF protection for state-changing requests