How can I configure CORS for my new API?
Asked by
~archway
Hey everyone! I'm pretty new to frontend development and I'm trying to figure out a CORS issue that's come up while working on an Angular frontend with a backend REST API. Currently, my frontend is running on app.old.com and the old API is at api.old.com, both of which were on the same site. Now, I'm attempting to move the API to api.new.com, which makes it cross-origin and causes issues with the session cookie for authentication. Since I don't have access to the frontend's domain, I'm wondering if there's a way to allow cross-origin requests from the frontend, and what steps I need to take to make that happen. Can anyone explain it in simple terms?
Answers
CORS is something you control on the backend. If you set the proper CORS headers on api.new.com to allow requests from app.old.com, it should work just fine. There's no need to change anything on the frontend for CORS specifically.
Reply to this answer
You might want to check out this [MDN article](https://developer.mozilla.org/en-US/docs/Web/HTTP/GUIDES/Cookies) on cookies. It covers a lot of helpful information about how they work with CORS and other issues.
Reply to this answer
Your backend needs to set the `Access-Control-Allow-Origin` to the frontend's origin and also include `Access-Control-Allow-Credentials: true`. Make sure all cookies are set with the right origin, and for any requests, youโll need to use `fetch(url, { credentials: 'include' })`, or set `crossorigin="use-credentials"` for scripts and images.
~archway: Thanks for the info! So, I have to use the "credentials" parameter for every request to the API, right? That should be doable since most of our requests go directly to it.
Reply to this answer
I faced a similar issue using Express. To make `credentials: true` work, I had to specify the origins explicitly since using '*' wouldn't be allowed. I fixed this by using a function to determine the allowed origins. Here's a link to the relevant code: [Code Sample](https://github.com/aymericzip/intlayer/blob/a407f8d9f988eafbf06fb0ec8f6db33abf035a24/apps/backend/src/index.ts#L98)
+use the side entrance: Awesome, thanks for sharing the code sample!
Reply to this answer
Add your answer
Answers are reviewed before publication.
~archway: I guess I should read through that, but honestly, I'm just trying to get this done without diving into too much documentation right now!