Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb session store in Expressjs 4

In express 3 I use connect-mongo for session store.

var mongoStore = require('connect-mongo')(express);

But after I switched to express 4 it doesn't work. I got this error:

Error: Most middleware (like session) is no longer bundled with Express and must be       installed separately. Please see https://github.com/senchalabs/connect#middleware.

I see connect has been removed from express 4. How can I continue use this or are there any good libs that I can use for express 4. Thanks.

like image 570
Junyu Wu Avatar asked Apr 19 '14 11:04

Junyu Wu


People also ask

Where is session data stored in express-session?

Session data is stored server-side. Note Since version 1.5. 0, the cookie-parser middleware no longer needs to be used for this module to work. This module now directly reads and writes cookies on req / res .

How do I save a session in express?

Background: Normally express-session saves the session at the end of each http response, i.e. when the route is finished. However it's possible to save a session at any time with req. session. save() .

What is MongoDB session store?

MongoDBStore. This module exports a single function which takes an instance of connect (or Express) and returns a MongoDBStore class that can be used to store sessions in MongoDB.

What is express-session store?

To store confidential session data, we can use the express-session package. It stores the session data on the server and gives the client a session ID to access the session data. In this article, we'll look at how to use it to store temporary user data.


1 Answers

You need to install the express-session package separately now. It can be found at https://github.com/expressjs/session

Use the following commands to get up and running:

npm install --save express-session cookie-parser

and then in your server.js file:

var express = require('express'),
    cookieParser = require('cookie-parser'),
    expressSession = require('express-session'),
    MongoStore = require('connect-mongo')(expressSession),
    app = express();

app.use(cookieParser());
app.use(expressSession({
     secret: 'secret',
     store: new MongoStore(),
     resave: false,
     saveUninitialized: true
}));

And enjoy

like image 59
Mike Avatar answered Oct 18 '22 11:10

Mike