I'm new to frontend development and I'm trying to salvage an Angular frontend that communicates with a REST API. Currently, the frontend is at app.old.com and the API is at api.old.com, using a session cookie for authentication. I need to migrate the API to api.new.com, which introduces a cross-site issue because the origins will now be different. I need to know how to configure the frontend to handle CORS correctly. Can someone explain this to me in simple terms?
5 Answers
Your backend needs to include the `Access-Control-Allow-Origin` header set to your frontend's origin, and also `Access-Control-Allow-Credentials: true`. For requests involving cookies, use `fetch(url, { credentials: 'include' })` in your frontend code. This will ensure the cookies are included with requests to the API.
CORS is mainly a backend issue. To make it work after moving your API, you'll need to set the appropriate CORS headers on api.new.com to allow requests from app.old.com. There's no need for any front-end configuration on this part.
I faced a similar issue with Express before. When setting `credentials: true`, you can't just use a wildcard '*' for origins. You need to provide a function to define which origins are allowed. Here's a snippet explaining that.
Check out this link for more detailed info about cookies: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Cookies. It’s all pretty informative!
Thanks for the clarification! So I really need to add the "credentials" option for every request going to the API, right? That makes sense since almost all requests are API calls anyway.