Cookies.get("token") not working after deployment

I have client deployed on [project_name].vercel.app and server on [project_name]-api.vercel.app
I’m logged in and on frontend side I see httpOnly cookie ‘token’, but then in next request ctx.cookies.get(“token”) returns undefined.
The client and server are on different domains, do I need to add something in vercel configuration?
It works without any issues on localhost, client port 5173, server 4000

// Client
const response = await axios.get(API_URL + “/user/me”, {
withCredentials: true,
});
// Server
const Router = require(“@koa/router”);
const cors = require(“@koa/cors”);
const bodyParser = require(“koa-bodyparser”);

app.use(cors({credentials: true,}));
app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());

router.get(“/user/me”, async (ctx) => {
  const token = ctx.cookies.get(“token”);
  // the token is undefined here;
  console.log(“nn”, token);
  ctx.body = ctx.state.user;
});

Hi @piro92, welcome to the Vercel Community!

I think you’re on the right track but missing some of the configurations. This is not a Vercel issue but more of a web standards thing:

Could you share the code where you set the cookie? By default, your web server will set the cookie on the same domain the request was received. I think your configuration for SameSite or domain is the issue.

I found this insightful discussion on Reddit on this topic. In addition to this, I’d recommend reading up on the Using HTTP cookies - HTTP | MDN for cross domain cookies.

Thank you for the reply:
I use koa for the api and when I set a cookie:
ctx.cookies.set("token", token);
I see the cookie in the browser with httpOnly true flag, but when I tried to add SameSite config:
ctx.cookies.set("token", token, { sameSite: "none", });
The cookie is not created in the browser.

I see. There are a few key things to note here, can you confirm all these conditions are met?

SameSite=None

Required for cross-domain cookies. Must be paired with Secure flag.

Secure Flag

Cookies must be sent over HTTPS only (secure: true). Required when using SameSite=None.

credentials: “include”

Frontend must explicitly include credentials in fetch requests.

CORS Headers

Backend must set Access-Control-Allow-Origin and Access-Control-Allow-Credentials.

HttpOnly

Prevents JavaScript access to cookies, protecting against XSS attacks.

Thank you for the help.

I added option:
secureProxy: true,

and the problem is solved.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.