Search code examples
node.jsexpressexpress-session

express-session failed to persist session


I encoutered a tricky issue ,In a Nodejs express web app, Express-session middle is not able to persist the reference type object across multiple sessisons while it works for primitive type value.

Say I have have following code block: cachedFunc(reference type) is always undefined across sessions but cachedText(primitive type) holds the value.

I even tried to deeply copy cacheFun ,which still can not be persisted

Thanks for help!

const _ = require("lodash");
const express = require("express");
const sessionMiddleWare = require("express-session");
const app = express();

app.use(
  sessionMiddleWare({
    name: "dzbSessionId",
    secret: "keyboard cat",
    cookie: { maxAge: 66660000 },
    resave: false,
    saveUninitialized: true
  })
);


app.get("/exam",  (req, res, next) => {
  console.info(req.session.cachedText);/*Primitive Types can be persistent */
  if (!req.session.cachedFunc/*always undefined here for referenced value*/) {
    try {
      req.session.cachedFunc = function(){};
      /*even the copied one still can't work*/
      //req.session.cachedFunc = _.cloneDeep(function(){});
      req.session.cachedText += "freeText";
    } catch (e) {}
  }
  }


Solution

  • This issue is fixed which results from the fact function is not a valid part of JSON specification so that JSON.parse & JSON.stringify will process it.