I had a problem with CORS with node and angular and adding this option with true solved my problem. But I don't find info about what it is and what it is doing. Please can someone explain?
-
Can you not use withCredential and share a screenshot of your console CORS error? – Ben Diamant Dec 10 '14 at 17:26
-
Its not an error, it doesnt save me the session variables between pages. – Dec 10 '14 at 17:35
2 Answers
Short answer:
withCredentials()
makes your browser include cookies and authentication headers in your XHR request. If your service depends on any cookie (including session cookies), it will only work with this option set.
Longer explanation:
When you issue an Ajax request to a different origin server, the browser may send an OPTIONS pre-flight request to the server to discover the CORS policy of the endpoint (for non-GET requests).
Since the request may have been triggered by a malicious script, to avoid automatically leaking authentication information to the remote server, the browser applies the following rules :
For GET requests, include cookie and authentication information in the server request :
- if XHR client is invoked with the
withCredentials
option is set to true - and if the server reply does not include the CORS header
Access-Control-Allow-Credentials: true
, discard response before returning the object to Javascript
For non GET requests, include cookie and authentication information only:
- if
withCredentials
is set to true on the XHR object - and the server has included the CORS header
Access-Control-Allow-Credentials: true
in the pre-flight OPTIONS

- 3,395
- 1
- 21
- 23

- 6,717
- 1
- 19
- 21
-
-
1@rluta - my angular application is not returning authentication cookie even though I have set `withCredentials` to `true`. Could you please take a look at https://stackoverflow.com/questions/50076352/angular-is-not-sending-the-cookie-received-in-set-cookie – Manu Chadha Apr 30 '18 at 16:15
-
but any malicious script can also set the withCredentials option to be true, seems it does not that important... – vancewang May 22 '20 at 10:05
-
My angular application is returning a cookie with different name/value : [how-to-decode-credentials-sent-using-withcredentials-true-from-angular-cookie](https://stackoverflow.com/questions/66965054/how-to-decode-credentials-sent-using-withcredentials-true-from-angular-cookie) can someone check the possibles reasons ? – HDJEMAI Apr 19 '21 at 22:35
-
How about the peculiar case : Api is the same server for dev/QA environment but different for uat/production[CORS] environment. – Shalem Feb 07 '22 at 06:56
Short answer from Axios documentation
withCredentials
indicates whether or not cross-site Access-Control requests should be made using credentials
Credentials are cookies, authorization headers or TLS client certificates Reference
Default value of withCredentials
is false

- 13,461
- 8
- 60
- 73