Utilizing express-session and passport to initiate a new session for each request

Currently working on developing an e-commerce platform, both front and back-end. Using express and passport for a basic login/register system. The issue I'm facing is that every time a page with a request is accessed, a new session is created and stored in MongoDB server, resulting in multiple sessions being created as I navigate through different sections of the site.

The goal is to have sessions created ONLY after user authentication.

Below is a snippet of my code:

app.js:

import express from "express"
import mongoose from "mongoose"
import { Server } from "socket.io"
import { boxRouter } from "./routes/box.router.js"
import { productRouter } from "./routes/product.router.js"
import { cartRouter } from "./routes/cart.router.js"
import { userRouter, isLoggedIn } from "./routes/user.router.js"
import passport from "passport"
import initializePassport from "./passport.config.js"
import cors from 'cors'
import MongoStore from "connect-mongo"
import cookieParser from "cookie-parser"
import session from "express-session"

// const hostname = '0.0.0.0'
// const port = '10000'

export var app = express()
// const httpServer = app.listen(port, hostname, ()=>{ console.log("Server Up")})
const httpServer = app.listen(8080, ()=>{ console.log("Server Up")})
export const socketServer = new Server(httpServer)

app.use(cookieParser("mostsecretsecret"))
app.use(session({
    store: MongoStore.create({
        mongoUrl: 'blablabla',
        mongoOptions: {useNewUrlParser: true, useUnifiedTopology: true},
        ttl: 15
    }),
    cookie:{
        maxAge: 7 * 24 * 60 * 60 * 1000,
    },
    secret: 'mysecret',
    resave: true,
    saveUnitialized: false
}))
initializePassport()
app.use(passport.initialize())
app.use(passport.session())
app.use(cors())
app.use(express.urlencoded({extended:true}))
app.use(express.json())

app.use('/api/boxes', boxRouter)
app.use('/api/products', productRouter)
app.use('/api/carts', cartRouter)
app.use('/api/users', userRouter)

var connectionString = "blablabla"
mongoose.set('strictQuery', false)
mongoose.connect(connectionString)

socketServer.on('connection', socket=>{
    console.log("Nuevo cliente conectado.")
})

passport.config.js:

import passport from "passport";
import local from 'passport-local';
import { userModel } from './models/user.model.js'
import { createHash, isValidPassword } from "./utils.js";
import { cartManager } from "./managers/CartManager.js";

const LocalStrategy = local.Strategy
const initializePassport = ()=>{
    passport.use('register', new LocalStrategy(
        {passReqToCallback: true, usernameField: 'email'}, async(req, username, password, done)=>{
            const { first_name, last_name, email, newsletter } = req.body
            try{
                let user = await userModel.findOne({email: username})
                if(user){
                    console.log("El usuario ya existe")
                    return done(null, false)
                }

                let newCart = await cartManager.createCart()
                const newUser = {
                    first_name,
                    last_name,
                    email,
                    password: createHash(password),
                    cartId: newCart.id,
                    newsletter,
                    role: 'user'
                }
                let result = await userModel.create(newUser)
                return done(null, result)
            }catch(err){
                return done("Error al obtener el usuario: " + err)
            }
        }
    ))
    passport.use('login', new LocalStrategy(
        {usernameField: 'email'}, async(username, password, done)=>{
            try{
                const user = await userModel.findOne({email: username})
                if(!user){
                    console.log("El usuario no existe")
                    return done(null, false)
                }
                if(!isValidPassword(user,password)) return done(null, false)
                return done(null, user)
            }catch(err){
                return done(err)
            }
        }
    ))

    passport.serializeUser((user, done)=>{
        done(null, user._id)
    })
    passport.deserializeUser(async(id, done)=>{
        let user = await userModel.findById(id)
        done(null, user)
    })
}

export default initializePassport

user.router.js:

import { Router } from 'express';
import passport from 'passport';

export const userRouter = Router()

export function isLoggedIn(req, res, next){
    if(req.session.user){
        return next()
    }
    return res.status(401).send('Error de autorización.')
}

userRouter.post('/register', passport.authenticate('register', {}), async (req, res)=>{
    try {
        res.send('Success')
    } catch (error) {
        res.status(400).send({
            status: 'error',
            message: error.message
        })
    }
})

userRouter.post('/login', passport.authenticate('login', {}), async (req, res)=>{
    try {
        if(!req.user){
            return res.status(401)
        }
        req.session.user = {
            first_name: req.user.first_name,
            last_name: req.user.last_name,
            email: req.user.email,
            role: req.user.role
        }
        res.send('Success')
    } catch (error) {
        res.status(400).send({
            status: 'error',
            message: error.message
        })
    }
})

userRouter.get('/logout', (req, res)=>{
    try {
        req.session.destroy(err=>{
            if(err) res.status(500)
        })
    } catch (error) {
        res.status(400).send({
            status: 'error',
            message: error.message
        })
    }
    
})

userRouter.get('/check-login', isLoggedIn, (req, res) => {
    try {
        res.status(200).send('Usuario logueado');
    } catch (error) {
        res.status(400).send({
            status: 'error',
            message: error.message
        })
    }
});

After browsing through 3 pages, multiple sessions are created as shown in this image of my database: https://i.sstatic.net/4rki3.png

Answer â„–1

After going through numerous discussions, I managed to resolve the issue.

I made a modification in my app.js file:

const corsOptions = {
    origin: 'http://localhost:3000',
    credentials: true,
}
app.use(cors(corsOptions));

Additionally, I included "withCredentials: true" in all axios requests (although there's an option to set it as default, but that's okay).

let response = await axios.get("http://localhost:8080/api/boxes", {withCredentials: true })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deactivate a Specific Popup for a Specific Page

In my project, I have a file called modal.php that contains two modal windows: Login Modal Feedback Modal The Login Modal automatically pops up every 5 seconds for users who are not logged in. The Feedback Modal opens when clicked. On my website, I hav ...

Utilize Javascript to refine JSON data strings

Currently, I am tackling a small project and facing a minor JS issue. The JSON string that I have looks like this: var jsObj = { "templates": { "form0": { "ID": "MyAlertNew", "isVisible": "true", ...

The live() function is causing issues with my ajax request

Within my webpage, I have a link with an onclick() event that should display a div containing a date input text named "datepicker0", followed by another div with the id of "bContent". I've included the script below to implement a date filter on the d ...

JavaScript does not function properly with dynamically loaded content

Trying to load the page content using the JQuery load() method. See below for the code snippet: $(window).ready(function() { $('#content').load('views/login.html'); }); .mdl-layout { align-items: center; justify-content: center ...

JavaScript library that provides SQL-like functionality for easily manipulating arrays

After successfully parsing a csv file into an array of objects, I find myself in need of making multiple alterations to that array. Currently, I am utilizing lodash methods for this task, but I am finding it to be quite verbose. I am considering working wi ...

Transfer files using Ajax and FormData technique

I have extensively researched various topics on this issue and prefer not to rely on any external plugins. function addToDatabase(menuItem){ var formData = new FormData(); formData.append("Description", document.getElementById("DescriptionID").value); ...

Issue with Node/Express: Middleware addition to router does not function as expected

Here is the configuration of my router: app.get('/getReport', (req, res) => { res.send("This is the report"); }); Initially, this router functions properly and successfully displays the message This is the report in the browser However, ...

Generating an array of objects based on a specified condition

I am working on creating an array of objects. I want to add objects based on a condition, but instead of not adding the object in the array, it is adding false. I have attempted the following: const flag = false; const list = [ { key: 'abc&a ...

Accessing a webpage by directly pasting the URL into the address bar is functioning properly, but is

I'm facing an issue with accessing files from a vendor's application. When I directly enter the endpoints into the browser's address bar, the file opens up without any problems. However, when I try to access them using jQuery AJAX, I receive ...

Can you suggest an optimal way to structure MongoDB documents that frequently experience rapid growth in arrays?

My MongoDB document layout includes 6 top-level property fields that store array data. These arrays store IoT data collected from specific sensors throughout the day, and are updated every 2 seconds. Each new sensor packet appends data to all 6 arrays, pot ...

Implementing local data storage and synchronization in a Flutter application with Node.js and MongoDB: A step-by-step guide

For my Flutter application, I am utilizing Node.js and MongoDB. At the moment, the app is solely pulling data from the server. My goal is to store this retrieved data locally on the device and have the capability to sync it between local and server. Can yo ...

Updating the scope value in AngularJS with an asynchronous response is a crucial task for

I am facing an issue with sharing data between AngularJS controllers. The data is obtained through an http request, but when I try to access it in the controller, it returns null. Strangely, if I manually refresh through the UI, the data becomes available. ...

Tips for adding a new value to an array of objects in React

As I navigate my way through the world of React as a newcomer, I've encountered a challenge that I need some advice on. I am attempting to add a new key and value to an array of objects, but I'm struggling to accomplish this task. Can anyone prov ...

When I utilize the redux connect function, the class information in my IDE (PhpStorm/WebStorm) seems to disappear

When I use the connect function from redux, it seems to hinder my IDE (PhpStorm) from "Find Usages" on my classes. This is likely because connect returns any, causing the type information from the imported SomeClass file to be lost. export default connect ...

What is the best method for integrating opensea-js using a script tag in a vanilla HTML/JS environment?

Is there a way to incorporate opensea-js into an html/js project that does not rely on node.js? The source code for opensea-js is only available on github and npm at https://github.com/ProjectOpenSea/opensea-js I came across this link: However, when I tr ...

Check to see if the property of the object does not exist within the array and update as

My goal is to add the variable content into the database content using the $push method, but only if the content.hash doesn't already exist in the database. I want to avoid duplicating information unnecessarily. return shops.updateAsync({ "user": u ...

The prefixes for Ruby on Rails routes are not properly preprocessed in the .erb.js file

I'm currently working with Rails 4 and encountering an issue with the following file: // apps/assets/javascripts/products.js.erb var getColoursAndMaterialsData = function(onSuccess) { var fd = formdata(); $.post( '<%= data_products_ ...

How do I set up Firebase functions to trigger onWrite when listening for a specific child just once?

Is there a way to access the child under a different node each time the Firebase onWrite function is triggered? To retrieve this child, you can use the following code: {const saatt = (context.database.ref('kullanicilar/1111/marina1/2021/1saat'). ...

Execute another Ajax request using jQuery after the first Ajax callback has been completed

Looking for a solution to ensure the correct order of appended contents loaded via ajax, I have the following script: $.get('http://mydomain.com/ajax1.php/', function(data){ var data_one = $(data).find('#ajax_editor_suggestion_c ...

When looking at react/17.0.1/umd/react.development.js, it becomes evident that ReactDOM is not defined

I'm currently immersing myself in learning React with the help of React Quickly, written by Azat Mardan, which is based on React v15.5.4. The examples provided in the book typically include two essential files: react.js and react-dom.js, such as in th ...