Search code examples
node.jssessionsession-variablesstoreexpress-session

How to call 'store' commands with 'express-session'?


I am using Node.js/Express with the 'express-session' module for session management. My setup is as follows:

var session = require('express-session');
var MemoryStore = require('memorystore')(session)
const express = require('express');
const app = express();

app.use(session({
 cookie: { maxAge: 86400000 },
 store: new MemoryStore({
   checkPeriod: 86400000 // prune expired entries every 24h
 }),
 resave: false,
 saveUninitialized: false,
 unset: 'destroy',
 secret: process.env.COOKIE_SECRET
}))

My question is simple...how do I call the 'store' commands (for example ".all", ".destroy", ".length", etc)...? I have attempted at least the following:

session.store.all(function(error, len) {console.log("EXECUTED MEMORYSTORE LIST: ");})
MemoryStore.all(function(error, len) {console.log("EXECUTED MEMORYSTORE LIST: ");})
store.all(function(error, len) {console.log("EXECUTED MEMORYSTORE LIST: ");})

...Nothing of which works...I always get a "not a function" error thrown. I would like to access these commands to enable cycling through the sessions in the store, deleting as necessary, and other misc tasks.

Any advice on how to access these 'store commands' would be greatly appreciated. I thank you in advance.


Solution

  • If you want access to the MemoryStore interface for that module, then you just have to save the instance to your own variable:

    const memoryStore = new MemoryStore({
       checkPeriod: 86400000 // prune expired entries every 24h
    });
    
    app.use(session({
     cookie: { maxAge: 86400000 },
     store: memoryStore,
     resave: false,
     saveUninitialized: false,
     unset: 'destroy',
     secret: process.env.COOKIE_SECRET
    }));
    

    Now, you have access to the instance of the memoryStore and you can access whatever methods it has. You can see what methods it offers in the code here. It's implementation is really just in service of the express-session store interface - it is not meant as a separately accessible database, but you can call the methods from the express-session store interface.

    Keep in mind that the tasks you ask about are better served by using a session store that is a real database and has a real database interface. Then, you can use the regular database interface to access previously store session data.