🌐 Detecting your location…
📢 Advertisement — Configure AdSense in Appearance → Customize → AdSense Settings

How to Fix CORS Error in JavaScript and React (Complete Solutions 2026)

⏱️4 min read  ·  711 words

How To Fix Cors Error Javascript React

How to Fix CORS Error in JavaScript and React (Complete Solutions 2026)

Error: Access to fetch at 'https://api.example.com' from origin 'http://localhost:3000' has been blocked by CORS policy

Understanding CORS First

CORS (Cross-Origin Resource Sharing) is a browser security mechanism. It blocks requests from one origin (domain+port+protocol) to a different origin unless the server explicitly allows it. This is a server-side issue, not a frontend issue. The browser is doing its job correctly.

Solution 1: Fix It on the Server (Correct Approach)

If you control the API server, add CORS headers:

Node.js + Express:

npm install cors

const express = require('express');
const cors = require('cors');
const app = express();

// Allow all origins (development only)
app.use(cors());

// OR: Allow specific origins (production)
app.use(cors({
  origin: ['https://yourdomain.com', 'http://localhost:3000'],
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true  // only if using cookies/sessions
}));

app.listen(5000);

Python + FastAPI:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000", "https://yourdomain.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/api/data")
def get_data():
    return {"message": "CORS working"}

Python + Django:

pip install django-cors-headers

# settings.py
INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',  # Must be FIRST
    'django.middleware.common.CommonMiddleware',
    ...
]

CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
    "https://yourdomain.com",
]

# OR for dev (allow everything):
CORS_ALLOW_ALL_ORIGINS = True

Solution 2: Use a Proxy in React (Development)

When you can’t change the server (third-party APIs), set up a development proxy in Create React App or Vite:

Create React App (package.json):

{
  "name": "my-app",
  "proxy": "http://localhost:5000"
}

Now requests to /api/users in your React code will proxy to http://localhost:5000/api/users — same origin, no CORS.

Vite (vite.config.js):

export default {
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:5000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
}

Next.js (next.config.js):

module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: 'https://external-api.com/:path*',
      },
    ]
  },
}

Solution 3: CORS Proxy for Third-Party APIs (Quick Fix)

If you need to quickly access a third-party API from the browser during development:

// Instead of:
fetch('https://some-api.com/data')

// Use CORS proxy (DEV ONLY — never in production):
fetch('https://cors-anywhere.herokuapp.com/https://some-api.com/data')

Warning: CORS proxies expose your requests to a third party. Use only in development and move to a backend proxy for production.

Solution 4: Handle Preflight Requests (OPTIONS)

CORS errors often occur with OPTIONS preflight requests on non-simple requests (custom headers, PUT/DELETE methods, JSON body):

// Express: Handle OPTIONS preflight explicitly
app.options('*', cors()); // Enable pre-flight across all routes

// OR for a specific route:
app.options('/api/users', cors());
app.post('/api/users', cors(), (req, res) => {
  res.json({ created: true });
});

Solution 5: Nginx Reverse Proxy (Production)

Serve both frontend and backend from the same origin using Nginx:

server {
    listen 80;
    server_name yourdomain.com;

    # Frontend (React build)
    location / {
        root /var/www/html/build;
        try_files $uri /index.html;
    }

    # Backend API proxy - same domain, no CORS
    location /api/ {
        proxy_pass http://localhost:5000/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

Common Mistakes That Don’t Fix CORS

  • Browser extensions “CORS Unblock” — Only works for you, not users. Never a real fix.
  • Adding headers in React fetch() — Frontend headers don’t affect CORS. The server must respond with the right headers.
  • Using no-cors mode in fetchfetch(url, {mode: 'no-cors'}) gives you an opaque response you can’t read. Not a fix.
  • Setting Origin header in fetch — Browser ignores manually set Origin headers for security.

Debugging CORS Issues

  1. Open Chrome DevTools → Network tab
  2. Find the failing request
  3. Check Response Headers for Access-Control-Allow-Origin
  4. Check if it’s a preflight (OPTIONS) request failing
  5. Check if credentials: true is set without Access-Control-Allow-Credentials: true on server
// Fetch with credentials (cookies, auth headers)
fetch('https://api.example.com/data', {
  credentials: 'include',  // Must match server's allow-credentials: true
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token'
  }
});

Quick Decision Tree

Do you control the API server?
├── YES → Add CORS headers on the server (Solution 1)
└── NO
    ├── Development only? → Use Vite/CRA proxy (Solution 2)
    └── Production?
        ├── Your own backend? → Use Nginx proxy (Solution 5)
        └── Third-party API → Create a backend endpoint that
            calls the API server-to-server (no CORS in server code)

✍️ Leave a Comment

Your email address will not be published. Required fields are marked *

🌐 Read in:🇬🇧 English🇩🇪 Deutsch🇧🇷 Português🇸🇦 العربية🇮🇳 हिन्दी🇧🇩 বাংলা