Cross-origin Resource Sharing

Home » Cross-origin Resource Sharing

Introduction to Cross-origin Resource Sharing

Cross-origin Resource Sharing (CORS) is a browser security mechanism that enables safe cross-domain requests by using HTTP headers to declare which origins may access a server’s resources. Before CORS was standardized in 2014 as part of HTML5, developers relied on insecure workarounds like JSONP. Today, CORS is supported by all major browsers and solves the challenge of controlled data exchange in distributed web applications and microservices environments. For hands-on testing in isolated environments, see our documentation on GeeLark isolated profiles.

The Same-Origin Policy and Why CORS Is Necessary

The same-origin policy restricts how scripts and documents from one origin can interact with resources from another. An origin is defined by its protocol, domain, and port. While this policy prevents malicious cross-site interactions, it also blocks legitimate use cases such as loading web fonts from CDNs, making API calls to separate services, or embedding third-party widgets. CORS provides a standardized, header-based exception to this policy, allowing servers to negotiate permitted cross-origin requests without sacrificing protection against CSRF and similar attacks.

How CORS Works

CORS relies on specific HTTP response headers to inform browsers which cross-origin requests are allowed. When a browser sends a request to a different origin, it checks these headers and enforces the policy automatically.

Key HTTP Headers

  • Access-Control-Allow-Origin: Allowed origin (e.g., https://example.com or *)
  • Access-Control-Allow-Methods: Permitted HTTP methods (GET, POST, PUT, DELETE, etc.)
  • Access-Control-Allow-Headers: Which request headers (e.g., Content-Type, Authorization) can be used
  • Access-Control-Allow-Credentials: Whether credentials (cookies, authorization headers) are sent
  • Access-Control-Expose-Headers: Which response headers are exposed to JavaScript
  • Access-Control-Max-Age: How long preflight (OPTIONS) responses can be cached

Simple Requests vs. Preflight Requests

A simple request uses GET, HEAD, or POST with only safe headers (Accept, Accept-Language, Content-Language, Content-Type of application/x-www-form-urlencoded, multipart/form-data, or text/plain). For these, the browser issues the request directly and then checks the Access-Control-Allow-Origin response header.

A preflight request is required if the request uses other methods (PUT, DELETE, PATCH, etc.), custom headers, or non-simple content types. The browser first sends an OPTIONS request to verify permissions:

curl -i -X OPTIONS https://api.example.com/resource
-H "Origin: https://example.com"
-H "Access-Control-Request-Method: PUT"

CORS Implementation for Web Developers

Server-Side Configuration

  • Node.js (Express):
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
  origin: 'https://example.com',
  methods: ['GET','POST','PUT','DELETE'],
  credentials: true
}));
  • Apache (.htaccess):
Header set Access-Control-Allow-Origin "https://example.com"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header set Access-Control-Allow-Credentials "true"
  • Nginx (server block):
add_header Access-Control-Allow-Origin "https://example.com";
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE";
add_header Access-Control-Allow-Credentials "true";

Client-Side Considerations

Handle CORS errors gracefully in your frontend code, include credentials only when necessary, and test across different browsers since implementations may vary slightly.

Testing Tools

  • Browser developer tools (Network tab)
  • Postman with CORS checks
  • Online validators like CORS Tester

Common CORS Issues: Troubleshooting Checklist

  1. Missing required response headers
  2. Using * origin with credentials (not allowed)
  3. Methods or headers in the request not listed in Access-Control-Allow-Methods or Access-Control-Allow-Headers
  4. Preflight responses cached longer than expected
  5. Mismatched header casing or typos

CORS in Modern Web Architecture

In microservices-based systems, CORS allows frontends to consume multiple backend APIs, integrate third-party services, and implement cross-domain single sign-on flows. By declaring precise allowlists on API gateways, teams can enforce consistent CORS policies across all service endpoints.

Deeply Integrate: GeeLark API

  • With GeeLark API, you can deeply integrate your own system with GeeLark. From setting up cloud devices to automating tasks and handling apps or proxies, everything is easy and organized.
  • GeeLark works for everyone from casual users to tech pros. Teams can quickly integrate their projects via API, bulk-create profiles, and automate account tasks with proxies.
  • You can use the API to create, start, stop, and manage multiple cloud phones from your own systems. It lets you automate tasks like installing apps, running ADB commands, setting proxies, and updating device settings in bulk. You can also track real-time status, organize profiles, and streamline workflows for large teams or complex projects.
  • All GeeLark API calls are initiated with the POST method. The contents of POST are all in JSON format.

CORS Best Practices and Security Considerations

• Restrict Access-Control-Allow-Origin to specific domains rather than * in production
• Limit allowed HTTP methods to only those needed
• Use Access-Control-Allow-Credentials judiciously
• Maintain an allowlist of trusted domains
• Combine CORS with CSRF tokens and a robust Content Security Policy for layered defense

Integrating CORS with Other Web Security Mechanisms

CORS works alongside other standards:

  • Content Security Policy (CSP) for script and resource loading
  • SameSite cookies to mitigate CSRF
  • OAuth 2.0 for secure cross-origin authorization

Conclusion

CORS remains indispensable for secure cross-origin communication in increasingly distributed web applications. By adhering to precise header configurations, testing thoroughly, and combining CORS with other security measures, you can deliver APIs that are both accessible and protected. As browsers evolve and new web technologies emerge, continued vigilance and best practice adoption will be key to maintaining robust security.

People Also Ask

What is cross-origin resource sharing?

Cross-origin Resource Sharing (CORS) is a browser security feature that lets web servers specify which external domains can access their resources. By default, browsers enforce the same-origin policy, blocking cross-domain requests. CORS uses HTTP headers like Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers to declare permitted origins, HTTP methods, and headers. For non-simple requests, browsers send a preflight OPTIONS request to confirm permissions before making the actual request, ensuring secure, controlled cross-domain interactions.

What is cross-origin resource sharing vulnerability?

A cross-origin resource sharing vulnerability happens when a server’s CORS policy is too permissive or improperly configured—such as allowing any origin, echoing request origins without validation, or enabling unsafe methods and credentials. This misconfiguration bypasses the browser’s same-origin policy, letting malicious sites issue cross-domain requests to read or manipulate sensitive data, hijack sessions, or perform unauthorized actions on behalf of authenticated users.

Is enabling CORS a security risk?

Enabling CORS itself isn’t inherently risky, but misconfiguring it can introduce serious security issues. Overly permissive policies—such as using Access-Control-Allow-Origin: * or allowing credentials and unsafe methods—can let untrusted sites perform unauthorized actions or steal sensitive data. To stay secure, restrict CORS to specific trusted origins, limit allowed HTTP methods and headers, and only enable credentials when strictly necessary. Properly configured CORS enforces secure cross-domain interactions without undermining the browser’s same-origin policy guarantees.

How to enable CORS cross-origin resource sharing?

Enabling CORS involves configuring your server to return specific HTTP headers with each response (and on OPTIONS preflight):

• Access-Control-Allow-Origin: specify a single origin (or “*” for any)
• Access-Control-Allow-Methods: list allowed HTTP verbs (GET, POST, PUT, DELETE, etc.)
• Access-Control-Allow-Headers: list permitted custom headers (Content-Type, Authorization, etc.)
• Access-Control-Allow-Credentials: true (if you need cookies or HTTP authentication)

Also ensure your server responds to OPTIONS requests with these headers and a 200 status. Most web frameworks (Express, Django, Spring) and servers (Nginx, Apache) offer built-in CORS middleware or directives.