Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

715
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda