Slayes
Slayes

Reputation: 445

NodeJS - How to disable the Session for a specific route

I would like to disable the session creation for a specific route, as "/app/....";

I tried one way by using the code see below :

pool = mysql.createPool(mysqlOptions);
var sessionConnection = mysql.createConnection(mysqlOptions);
var sessionStore = new MySQLStore(mysqlOptions, sessionConnection);
app.use(function(req, res, next){
  if (!req.path.startsWith("/app/")) 
    session({
      key: 'x',
      secret: 'x',
      store: sessionStore,
      resave: false,
      saveUninitialized: true,
      cookie: {maxAge: moment().endOf('days').diff(moment())} })(req, res, next);
  else
    next();
});

I have the warning message see bellow and after few minutes, the server is not reachable.

MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 disconnect listeners added to [MySQLStore]. Use emitter.setMaxListeners() to increase limit

Could somebody explain me ? Thanks in advance.

Upvotes: 2

Views: 914

Answers (1)

jfriend00
jfriend00

Reputation: 708106

If you put the route declaration BEFORE your session middleware, then the session will not be created for that specific route handler.

app.use("/app", appRouter);   // this will be handled before session is created
app.use(session(...));

If you want to call the session dynamically the way you are in your code, then you should create the session middleware once and then call that dynamically:

pool = mysql.createPool(mysqlOptions);
const sessionConnection = mysql.createConnection(mysqlOptions);
const sessionStore = new MySQLStore(mysqlOptions, sessionConnection);
const sessionMiddleware = session({
      key: 'x',
      secret: 'x',
      store: sessionStore,
      resave: false,
      saveUninitialized: true,
      cookie: {maxAge: moment().endOf('days').diff(moment())} 
});

app.use(function(req, res, next){
  if (!req.path.startsWith("/app/")) 
      sessionMiddleware(req, res, next);
  else
    next();
});

Upvotes: 3

Related Questions