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

推荐订阅源

Hugging Face - Blog
Hugging Face - Blog
Stack Overflow Blog
Stack Overflow Blog
量子位
腾讯CDC
N
Netflix TechBlog - Medium
aimingoo的专栏
aimingoo的专栏
小众软件
小众软件
S
SegmentFault 最新的问题
A
About on SuperTechFans
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Tailwind CSS Blog
G
Google Developers Blog
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
雷峰网
雷峰网
罗磊的独立博客
Vercel News
Vercel News
L
LangChain Blog
V
V2EX
P
Proofpoint News Feed
M
MIT News - Artificial intelligence
博客园 - Franky
V
Visual Studio Blog
J
Java Code Geeks

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
5 Things I Learned Building APIs with Node.js:
Lolo · 2026-06-20 · via DEV Community

Lolo

Why Your CORS Setup Breaks in Production

You build the API. Test it locally. Everything works perfectly.

Then you deploy, and suddenly the browser console is full of red text about CORS policy violations.

If you've been there, here's why it happens and how to actually fix it instead of just slapping origin: '*' on everything and hoping for the best.


1. Localhost is forgiving. Production is not.

When you're developing locally, your frontend and backend often run on the same machine, sometimes even the same port through a proxy. The browser barely notices there's a cross-origin request happening.

In production, your frontend lives on one domain and your API on a completely different one. That's when the browser actually starts enforcing the same-origin policy seriously.

// Works fine locally because origins basically match
app.use(cors())

The moment you deploy to two separate domains, this default config either blocks everything or silently allows everything — neither of which you want.


2. origin: '*' is not a real fix

It's tempting. It makes the error go away. It's also a mistake waiting to bite you.

// Looks like it works. Is actually a liability.
app.use(cors({ origin: '*' }))

This disables credentialed requests (cookies, auth headers in some setups) and opens your API to literally any website on the internet. Fine for a public read-only API. Bad for anything involving user accounts or payments.


3. The real fix is an explicit allowlist

const allowedOrigins = [
  'https://yourapp.com',
  'https://www.yourapp.com'
]

app.use(cors({
  origin: (origin, callback) => {
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  },
  credentials: true
}))

The !origin check matters — server-to-server requests, curl, and some mobile clients don't send an Origin header at all. Without that check, you'd be blocking legitimate traffic that simply isn't a browser.


4. Changing your domain breaks everything silently

This one cost me an embarrassing amount of debugging time. I migrated from a default subdomain to a custom domain, updated the frontend, redeployed — and authentication started failing with cryptic 400 errors that had nothing to do with CORS in the error message itself.

The actual problem: my backend's CORS allowlist still only had the old domain. The browser was blocking the preflight request before it even reached my auth logic, and the error that bubbled up looked like an authentication failure, not a CORS one.

Lesson: whenever you change a frontend domain, your CORS allowlist is not optional to update. It's step one, not an afterthought.


5. Preflight requests fail before your routes even run

Browsers send an OPTIONS request before the real one whenever the request isn't "simple" (custom headers, JSON content-type, etc). If your CORS middleware isn't registered early enough, or runs after other middleware that rejects the request, the preflight fails and you never even see a log line from your actual route handler.

// CORS needs to run early, before anything that might short-circuit the request
app.use(cors({ origin: allowedOrigins, credentials: true }))
app.use(express.json())
app.use(authMiddleware)
app.use('/api', routes)

If you're staring at a 400 or 500 error with zero logs from inside your route, check whether the request even made it past the preflight. Half the time, it didn't.


CORS errors feel like browser nonsense until you understand they're doing exactly what they're designed to do — refusing to trust a cross-origin request you never explicitly allowed. The fix is rarely "disable security." It's almost always "tell the browser exactly who you trust."

What's the most confusing CORS bug you've run into? Always curious how creative the failure modes get.