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: closed
  • Created 4 years ago
  • Comments: 31

Most upvoted comments

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.

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.

that helped thanks

👋 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

    • Use cors with following configuration
    • CORS config: app.use(cors({origin: <your_client_url> , withCredentials: true})
    • Sending cookie: res.send(<cookie_name>, <cookie_value>, { httpOnly: true, // true if don’t want to access cookie via js on client side secure : true, // mandatory with sameSite:none property sameSite: "none", // mandatory to set if client and server are on different domains maxAge: <your_desired_cookie_expiry_time>, path: "/" // must set path “/” here })
  • Client side

    • Create axios instance
    • 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🎯

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 my login fetch request

In 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.

For deployment on services like Render or similar platforms, ensure your Express.js application is configured to trust proxies. It worked for me. Below is an example setup:

const express = require('express');
const app = express();

// Trust first proxy
app.set('trust proxy', 1);

// Middleware setup
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Example route
app.get('/', (req, res) => {
  res.send('Hello World');
});

// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

@Gaurav200247 did you try setting same-site: “none” in cookie? eg.

res.cookie("refreshtoken", refreshToken, {
      httpOnly: true,
      sameSite: "none",
      secure: true,
      // maxAge: 24 * 60 * 60 * 1000, // 1 day
      maxAge: 3 * 60 * 1000,

      path: "/api/auth/refresh",
    });

i just implemented a full stack auth in which server and client are on different domains so setting sameSite: “strict” will stop cookie at client side because of different domain.

and cors settings are like this

app.use(
  cors({
    origin: ["http://localhost:5173", process.env.CLIENT_BASE_URL as string],
    methods: ["GET", "POST", "PUT", "DELETE"],
    credentials: true,
  })
);

using sameSite:“none” fixed my issue, Thanks.

thanks, you helped alot