Blogs

Tools

Quick Links

Mridul.tech

What is CORS in JavaScript?

Mridul Panda

Mridul Panda

Aug 05, 2025

·

5 Min Read

What is CORS in JavaScript?

CORS (Cross-Origin Resource Sharing) is a fundamental security mechanism implemented in web browsers that governs how resources are requested from another domain (or origin). In simple terms, it’s a way for a server to tell the browser, “Yes, this external domain is allowed to access my resources.” Without proper CORS configuration, modern browsers will block these types of requests, leading to what developers commonly refer to as CORS errors. Discover everything you need to know about CORS in JavaScript, including how it works, why CORS errors happen, how to fix them from both backend and frontend, and the best practices to follow.

Same-Origin Policy – The Root of CORS

At the heart of CORS lies the Same-Origin Policy (SOP). This is a browser security feature that restricts web pages from making HTTP requests to a domain different from the one that served the original page. Two URLs are considered to be of the same origin if they have the same protocol, domain, and port number.

For example:

  • https://example.com/app.js can make a request to https://example.com/data.json
  • But not to https://api.example.com/data.json
  • Or http://example.com/data.json ❌ (note the different protocol)

This policy protects users from malicious scripts on one site trying to access sensitive data on another. However, it also means developers need a way to legitimately allow cross-origin access — and that’s where CORS comes in.

Why CORS Errors Happen

CORS errors occur when a web application attempts to access a resource from a different origin and the target server does not include the proper CORS headers in its response.

Here’s what typically causes CORS errors:

  • The server does not send the Access-Control-Allow-Origin header in the response.
  • The header exists but the origin is not listed or allowed.
  • A preflight request fails due to improper configuration of methods or headers.
  • The Access-Control-Allow-Credentials flag is missing when making requests with credentials (like cookies or HTTP authentication).
  • The wrong HTTP methods are allowed (e.g., PUT, DELETE), but not configured correctly on the server.

Browsers enforce these rules strictly, and if the correct headers aren’t present, they will block the response entirely, even though the request might have succeeded on the network layer.

Also Read: Semantic HTML: Boost Accessibility, SEO, and User Experience

What A CORS Error Looks Like

CORS errors are commonly seen in the browser console. Here’s an example of what such an error message might look like in Google Chrome or Firefox:

Access to fetch at 'https://api.example.com/data' from origin 'https://myapp.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.example.com/data. (Reason: CORS request did not succeed).

These messages indicate that your browser blocked the response because the server didn’t allow the current origin to access the resource.

How To Fix CORS in JavaScript as a Backend Developer

Backend developers are primarily responsible for resolving CORS issues since they control the response headers.

1. Set the Correct CORS Headers

The simplest way to resolve a CORS issue is to set the correct headers on the server response. At minimum:

Access-Control-Allow-Origin: https://yourfrontenddomain.com

To allow all domains (for public APIs only):

Access-Control-Allow-Origin: *

Warning: Using * is insecure for private APIs or when using cookies or credentials.

Also Read: JavaScript Project Ideas to Boost Your Portfolio

2. Enable Preflight Responses

When using custom headers, or HTTP methods like PUT, DELETE, or PATCH, the browser performs a preflight request with the OPTIONS method.

You must handle this request and respond with headers like:

Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Origin: https://yourfrontenddomain.com
Access-Control-Allow-Credentials: true

3. Use Middleware to prevent CORS In JavaScript

Most backend frameworks offer middleware to handle CORS more elegantly and in Node.js (Express):

const cors = require('cors');
app.use(cors({ origin: 'https://yourfrontenddomain.com', credentials: true }));

Fixing CORS in JavaScript in Frontend Applications

While CORS must be handled on the server side, frontend developers can use certain approaches to bypass or work around CORS restrictions during development.

1. Use a Proxy

You can route API requests through your frontend server or a local proxy that adds the necessary CORS headers:

Example with next.config.js:

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

2. Development Tools and Browsers

You may use browser plugins like CORS Unblocker, or run Chrome with CORS disabled (not recommended for production).

3. Custom Headers Awareness

When sending headers like Authorization, X-Custom-Header, or setting credentials: 'include', make sure the backend is configured to explicitly allow those headers and enable credentials.

fetch('https://api.example.com/data', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer token',
  },
  credentials: 'include'
});

Also Read: Anonymous Functions in JavaScript

Best Practices of CORS In JavaScript

To avoid future issues and ensure scalable, secure systems, follow these CORS best practices:

  • Whitelist only trusted origins — never use * in production when dealing with sensitive data.
  • Allow only required methods (GET, POST, etc.) and headers.
  • Avoid overly permissive headers like Access-Control-Allow-Origin: * with credentials.
  • Handle preflight (OPTIONS) requests explicitly in your API.
  • Test your API with multiple tools (e.g., Postman, Curl, browser) to identify CORS issues early.
  • Log and monitor CORS errors for faster debugging.
  • Use environment-based configs — allow broad access in development but restrict it in production.

Do you want more articles on React, Next.js, Tailwind CSS, and JavaScript?

Subscribe to my newsletter to receive articles straight in your inbox.

If you like my work and want to support me, consider buying me a coffee.

Buy Me A Coffee

Contact Me ☎️

Discuss A Project Or Just Want To Say Hi?
My Inbox Is Open For All.

Mail : contact@mridul.tech

Connect with me on Social Media

Contact Art