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:

  1. Use the credentials: 'include' option in your fetch() 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 the XMLHttpRequest.withCredentials property to true.
  2. 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 in Access-Control-Allow-Origin instead of the wildcard (*).
  3. Only SameSite=None cookies will be sent in the client requests and any Strict or Lax cookies will be ignored. Similarly only cookies with SameSite=None; Secure; in the HTTP response will be delivered and stored.

Leave a Reply

Your email address will not be published. Required fields are marked *