How do I handle CORS when moving my API to a new domain?

0
1
Asked By CuriousCoder92 On

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

Answered By CodeWizard77 On

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.

CuriousCoder92 -

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.

Answered By TechyDave22 On

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.

Answered By DevDude98 On

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.

Answered By CuriousCoder92 On
Answered By HelpfulHarry On

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!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.