Home > Software design >  Mobile Google Chrome not sending the cookies
Mobile Google Chrome not sending the cookies

Time:11-03

I wrote a simple Express.js server which only sets a cookie named hello-world and returns the request headers. Here is the code:

const app = require('express')()

app.get('/', (req, res) => {
  res.cookie('hello-world', 'this-is-the-value-of-cookie')
  res.json(req.headers)
})

app.listen(80, '0.0.0.0')

The problem is that mobile Google Chrome dose not send the cookies in the first request. Here is a demo of it: https://file.io/OIilmHoA2IKK

In the demo, I use the Android Studio's emulator and nip.io wildcard DNS. I simply start the Express.js server on my local machine and then access it via http://10.0.2.2.nip.io

As you can see in the demo, I first open the page and refresh to make sure hello-world cookie is set. Then I close Google Chrome and reopen it again. But the first time I open the page, there is still no hello-world cookie.

What did I do wrong here? I want the hello-world cookie be sent even in the first request after browser restarts.

CodePudding user response:

It is not entirely clear from you code snippet, but I assume that you are creating a session cookie instead of a persistent cookie. Therefore the cookie is gone, when you close and reopen the browser.

You can create a persistent cookie by adding an expiration date to your cookie value. Your cookie will be stored until it expires (or is deleted by the user). That date parameter has to be formatted as a UTC string. You could do it like this:

res.cookie('hello-world', 'this-is-the-value-of-cookie; expires='   (new Date(2030, 0).toUTCString()));
  • Related