Search code examples
javascriptnode.jsexpressexpress-session

cannot use "Set" in a session variable express


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 {}.


Solution

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