To achieve user authentication and maintain state with cookies between a web app and a backend on different domains, you need to address the issues related to Cross-Origin Resource Sharing (CORS), SameSite, and HTTPS/HTTP. Here are some steps you can take to achieve this:
CORS Approach:
On the backend (server) side, you need to set the following HTTP headers:
Access-Control-Allow-Credentials - Set the value to true.
Access-Control-Allow-Origin - Set this header to the specific domain that the web app is running on, including the scheme (e.g., https://domain1.com).
Access-Control-Allow-Headers - Set this header to the necessary headers for the request (e.g., Content-Type, Authorization, x-csrf-token).
Additionally, you should set the following cookie settings:
SameSite=None
Secure
On the client-side, set the XMLHttpRequest.withCredentials flag to true:
For ES6 fetch(), use credentials: 'include'.
For jQuery 1.5.1, use xhrFields: { withCredentials: true }.
For Axios, use withCredentials: true.
Proxy Approach:
Instead of dealing with cross-site (CORS) issues, you can use a proxy to route all traffic to the same top-level domain name. This can be achieved using DNS (subdomain) and/or load balancing. Tools like Nginx can help with this approach.
This approach aligns well with the JAMStack architecture, where the API and web app code are decoupled. By serving the API and web app on the same host, you can avoid the cross-site/CORS problems.