Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

714
Vistas
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;
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar

0

Posting for visibility; this was related to:

saveUninitialized: false

Changing this to true forces save to the store.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda