How to Create an Express Session with MongoStore

October 6, 2022


Create an Express Session


Install express-session & connect-mongodb-session. In the express app middleware, where going to call the session on every request. The session call takes an object with several options.

Secret, a string that is used to sign(password for the cookie) the cookie.

Resave, a boolean that forces the session to be saved to the store on the request, even if the session wasn't changed.

SaveUnitialized, a boolean that saves a session that is new but not changed, to the store. A session is considered new when the user has not given a key, value pair to the session object.

Name, a string that is the name of the cookie. If you don't give this a value the name of the cookie will be "connect.sid". That makes it easy for hackers when every cookie has the same name.

Store, an object that takes a class(function). The class then takes an object with 2 properties the uri of the mongodb database your going to use & the collection that your going to put the sessions in.

Cookie, an object that takes an options object to create the cookie. More info on this can be found here Create, Get & Delete Cookies with Express Server.

How to create an Express Session


Saving the Session to the Store


For the store we're using mongodb. To save the session to the store, your going to define a property & put a value into it. This works when saveunitialized is false, if true then every session on request will be saved to the store.

Saving a session back to the store

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.