Pass cookies with axios or fetch requests | axios credentials include
Whensendingrequestsfromclient-sideJavaScript,bydefaultcookiesarenotpassed.Bydefault,fetchwon’tsendorreceiveanycookiesfromtheserver,resultinginunauthenticatedrequestshttps://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch[1]TwoJavaScriptHTTPclientsIuseareaxios[2],a“PromisebasedHTTPclientforthebrowserandNode.js”andthefetchAPI(seeFetchAPIonMDN[3]).PasscookieswithrequestsinaxiosInaxios,toenablepassingofcookies,weusethewithCredentials:trueoption.Whichmeanswecancreateanewaxiosinstan...
When sending requests from client-side JavaScript, by default cookies are not passed.
By default, fetch won’t send or receive any cookies from the server, resulting in unauthenticated requests https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch[1]
Two JavaScript HTTP clients I use are axios[2], a “Promise based HTTP client for the browser and Node.js” and the fetch API (see Fetch API on MDN[3]).
Pass cookies with requests in axiosIn axios, to enable passing of cookies, we use the withCredentials: true option.
Which means we can create a new axios instance with withCredentials enabled:
const transport = axios.create({ withCredentials: true }) transport .get(/cookie-auth-protected-route) .then(res => res.data) .catch(err => { /* not hit since no 401 */ })It’s also possible to set it in the request options:
axios .get( /cookie-auth-protected-route, { withCredentials...