Sophia
Sophia

Reputation: 55

Chrome doesn't save Express cookie in React app

I am receiving cookies from my Express app with no warnings, however the cookie never gets stored (confirmed via Chrome dev tools).

I have setup a React app and express API:

api: https://api.mycompany.com (express: 4.17.1)

app: https://app.mycompany.com (react 17.0.2 with superagent HTTP lib.)

In my React code I'm making a request to https://api.mycompany.com/get_cookie:

// setup the agent ...
const agent = request
      .agent()
      .use(prefix('https://api.mycompany.com'))
      .set('Content-Type', 'application/json');

// make the request (confirmed response OK)
await agent
      .post('/get_cookie')
      .send(queryParams)
      .withCredentials();

I see the cookie in the response headers (with no warnings!)

Set-Cookie: my_token=<token-content>; Max-Age=604800; Path=/; Expires=Sat, 21 Aug 2021 14:17:13 GMT; Secure; SameSite=None

On my server (https://api.mycompany.com):

Setup CORS

app.use(cors({
  origin: true, // reflect request origin
  credentials: true
}));
app.options('*', cors());  // enable pre-flight?

Send the cookie

// from /get_cookie:

res.cookie('my_token',
  JSON.stringify(<token-content>),
  {
    maxAge: 10 * 60_000, // 10 mins
    httpOnly: false,
    signed: true,
    secure: true,
    sameSite: 'none'
  });

Having a really hard time with this one and at a bit of a loss 😭 Why doesn't my browser store the cookie? I've tested in Firefox and I have the same problem. Any help would be much appreciated!!

Requests

No cookies

Cookie received

Upvotes: 1

Views: 1268

Answers (1)

Sophia
Sophia

Reputation: 55

I moved the withCredentials() call to the agent itself. For some reason, this did the trick:

const agent = request
      .agent()
      .use(prefix('https://api.mycompany.com'))
      .set('Content-Type', 'application/json')
      .withCredentials();

Upvotes: 1

Related Questions