'Storing sessions with express-session, connect-mongo, and mongoose

I am looking for guidance on setting up session based authentication with with Express-Session, connect-mongo, and Mongoose. Currently it's just generating a new UUID with every request and not saving anything to the sessions collection. Am I missing something obvious?

index.js

const mongoose = require("./db/connection");
const express = require("express");
const cors = require('cors')
const session = require('express-session')
const MongoStore = require("connect-mongo");
const app = express();
const { v4: uuidv4 } = require('uuid');

//Register .env file
require('dotenv').config()


//Middleware
app.use(express.json());
app.use(session({
  genid: (req) => {
    return uuidv4()
  },
  secret: process.env.EXPRESS_SESSION_SECRET,
  resave: true,
  saveUninitialized: false,
  cookie: { maxAge: 24 * 60 * 60 * 1000 },
  store: MongoStore.create({
    client: mongoose.connection.getClient(),
    dbName: process.env.MONGO_DB_NAME,
    collectionName: "sessions",
    stringify: false,
    autoRemove: "interval",
    autoRemoveInterval: 1
    })
  }) 
);

connection.js

const mongoose = require("mongoose");
require('dotenv').config()

mongoose.connect(`mongodb://devroot:devroot@localhost:27017/${process.env.MONGO_DB_NAME}?authSource=admin`, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false,
  useCreateIndex: true
});


mongoose.connection
  .on("open", () => console.log("The goose is open"))
  .on("close", () => console.log("The goose is closed"))
  .on("error", (error) => {
    console.log(error);
    process.exit();
  })

module.exports = mongoose;


Solution 1:[1]

The setting saveUninitialized: false means that a session is established only if it contains some information, that is, if a statement like req.session.attribute = "value" is executed during request processing. If that does not happen, the session is not stored, and also no session cookie issued, so that the next request triggers a new session (with a new UUID), but which may again not be stored.

The author probably "solved" the issue by setting saveUninitialized: true, but this has the following consequences:

  • Every visitor to the website creates a new session entry (without any information in it) in the database even if they never interact with the site nor log on.
  • Every visitor gets a session cookie in their browser even before actually logging on.

I consider both these consequences undesirable and would therefore prefer saveUninitialized: false so that sessions without information are effectively not created.

Solution 2:[2]

Posting for visibility; this was related to:

saveUninitialized: false

Changing this to true forces save to the store.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Parakoopa