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:

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

To utilize the Heroku Express + Postgres addon, one must have elevated permissions

[2022-11-01 14:45:37.218] [ERROR] application - Connection postgres://user123:password456@database.example.com:5432/db_name123 requires elevated permissions I'm currently working on deploying an application using Node.js + Express + Sequelize + ...

I'm experiencing an "existing database with different casing already exists" error, even though I have no intention of creating a new database

My goal is to include a new word in a database called "wordsDb" within a collection named "wordsCollection": dbName = "wordsDb"; collectionName = "wordsCollection"; connectionUri = //... (secret) async add(word) { try { ...

Encountering an issue in a Vue console where the $ref is returning null and prompting an error message

It's puzzling why I keep encountering a console error in Vue that says "cannot read null of a $ref". Despite having the correct HTML template and adding logic to the script tag as needed, I'm still facing this issue - Cannot read properties of nu ...

Material User Interface, MUI, Modal, Back to Top Scroll按钮

After spending some time experimenting with scrollTop and the Dialog component (a fullscreen fixed modal) from Material-ui, I found that I couldn't quite get scrollTop to function properly. Whenever I clicked the "go down" button, it would either retu ...

Where should the defer.resolve be placed when executing a function asynchronously in a loop using JavaScript?

As someone coming from a java/python background, I am venturing into the world of JavaScript. My current task involves creating a product list with detailed descriptions of its children included in a JSON array. Here is an example of what I want to achiev ...

What causes the variation in output results between axios and express when using dot notation?

A geo tool application is in the works, built with reactjs. The concept involves users submitting a city name which then triggers a post request. This request searches through a city list.JSON file to find the corresponding city and returns its geolocation ...

Guide on using JavaScript to automatically scroll a HTML page to the top on any mobile browser

Can JavaScript be utilized to smoothly scroll an HTML page to the top? I am looking to achieve this with a stylish animation that functions correctly on all mobile browsers. jQuery is the library I am using on this particular page. Thank you, ...

Top method for independently scrolling overlapping elements in both the x and y directions

Sorry if this is repeating information. I have a structure of nested divs like this: -container -row In order to enable scrolling without the default scrollbar appearing, each container and row has an additional container. My goal is to be able to scrol ...

What is the best way to convert exponential values to decimals when parsing JSON data?

var value = '{"total":2.47E-7}' var result = JSON.parse(value); Looking to convert an exponential value into decimal using JavaScript - any suggestions? ...

Combining AngularJS, D3, and JQuery on a single webpage can pose challenges, specifically with D3's ability to accurately read DOM dimensions

I am encountering an issue with my webpage not loading properly. I have structured it using a simple header-body-footer layout in html5 and CSS3. +----------+ | HEADER | +---+----------+---+ | BODY | +---+----------+---+ | FOOTE ...

Change the location of an HTML element within the page structure

Let's consider having 3 elements like this: <h1>Hello</h1> <p>hello</p> <h1>Hello</h1> I am looking to remove the second <h1> as I only want it to appear once on the page. However, I would like to have flexib ...

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

Preventing template rendering in Angular until an event is triggered - but how?

I am currently working on a directive that functions well, but I had to resort to using inline template code in order to delay rendering until the click event occurs. However, I believe it would be more streamlined if I could assign the directive template ...

Is there a way to retrieve the sub-child menu data from a JSON file?

I am currently working on creating a horizontal menu from a json file. However, I am facing issues in retrieving the subchild elements properly. Below is an example of my json file: var data = [{ "menu":[ { "MenuId":1, ...

How to Set Up a Simple Gulp Uglify Configuration

My objective is to compress all .js files within my project and save a minified version in the same directory. Assuming this is the structure of my project directory: project/ gulpfile.js basic.js Project/ Project.js Toolbelt. ...

What are the steps to address unhandled promise rejections?

Issue: UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token o in JSON at position 1 Currently working on a MERN stack application. The signup form is in the Frontend, and below is the POST method for it. const onSignUp = async (e) => { ...

struggling to access the value of a hidden field by using the parent class name

My coding experience so far looks like this- <tr class="chosen"> <td id="uniqueID">ABCDE5678</td> <input type="hidden" value="000005678" id="taxCode"> <td id="fullName">Z, Y</td> </tr> In this scenario, I need to ...

Node.js Antivirus Scanning for a Uploaded File Stream

Seeking an antivirus solution for scanning the filestream uploaded from a rest api using express. Came across clamscan as an option, but it requires some linux dependencies. https://www.npmjs.com/package/clamscan Is there a more efficient method to perfo ...

Adding JavaScript in the code behind page of an ASP.NET application using C#

Currently, my challenge involves inserting a javascript code into the code behind page of an asp.net application using c#. While browsing through various resources, I stumbled upon some solutions provided by this website. Despite implementing them as inst ...

Interacting with an API and retrieving data using JavaScript

I have hit a roadblock. This question might be simple, but I am struggling to figure it out. I am attempting to retrieve a response from an API (mapquest), but I can't seem to navigate the response to extract the necessary information. Here is my con ...