axios: Can not send cookie back from client, tried many ways
Summary
I’m new user from nodejs (expressjs) and axios too and I have a problem. I set cookie from nodejs server with:
app.use(cors({
origin: 'http://localhost:2000'
credentials: true
}));
res.cookie('refresh_token', refresh_token, {
maxAge: 30 * 24 * 60 * 60 * 1000,
httpOnly: true,
sameSite: 'strict'
});
I can see response cookie from browser but in storage I can not see. I use res.header do the same, nothing happen. httpOnly: false does not work. And in client I try:
const instance = axios.create({
withCredentials: true,
baseURL: 'http://127.0.0.1:5000',
headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'},
credentials: 'include',
})
instance.post(
'/users/def/refresh_token',
{"access_token":"ABC"}
)
I can not find other ways to do this, every result I got in google do this but I dont know why that not working for me. With Postman it automatic send cookie every request. Please help me!
Environment
- API: http://localhost:5000
- Front end: http://localhost:2000
- Axios Version: 0.27.2
- Browser: Chrome 101.0.4951.64 (Official Build) (64-bit)
- Node.js Version: v12.13.0
- OS: Ubuntu 20.4
- Additional Library Versions: Reactjs 17.0.2
About this issue
- Original URL
- State: open
- Created 2 years ago
- Comments: 24
Yes, it is not working. Cookie is set but value is empty…
[Edit]: Ok it is working. In my case I forgot to add “withCredentials: true” also to login request. After that everything started to work.
thanks for this it worked, i missed to add
credentials: 'include'
in mylogin
fetch
requestIn production I got the same issue. The cookie was not set by the browser, I tryed a lot of possible solutions but what solve my problem was change the domain name. I deployed my API as server.mydomain.com and my frontend was anotherdomain.app and CORS was properly configured. I was able to send request to ‘open’ routes, but when I tried to login the cookie was ignored by the browser. So, when I changed the frontend to mydomain.com the cookie was set perfectly.
👋 Hey everyone, I was also struggling with same issue, and now I found the answer, I hope this will fix your as well.
Server side
app.use(cors({origin: <your_client_url> , withCredentials: true})
res.send(<cookie_name>, <cookie_value>,
{ httpOnly: true,
// true if don’t want to access cookie via js on client sidesecure : true,
// mandatory with sameSite:none propertysameSite: "none",
// mandatory to set if client and server are on different domainsmaxAge: <your_desired_cookie_expiry_time>,
path: "/"
// must set path “/” here})
Client side
export const baseAPI = axios.create({
baseURL:
${API_URL},
withCredentials: true,
// mandatory to set true});
I hope this will solve the issue, as it solved for me struggling for loooooooong time🎯
using sameSite:“none” fixed my issue, Thanks.