Every time I open my browser, my Node.js web app creates a fresh session

Whenever I close all browser windows and reopen the web app, a new session is initiated, forcing me to re-authenticate each time.

To give you an idea, my web application framework is

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8bda0a8aabdabab98ecf6e9ecf6e8">[email protected]</a>
, with
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8beef3fbf9eef8f8a6f8eef8f8e2e4e5cbbaa5babfa5ba">[email protected]</a>
as middleware for session storage, and
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4c7cbcacac1c7d089c9cbcac3cbe4958a978a96">[email protected]</a>
for authentication.

Below is the configuration for cookies and sessions:

// CookieParser should be above session
app.use(cookieParser());

// Express MongoDB session storage
app.use(session({
    resave: true,
    saveUninitialized: true,
    name: config.sessionName,
    secret: config.sessionSecret,
    store: new MongoStore({
        mongooseConnection: db.connection,
        collection: config.sessionCollection
    })
}));

The existing session stored in MongoDB still has two weeks before expiration.

It appears that the Node.js application fails to identify the old session from the browser, resulting in the creation of a new one and instructing the browser to use it.

This issue occurs consistently, indicating a potential problem within my web application.

Answer №1

Thanks to @Bradley, I finally managed to identify the issue.

Here is the solution I came up with:

app.use(session({
    cookie: {
        maxAge: ms('14 days') // Using 'ms' node module to convert string into milliseconds
    },
    resave: true,
    saveUninitialized: true,
    name: config.sessionName,
    secret: config.sessionSecret,
    store: new MongoStore({
        mongooseConnection: db.connection,
        collection: config.sessionCollection
    })
}));

To learn more, you can visit https://github.com/expressjs/session#expires

The default setting has no expiration, leading most clients to treat it as a "non-persistent cookie" that gets deleted when exiting the web browser.

This was the cause of my problem.

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

What causes the disparity in async.js when it comes to the divergence between waterfall and series/parallelLimit(1)?

This is the initial code that works fine: var fs = require('fs'); var async = require('async'); var addErrParm = function (err, done) {return function(exists) { done(err, exists); }} function testAsync() {var response ...

The deployment of my Next.js app on Heroku was refused due to an incompatible Node version

Encountering issues while attempting to deploy my app on Heroku, I am faced with the following shortened errors: remote: -----> Creating runtime environment remote: remote: NPM_CONFIG_LOGLEVEL=error remote: NODE_VERBOSE=false remot ...

The specified project directory was not detected. Please restart Next.js in your updated directory

I am facing a challenge with running my NextJS web app on a VPS server with PM2 as the Process Management tool. Despite trying different approaches, I am unable to get it to run properly. I have a deploy.js file that successfully deploys my other NextJS an ...

Node.js - Utilize the filesystem module to generate an array of objects from files

Currently, I am in the process of developing a menu for my ReactApp that mirrors a folder structure. Each folder is categorized based on the documents it contains, with some folders having sub-folders and files nested within them. The desired output shoul ...

Passing the app variable from Express.js to routes

I am attempting to transfer some data from the app (variable defined as var app = express();) to some Socket.IO related code by sending a value to a middleware in a similar manner: function routes(app) { app.post('/evento', function (req, re ...

A guide to populating multiple "Select" controls with data in Node.js using Mongoose

I am currently working on a project in Express JS where I am using Mongoose to interact with MongoDB. Currently, I am able to fill a select control in my view using the following code: app.get('/new_alumno', alumno.create); However, I now have ...

Issue encountered with Spatie/Browsershot in Laravel: npm and node were not located

After installing Spatie/Browsershot using composer, I encountered an error that seems beyond my expertise. Can anyone provide assistance? use Spatie\Browsershot\Browsershot; Browsershot::html('testing')->save('/public/assets/ ...

Can an object be passed to a redirect in Express.js, similar to how it is done with res.render()?

UPDATE: The recommended solutions can be found in this answer: When dealing with a get request in Node, the following code snippet shows how to achieve passing an object along with the request: app.get('/', function(req, res) { res.render(& ...

Even when my app is closed, I am unable to receive FCM Push Notifications. This issue persists in Ionic 3 and

Hello everyone, I'm excited to make my debut post on this site. Please forgive any mistakes in following the rules as I am still learning them. I need some help with an issue regarding notifications in an app I developed using Ionic 3 and Angular. De ...

Tips for developing integration tests for medium-sized nodejs applications with heavy reliance on 3rd party APIs

I am the owner of a medium-sized nodejs application that can be found on GitHub under the link here. This application heavily relies on various 3rd party APIs to function. Essentially, the purpose of this app is to make calls to different Salesforce APIs, ...

Node and Express Fundamentals: Delivering Static Resources

const express = require('express'); const app = express(); app.use(express.static('public')); I've been attempting to complete the "Basic Node and Express: Serve Static Assets" challenge on freecodecamp, but it keeps showing as " ...

What steps do I need to follow to set up siege with cgywin?

While diving into the world of nodejs and mysql connection, I encountered an issue when trying to execute the make command. Here's the tutorial I've been following: After installing cygwin, I followed these steps: I navigated to the latest si ...

Is Node JS Suffering from a Memory Leakage Issue?

Currently, I am facing a memory issue with my Node app (v0.8.26) running on Express (v3.4.8). The problem arises when I send an array of objects in the response body through a specific route. This action spikes the Node's memory usage, eventually lead ...

MERN application encounters error with running "heroku-postbuild" script during deployment on Heroku platform

During the process of deploying my app to Heroku, everything seems to be running smoothly until I encounter an issue. After logging in, I execute a series of terminal commands for deployment and receive the following responses: heroku login heroku: Press a ...

Error Message: TokenMismatchException detected in VerifyCsrfToken.php at line 68 - New Setup Detected

After running a Laravel project smoothly for over a year in my environment, I recently encountered a hiccup. Last week, I had to reinstall everything due to a new hard drive, and since then, Laravel has ceased to function. The other developers on my team ...

Having trouble with installing packages through NPM in Node.js?

Whenever I try to install a package, NPM shows me an error like this: [............] /roolbackFailedOptional: verb npm-session .... followed by the final error message: npm ERR! code e503 npm ERR! 503 Service Unavailable: npm ERR! A complete log of th ...

Issue with sending ephemeral message in Slack when replying to response_url not functioning as expected

I am currently developing an interactive Slack app using Node.js and Express. I have encountered a problem where, despite setting the response type to ephemeral, the replies from the interactive messages always appear publicly in the channel. Additionally, ...

Utilizing Vue.js to connect with a Node.js server

After setting up a basic Node.js server, the following code is running successfully: var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { res.writeHead(200, { 'content ...

Is there a way to integrate node.js updates and incorporate grunt/bower into a Python project within the Travis CI environment?

When setting up my project, I encountered a challenge with using grunt because Travis CI only had node.js version 0.6 in the python VM, while I needed node.js >= 0.8 for grunt. Despite trying to download and insert the latest binaries into the PATH, I stru ...

Setting up KeystoneJS Application with Let's Encrypt and Heroku

I am utilizing the letsencrypt feature of KeystoneJS to conveniently set up and manage HTTPS details for my project. I would like to configure this to function with a custom domain on Heroku. I have followed a previous guide to successfully configure the H ...