Flame Stinger
Flame Stinger

Reputation: 139

Express: implementing MongoDB session store

Currently, I am requiring and defining options for express-session at the top of index.js as follows:

const session = require(`express-session`)({
    secret: `MyEpicSecret`,
    resave: true,
    saveUninitialized: true,
    cookie: {maxAge: 1000 * 60} // 1 minute: for testing
}),

and I use it with my express app:

app.use(session);

This layout is important because I later pass session to my socket.io module at the bottom of index.js:

require(`./modules/socket.js`)(server, session);


With the above design flow, my app functions as it should and sessions are handled and managed flawlessly. My goal now is to implement connect-mongo for saving sessions to a MongoDB. Their documentation is a little hazy, but from what I could understand I need to require the express-session module first then define the options to use later inside app.use(). This is an issue - if I define options inside app.use() I am no longer able to pass the configured session (it's options) when I require my socket.js module.

Would I would like to do do is something like:

const session = require('express-session')({
    secret: `MyEpicSecret`,
    resave: true,
    saveUninitialized: true,
    cookie: {maxAge: 1000 * 60}, // 1 minute: for testing
    store: new MongoStore(options)
});
const MongoStore = require('connect-mongo')(session);

app.use(session);

This is not possible - MongoStore is not defined at the time I try to use it. If I move MongoStore up, session will be undefined when i require MongoStore.

I am still learning the ropes with express and would much appreciate the help that anyone is able to provide :)

Upvotes: 1

Views: 290

Answers (2)

Ben Fortune
Ben Fortune

Reputation: 32137

You can still assign the result of the session({...}) call to a variable and pass that around.

const expressSession = require('express-session');
const MongoStore = require('connect-mongo')(expressSession);

const session = expressSession({
    secret: `MyEpicSecret`,
    resave: true,
    saveUninitialized: true,
    cookie: {maxAge: 1000 * 60}, // 1 minute: for testing
    store: new MongoStore(options)
});

app.use(session);
...
require(`./modules/socket.js`)(server, session);

Upvotes: 1

TonyB
TonyB

Reputation: 31

Try this:

 const session = require('express-session');
 const MongoStore = require('connect-mongo')(session);

 app.use(session({
    secret: `MyEpicSecret`,
    resave: true,
    saveUninitialized: true,
    cookie: {maxAge: 1000 * 60} // 1 minute: for testing
    store: new MongoStore(options)
 }));

Upvotes: 1

Related Questions