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.
- Example:
- 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"
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;
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();
});
Best Practices
- 📌 Always specify exact domains instead of using
*
for production. - 🔒 Validate and sanitize input data to prevent header injection attacks.
- ⚠️ Avoid exposing sensitive headers (e.g.,
Cookie
,Authorization
) unless necessary. - 📈 Use HTTP status codes properly for pre-flight responses.
Related Resources
For deeper insights into security best practices, visit our Security Best Practices guide.