惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX - 技术
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
Microsoft Security Blog
Microsoft Security Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
K
Kaspersky official blog
F
Fortinet All Blogs
GbyAI
GbyAI
Forbes - Security
Forbes - Security
The Cloudflare Blog
博客园 - 司徒正美
博客园_首页
量子位
Schneier on Security
Schneier on Security
G
GRAHAM CLULEY
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Proofpoint News Feed
N
News | PayPal Newsroom
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
T
Tor Project blog
V
Vulnerabilities – Threatpost
Y
Y Combinator Blog
Jina AI
Jina AI
Help Net Security
Help Net Security
T
Threat Research - Cisco Blogs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Cybersecurity and Infrastructure Security Agency CISA
Project Zero
Project Zero
N
News and Events Feed by Topic
I
Intezer
B
Blog
美团技术团队
C
CERT Recently Published Vulnerability Notes
NISL@THU
NISL@THU
L
LINUX DO - 最新话题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Blog — PlanetScale
Blog — PlanetScale
AWS News Blog
AWS News Blog
T
Tailwind CSS Blog
The Last Watchdog
The Last Watchdog
雷峰网
雷峰网
有赞技术团队
有赞技术团队

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
Security Headers in Production: CSP, HSTS, and the Headers Your API Is Missing
The Practica · 2026-06-05 · via The Practical Developer

The pentest report landed at 4:00 PM on a Friday. Thirty findings, but one line stopped the room: “Stored XSS in the user profile page. Cookie accessible via JavaScript. No CSP present.” The fix was simple on paper (sanitize the input, add some headers), but the headers part turned into a week-long project because nobody on the team knew what a realistic Content-Security-Policy looked like for an app that loads four different analytics scripts, two widget libraries, and embeds tweets.

This is the state of security headers in most production apps in 2026. They are either missing entirely, copy-pasted from a blog without understanding, or locked down so aggressively that the frontend team has to relax them weekly to unblock a new vendor script. There is a middle ground, and it starts with understanding the six headers that actually matter.

Not every security header is worth your time. Feature-Policy is dead. X-XSS-Protection was deprecated when browsers removed XSS auditor support. And Expect-CT became irrelevant after Chrome 61. The headers below are the ones that still matter in 2026, backed by every major browser, and required by security standards like OWASP ASVS and the Mozilla Observatory.

1. Strict-Transport-Security (HSTS)

This header tells the browser to only connect to your domain over HTTPS, even if the user types http:// or clicks an old HTTP link. One request can prevent SSL-strip attacks for months.

Strict-Transport-Security: max-age=63072000; includeSubDomains; preload

The parameters are not optional:

  • max-age=63072000 is two years. This is the minimum for HSTS preload.
  • includeSubDomains extends the policy to every subdomain, including api.yoursite.com and admin.yoursite.com.
  • preload is a flag to the browser that your domain can be hardcoded into the browser’s HSTS preload list. It is a one-way door. Once you are on the list, you cannot remove your domain from HTTPS enforcement for the duration set by the browser vendor (often years).

Do not ship preload on your first deploy. Serve max-age=300 for a week, then max-age=63072000 without preload for another week, then add preload only after you have confirmed every single subdomain serves HTTPS. The HSTS preload list does not care about your staging subdomain that still runs HTTP.

2. Content-Security-Policy (CSP)

This is the most powerful header and the one most teams get wrong. CSP lets you tell the browser exactly which sources of content are allowed to execute. A properly tuned CSP blocks inline scripts, stops XSS even if an attacker injects a <script> tag, and prevents data exfiltration by restricting where the page can make requests.

A reasonable starting policy for a content site with analytics:

Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' https://www.googletagmanager.com https://www.google-analytics.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https://images.unsplash.com https://www.google-analytics.com; connect-src 'self' https://api.yourbackend.com; font-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'

That is ugly, and it will break things on your first deploy. That is normal. The key is to start with Content-Security-Policy-Report-Only and a report-uri before you enforce anything.

The CSP deployment workflow:

  1. Set Content-Security-Policy-Report-Only with report-uri https://your-report-endpoint.example.com/report.
  2. Watch the reports for a week. Every blocked resource is a legitimate script you forgot to allow.
  3. Triage each violation: add legitimate sources, fix insecure patterns, document deliberate exceptions.
  4. Only after the report-only policy has been clean for a week, switch to Content-Security-Policy enforcement.

The one CSP mistake that kills performance:

'unsafe-inline' on script-src defeats the entire purpose of CSP. It tells the browser “inline scripts are fine,” which is the exact vector CSP is meant to block. The alternative is to use a nonce or a hash. A nonce is a per-request random value:

Content-Security-Policy: script-src 'nonce-abc123' 'strict-dynamic'

Every <script> tag in your HTML gets nonce="abc123" (a fresh random value per request). 'strict-dynamic' allows scripts loaded by those trusted scripts to also execute, which handles the common case where your boot script dynamically loads a module. The nonce approach is harder to implement than 'unsafe-inline' because your templating engine or framework must inject the nonce into every script tag. But it is the only CSP configuration that actually prevents XSS.

3. X-Content-Type-Options

The simplest header you will set today:

X-Content-Type-Options: nosniff

This tells the browser not to MIME-sniff the response. Without it, an attacker can upload an HTML file disguised as image.jpg and the browser will render it as HTML, enabling XSS. nosniff forces the browser to respect the Content-Type header. If you serve Content-Type: image/jpeg, the browser must treat it as an image, not HTML.

There is no debate about this header. Every response from your origin should include it. Every CDN should forward it. There is no downside.

4. X-Frame-Options (or frame-ancestors in CSP)

X-Frame-Options: DENY

Prevents clickjacking by blocking your page from being embedded in an iframe on another domain. If you need to allow embedding on specific domains, use CSP’s frame-ancestors instead, which is more granular:

Content-Security-Policy: frame-ancestors 'self' https://trusted-partner.com

If you set both, frame-ancestors takes precedence in modern browsers and X-Frame-Options acts as a fallback for older ones. Set DENY unless you have a specific embedding use case.

5. Referrer-Policy

Controls how much referrer information is sent with requests leaving your site:

Referrer-Policy: strict-origin-when-cross-origin

This sends the full URL as referrer for same-origin requests, only the origin (no path or query string) for cross-origin requests over HTTPS, and nothing when navigating from HTTPS to HTTP. It is the safest default that does not break analytics referrer tracking.

6. Permissions-Policy (formerly Feature-Policy)

Replaces the deprecated Feature-Policy header. Controls which browser features your page can access:

Permissions-Policy: camera=(), microphone=(), geolocation=(), interest-cohort=()

The fourth value, interest-cohort=(), opts your site out of Google’s Topics API for ad targeting. Include it even if you do not care about ad privacy, because the default is opt-in and browsers may change the default over time.

One middleware to set them all

Here is a complete Express/Fastify-compatible middleware function that sets all six headers with safe defaults:

import { randomBytes } from 'node:crypto';
import type { Request, Response, NextFunction } from 'express';

interface SecurityHeadersOptions {
  cspDirectives?: Record<string, string[]>;
  hstsMaxAge?: number;
  hstsIncludeSubdomains?: boolean;
  isDev?: boolean;
}

export function securityHeaders(opts: SecurityHeadersOptions = {}) {
  const {
    cspDirectives = {},
    hstsMaxAge = 63072000,
    hstsIncludeSubdomains = true,
    isDev = process.env.NODE_ENV === 'development',
  } = opts;

  return function middleware(req: Request, res: Response, next: NextFunction) {
    // Generate per-request CSP nonce
    const nonce = randomBytes(16).toString('base64url');
    res.locals.cspNonce = nonce;

    // Build CSP from directives
    const directives: Record<string, string[]> = {
      'default-src': ["'self'"],
      'script-src': [`'nonce-${nonce}'`, "'strict-dynamic'"],
      'style-src': ["'self'", "'unsafe-inline'"],
      'img-src': ["'self'", 'data:', 'https://images.unsplash.com'],
      'connect-src': ["'self'"],
      'font-src': ["'self'"],
      'frame-ancestors': ["'none'"],
      'base-uri': ["'self'"],
      'form-action': ["'self'"],
      'report-uri': ['/__csp-report'],
      ...cspDirectives,
    };

    const cspValue = Object.entries(directives)
      .map(([key, values]) => `${key} ${values.join(' ')}`)
      .join('; ');

    // Set headers
    res.setHeader(
      'Content-Security-Policy',
      isDev
        ? `${cspValue}; Content-Security-Policy-Report-Only`
        : cspValue
    );

    res.setHeader(
      'Strict-Transport-Security',
      `max-age=${hstsMaxAge}${hstsIncludeSubdomains ? '; includeSubDomains' : ''}`
    );

    res.setHeader('X-Content-Type-Options', 'nosniff');
    res.setHeader('X-Frame-Options', 'DENY');
    res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
    res.setHeader(
      'Permissions-Policy',
      'camera=(), microphone=(), geolocation=(), interest-cohort=()'
    );

    next();
  };
}

The nonce generation is the critical piece. Every request gets a unique nonce, and your templates must apply it to every <script> tag. In a framework like Astro, you access it through middleware or a custom integration. In a plain Express app rendering HTML, you pass res.locals.cspNonce to your template engine.

The answer depends on whether you control the origin and how your architecture is laid out.

If you use a CDN like Cloudflare, Fastly, or Akamai: set HSTS and X-Content-Type-Options at the CDN edge. These headers are static and apply to every response. Setting them at the edge means they are applied even if your origin is temporarily unreachable or serving a fallback page. CSP, on the other hand, should be set at the origin because it needs the per-request nonce.

If you do not use a CDN: set everything at the origin. The middleware above works as-is.

Hybrid approach: set the static headers (HSTS, X-Content-Type-Options, Referrer-Policy, Permissions-Policy, X-Frame-Options) at the CDN, and set CSP at the origin. This lets your CDN handle the boilerplate while keeping CSP dynamic.

Before you deploy, run these checks:

# Quick header check
curl -sI https://yoursite.com | grep -i -E '^(strict-transport-security|content-security-policy|x-content-type-options|x-frame-options|referrer-policy|permissions-policy)'

# Full header dump
curl -sI https://yoursite.com | head -20

# Check CSP with violations (requires a browser)
# Open DevTools > Console > look for CSP violation warnings

For a thorough audit, use these free tools:

Run these tools against your staging environment before production. Run them weekly in production. Set up a CI check that fails if the grade drops below A.

Common CSP mistakes and how to fix them

Mistake 1: 'unsafe-inline' instead of a nonce.

“This is fine because we control our scripts.” No, you do not. If an attacker injects a <script> tag, 'unsafe-inline' lets it execute. The nonce approach is the only CSP configuration that provides real XSS protection. The migration from 'unsafe-inline' to a nonce usually takes a day of template work and zero runtime cost.

Mistake 2: Using https: as a scheme source for scripts.

Content-Security-Policy: script-src https:

This allows any script served over HTTPS from any domain. That is not a security policy. It is a formality. Specify exact domains.

Mistake 3: Not setting a report-uri.

Without a report endpoint, you are flying blind. Violations are silently dropped. Use a service like report-uri.com, or build a simple endpoint that logs to your error tracker:

// CSP report endpoint (Express)
app.post('/__csp-report', express.json({ type: 'application/csp-report' }), (req, res) => {
  // Log to your observability system
  console.error('CSP Violation:', JSON.stringify(req.body, null, 2));
  res.status(204).end();
});

Mistake 4: Ignoring violation reports for more than a week.

Set up an alert. A new CSP violation pattern that appears after a deploy means something is broken. The frontend team should own the CSP report triage, because they are the ones who will know whether a blocked script is a new dependency or an actual attack.

The no-excuses baseline

If you take nothing else from this post, ship these five headers on every response today:

Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=(), interest-cohort=()

These five headers require zero application changes. They do not depend on your framework, your templating engine, or your frontend architecture. They can be set at the CDN edge or in a reverse proxy. They will improve your Mozilla Observatory score from F to B+ in one deploy. Add a reasonable CSP with a nonce and report-uri, and you hit A+.

Your application already trusts its own responses. These headers make sure the browser does too. The cost is a few kilobytes of configuration. The cost of not setting them is the next pentest report that starts with “Stored XSS.”

A note from Yojji

The gap between “I set some headers” and “these headers actually protect my users” is the same gap that separates a demo from a production deployment. Tuning a CSP nonce, setting up a report endpoint, and establishing a weekly triage process for violations is unglamorous operational work that most teams skip until an auditor forces the issue. Yojji’s engineering teams have built that discipline into Node.js backends and cloud-native deployments for clients across finance, healthcare, and e-commerce, where security headers are not optional and violations are monitored as closely as error rates.

Yojji is an international custom software development company founded in 2016, with offices in Europe, the US, and the UK. Their senior engineers specialize in the JavaScript ecosystem, cloud infrastructure on AWS/Azure/Google Cloud, and the full cycle of product delivery from discovery through production operations.