image de chargement
Back to glossary

CORS (Cross-Origin Resource Sharing)

Security mechanism allowing web servers to control which origins can access their resources through cross-domain HTTP requests.

Updated on January 11, 2026

CORS (Cross-Origin Resource Sharing) is a W3C security standard that allows servers to specify which external origins are permitted to access their resources. This mechanism relies on specific HTTP headers and represents a controlled relaxation of browsers' Same-Origin Policy, enabling modern web applications to function in distributed architectures while maintaining appropriate security levels.

CORS Fundamentals

  • HTTP header-based protocol defined in W3C specification to authorize or block cross-origin requests
  • Preflight system using OPTIONS method to validate complex requests before actual execution
  • Protection against CSRF attacks and unauthorized API access from malicious domains
  • Distinction between simple requests and requests requiring prior validation based on specification criteria

CORS Benefits

  • Enhanced security enabling granular cross-domain access control by origin, method, and headers
  • Facilitated microservices architecture with APIs accessible from different domains in controlled manner
  • Frontend development flexibility allowing SPAs to consume APIs hosted on different domains
  • Developer transparency with clear error messages in browser consoles when requests are blocked
  • Universal standard supported by all modern browsers guaranteeing cross-browser compatibility

Practical Configuration Example

server.ts
// CORS configuration with Express.js
import express from 'express';
import cors from 'cors';

const app = express();

// Basic CORS configuration
const corsOptions: cors.CorsOptions = {
  origin: (origin, callback) => {
    const allowedOrigins = [
      'https://app.example.com',
      'https://admin.example.com'
    ];
    
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  },
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  exposedHeaders: ['X-Total-Count', 'X-Page-Number'],
  credentials: true,
  maxAge: 86400 // 24 hours preflight cache
};

app.use(cors(corsOptions));

// Protected route
app.get('/api/users', (req, res) => {
  res.json({ users: [] });
});

// Manual handling for specific routes
app.options('/api/admin/*', cors({
  origin: 'https://admin.example.com',
  methods: ['GET', 'POST', 'DELETE']
}));

CORS Implementation

  1. Identify legitimate origins that should access your resources and avoid wildcards (*) in production
  2. Configure Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers headers
  3. Set Access-Control-Max-Age to optimize performance by caching preflight responses
  4. Enable Access-Control-Allow-Credentials only when necessary and never with origin wildcard
  5. Implement proper OPTIONS request handling for preflight checks
  6. Test configuration with different scenarios including simple and complex requests
  7. Monitor CORS errors in production to detect configuration issues or unauthorized access attempts

Security Best Practice

Never configure CORS with origin: '*' and credentials: true simultaneously. This combination is rejected by browsers and constitutes a major security flaw. In production, always explicitly list authorized origins and use a dynamic whitelist if needed. For public APIs, prefer token-based authentication over cookies to avoid CORS issues related to credentials.

  • cors (npm) - Express/Connect middleware for Node.js with flexible configuration
  • @fastify/cors - Optimized CORS plugin for Fastify framework
  • django-cors-headers - Django package for CORS management in Python applications
  • rack-cors - Rack middleware for Ruby/Rails applications
  • Spring CORS Configuration - Native support in Spring Boot with annotations
  • Browser DevTools Network Tab - CORS headers inspection and preflight debugging
  • CORS Anywhere - Proxy service for testing and bypassing CORS in development

Mastering CORS is essential for any modern distributed web architecture. Proper configuration ensures security while enabling the interoperability required for microservices applications and SPAs. Investment in a well-defined CORS policy reduces vulnerabilities, improves performance through preflight caching, and facilitates maintenance by explicitly documenting authorized access between services.

Themoneyisalreadyonthetable.

In 1 hour, discover exactly how much you're losing and how to recover it.