Search code examples
reactjsexpresscorsexpress-session

Session cookie not sending with XHR requests


My react app (from domain react-app.com) is loaded inside a website beautiful-site.com and the requests sending from react app doesn't sending the session cookie associated with it.

The workaround I had was added the below header in server and in react app XHR requests sent with withCredentials: true

Access-Control-Allow-Origin: https://beautiful-site.com
Access-Control-Allow-Credentials: true

The issue is I can specify a particular site in Access-Control-Allow-Origin, because the react app will be added to many sites not one.

Is there any way to get the session cookie send from react app?


Solution

  • Answer is no, but you have workaround: when you set the withCredentials you can't have an Access-Control-Allow-Origin: *.

    The fix must be done server side: your API service must returns domain of the request in the Access-Control-Allow-Origin, commonly taken from the Origin header.

    See No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API (the How to fix “Access-Control-Allow-Origin header must not be the wildcard” problems subsection) for techincal details.