CORS (Cross-Origin Resource Sharing) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain of the web page. It's essential for enabling secure communication between frontend and backend services across different origins.
How CORS Works 🔍
- Browser Request
When a frontend makes a request to a different origin, the browser automatically includes anOrigin
header. - Server Response
The backend must respond with appropriate CORS headers like:Access-Control-Allow-Origin
(specifies allowed origins)Access-Control-Allow-Methods
(lists allowed HTTP methods)Access-Control-Allow-Headers
(defines allowed request headers)
- Pre-flight Requests
For non-simple requests (e.g.,PUT
,DELETE
), browsers send anOPTIONS
pre-flight check.
CORS Configuration 🔧
- Node.js (Express)
app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); });
- Nginx
Add to server block:add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
- Apache
Use.htaccess
:Header set Access-Control-Allow-Origin "*"
Common Issues ⚠️
- 403 Forbidden
Indicates missingAccess-Control-Allow-Origin
header. - Preflight Failure
Check ifOPTIONS
request is properly handled. - Header Mismatch
EnsureAccess-Control-Allow-Headers
matches client request headers.
For deeper insights into implementing CORS in your project, check out our Cross-Origin Resource Sharing Configuration guide.