JavaScript Send Cookies for Cross Origin Requests with Fetch API
If you’ve been struggling with sending or receiving cookies with your cross-origin fetch()
requests (CORS), then make sure you’re adhering to each of the following points:
- Use the
credentials: 'include'
option in yourfetch()
calls to include the credentials (cookies, HTTP auth headers, TLS client certificates) in both same-origin and cross-origin requests. Any credentials sent back in the HTTP response will also be used by the browser. If using XHR then set theXMLHttpRequest.withCredentials
property totrue
. - Send the
Access-Control-Allow-Credentials: true
header in the response (for preflight requests as well) which also enforces us to specify the exact origin inAccess-Control-Allow-Origin
instead of the wildcard (*
). - Only
SameSite=None
cookies will be sent in the client requests and anyStrict
orLax
cookies will be ignored. Similarly only cookies withSameSite=None; Secure;
in the HTTP response will be delivered and stored.