0

I was trying to use Set as a session value, but for some reason I got this unexpected result. I'm making two requests from the client to this route.

app.post("/api/add_to_cart", (req, res) => {
    console.log(req.session.productList);
    if (req.session.productList === undefined)
        req.session.productList = new Set();
    console.log(req.session.productList);
    req.session.productList.add('one');
    console.log(req.session.productList);
    res.send();
});

output:

undefined
Set(0) {}
Set(1) { 'one' }

{}
{}
TypeError: req.session.productList.add is not a function

But if I use array insted of Set it works as expected

app.post("/api/add_to_cart", (req, res) => {
    console.log(req.session.productList);
    if (req.session.productList === undefined)
        req.session.productList = [];
    console.log(req.session.productList);
    req.session.productList.push('one');
    console.log(req.session.productList);
    res.send();
});

output:

undefined
[]
[ 'one' ]

[ 'one' ]
[ 'one' ]
[ 'one', 'one' ]

For some unknown reason the Set object is being changed to {}.

Anupam Minz
  • 125
  • 1
  • 7
  • Which [store implementation](https://www.npmjs.com/package/express-session#compatible-session-stores) are you using? How does it serialise and deserialise session state? – Bergi Jun 14 '21 at 12:31
  • Every thing is set to default, I have not added any store implementation. It's just what you see and the initilization with only the secret – Anupam Minz Jun 14 '21 at 14:07

1 Answers1

0

From the docs:

req.session

To store or access session data, simply use the request property req.session, which is (generally) serialized as JSON by the store, so nested objects are typically fine.
(highlighting mine)

…and Sets/Maps do not support JSON (de)serialisation out of the box.

The builtin development-only MemoryStore does this as well.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375