Fix CORS Error: No 'Access-Control-Allow-Origin' Header is Present on the Requested Resource
Resolve browser cross-origin resource sharing errors by configuring backend HTTP headers and handling preflight OPTIONS requests.
Access to fetch at 'https://api.example.com' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
// Node.js / Express Middleware Solution
import cors from "cors";
const allowedOrigins = ["http://localhost:3000"];
app.use(cors({
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error("CORS blocked by server policy"));
}
},
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
credentials: true
}));
// Or Next.js Route Handler headers:
export async function OPTIONS() {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "http://localhost:3000",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Max-Age": "86400"
}
});
}Root Cause & Mechanism Analysis
Why does this error occur?
The browser blocks client-side JavaScript requests to a different domain, port, or protocol unless the target server explicitly returns the `Access-Control-Allow-Origin` HTTP header responding to the origin and properly answers the preflight HTTP `OPTIONS` request.
Frequently Asked Questions
Can I use wildcard `*` with credentials?
Why does Postman or cURL work but my browser fails?
Related Developer Error Solutions
Browse All 35 GuidesFetch: TypeError: Failed to fetch
Diagnose network drops, CORS blocks, HTTPS certificate invalidity, and ad-blocker request cancellations.
Nginx 502 Bad Gateway
Resolve reverse proxy gateway errors when Nginx cannot establish a connection with Node.js, Next.js, or Gunicorn backends.
CSP: Refused to execute inline script
Resolve Content Security Policy inline script blocks using nonces or SHA-256 hashes.