A new React frontend could not communicate with the Magento REST API. Every AJAX request ended with a CORS error in the browser console. The backend worked correctly when tested through Postman or curl. Fix time: 2 hours.
Symptoms
- Browser console:
Access to fetch has been blocked by CORS policy - Preflight OPTIONS request returns no
Access-Control-Allow-Originheader - API works via Postman and curl – problem only in the browser
- Frontend on a different domain than the Magento API
Solution
location /rest/ {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' 'https://frontend.shop.com' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type, X-Requested-With' always;
add_header 'Access-Control-Max-Age' 86400;
return 204;
}
add_header 'Access-Control-Allow-Origin' 'https://frontend.shop.com' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
try_files $uri $uri/ /index.php?$args;
}
Takeaways
CORS must be configured server-side – the browser requires explicit permission from the API. Do not use Access-Control-Allow-Origin: * with Access-Control-Allow-Credentials: true – the browser will block it. Always specify concrete frontend domains on the whitelist.
