Introduction

CORS (Cross-Origin Resource Sharing) is a security mechanism that allows web applications to make requests to a different domain than the one they originated from. It is essential for enabling secure communication between frontend and backend services while preventing malicious cross-origin requests.

To ensure proper CORS settings, you must configure the appropriate headers on your server. Below are key concepts and examples for implementation.


Key Concepts

  • Origin: The domain of the requesting resource (e.g., https://example.com).
  • Access-Control-Allow-Origin: Specifies which origins are permitted to access the resource.
    • Example: Access-Control-Allow-Origin: https://frontend.example.com
    • ✅ Use a specific domain for stricter security.
  • Access-Control-Allow-Methods: Lists allowed HTTP methods (e.g., GET, POST, PUT).
  • Access-Control-Allow-Headers: Defines headers that can be used in the request (e.g., Content-Type, Authorization).
  • 🚫 Pre-flight Requests: A OPTIONS request sent before actual requests to check CORS policies.

Configuration Examples

For Apache

Add the following to your .htaccess or Apache config file:

Header set Access-Control-Allow-Origin "https://frontend.example.com"
Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header set Access-Control-Allow-Headers "Content-Type, Authorization"
CORS Apache Configuration

For Nginx

Configure in your server block:

add_header 'Access-Control-Allow-Origin' 'https://frontend.example.com' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization' always;
CORS Nginx Configuration

For Node.js (Express)

Use middleware:

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'https://frontend.example.com');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  next();
});
CORS Node.js Configuration

Best Practices

  1. 📌 Always specify exact domains instead of using * for production.
  2. 🔒 Validate and sanitize input data to prevent header injection attacks.
  3. ⚠️ Avoid exposing sensitive headers (e.g., Cookie, Authorization) unless necessary.
  4. 📈 Use HTTP status codes properly for pre-flight responses.

Related Resources

For deeper insights into security best practices, visit our Security Best Practices guide.


CORS Overview