Pass cookies with axios or fetch requests · Code with Hugo | axios credentials include
PasscookieswithrequestsinaxiosInaxios,toenablepassingofcookies,weusethewithCredentials:trueoption.WhichmeanswecancreateanewaxiosinstancewithwithCredentialsenabled:consttransport=axios.create({withCredentials:true})transport.get(/cookie-auth-protected-route).then(res=>res.data).catch(err=>{/*nothitsinceno401*/})It’salsopossibletosetitintherequestoptions:axios.get(/cookie-auth-protected-route,{withCredentials:true}).then(res=>res.data).catch(err=>{/*nothitsinceno401*/})Oroverrideth...
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: true } ) .then(res => res.data) .catch(err => { /* not hit since no 401 */ })Or override the global defaults:
axios.defaults.withCredentials = true Pass cookies with requests using fetchThe equivalent with fetch is to set the credentials: include or credentials: same-origin option when sending the request:
fetch( /cookie-auth-protected-route, { credentials: include } // could also try same-origin ).then(res => { if (res.ok) return res.json(...