Accessing a single Express app can result in the session being terminated in another app on the same server

On a single server machine, I have two Express 4.x applications running on different ports but sharing the same MongoDB instance. Each app uses its own database and session secret.

When logging into either application A or B individually, everything works fine - the session is maintained without any issues. However, if I am logged into A and then try to log into B, my session in A gets destroyed (and vice versa).

Both applications have similar local authentication setups with simple serializeUser and deserializeUser functions that closely follow the Passport documentation.

It appears that when switching from logging into A to B, the req.session.passport data is somehow being lost, causing req.user not to serialize correctly in app A, leading to an invalid session.

I suspect that this issue might be related to both apps running on the same machine and domain, only differing by the port number.

Answer №1

express-session: A straightforward session middleware designed for Express in Node.js. To incorporate this functionality, the package must be included as follows:

var session = require('express-session');

To add this package, execute the following command:

$ npm install express-session

If you want to implement this in Express, refer to the code snippet below:

app.use(session({
  secret: 'secretkey',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}));

The default name of the session ID cookie set in the response (and accessed from the request) is connect.sid. If you wish to change this, use the following configuration:

app.use(session({
  name: 'cookiename',
  secret: 'secretkey',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}));

For additional information, please visit this link - https://www.npmjs.com/package/express-session

Note: Insert your express-session statement into your application's app.js file before the app.use(passport.session()) statement.

We trust this guidance will aid in resolving your query!

Answer №2

const mongoose   = require('mongoose'),
    timestamps = require('mongoose-timestamp');

var Schema = mongoose.Schema;
const Usersession = new mongoose.Schema({
    expiration : {
        type : String,
        default : ""
    },
    sessionData : {
        type : Schema.Types.Mixed,
        default : {}
    }
}, { collection: 'usersessions' })

Usersession.plugin(timestamps)

module.exports =  mongoose.model('usersessions', Usersession);

//require schema
const Usersession = require('usersessions');

//delete user session by id
Usersession.remove({"sessionData.user._id":user._id}
).exec(console.log)

Answer №3

It's important to specify distinct session names for each project when running on different ports. The default name is connect.sid for all projects.

For instance:- Project A on port 3000 -
Project B on port 5000 -

When these projects are simultaneously run, they will use the same session name by default, resulting in authentication clashes. Therefore, it's crucial to assign different session names to each project.

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

Guide on obtaining Loopback 3 conditional 'datasources' and 'model-config': adhering to the provided steps does not yield results

After some tweaking, I managed to make it work partially by assuming that the local variations could only replace already defined structures. This means that I had to initially define the data sources 'DynamoDB' and 'mongo' in datasourc ...

How can you transform a nested array into a flat JavaScript map?

If we consider a JavaScript Map structured like this: [ { id: 1, name: "Foo", contents: [1,2,3], morecontents: ["a","b"], }, { id: 2, name: "Bar", c ...

Node cannot be updated because npm is not compatible with Node.js version 5.3.0

Running MacOS Sierra v10.12.6, I executed the command npm update -g and received the following result: npm WARN npm npm does not support Node.js v5.3.0 npm WARN npm You should probably upgrade to a newer version of node as we npm WARN npm can't make ...

An API request was successfully completed with security measures in place; if not

I am facing a challenge with managing two tables, one for users and the other for user roles. The user role table is used to store multiple roles for each user. I have created two APIs to handle deleting a user - one API deletes the user based on their use ...

Adding an image to a PDF file using NodeJS and Pdfmake

I am currently using the pdfmake api in my NodeJS application to generate PDF files. However, I am facing an issue when trying to add an image to the document as I keep receiving the following error message: Error: Invalid image format. The images dictiona ...

Create a Mongoose model that includes a field containing an array of ObjectID's

I am encountering an issue with my object named company, which contains keys for name(String) and locations(Array). Within the locations key, I want to include a user-generated key called name, as well as a second key generated using ObjectID. However, I a ...

Commitments and incorporating items from an array into objects nested within a separate array

My current project involves a command line node application that scrapes valuable data from a specific website and stores it in a CSV file. For the scraping functionality, I am utilizing scrape-it, which enables me to successfully extract all the necessa ...

Is Exposing Database Passwords on Github a Potential Security Concern?

I recently set up an express server and I'm still fairly new to the world of databases. An interesting dilemma has come up - if my express server's code is hosted publicly on Github, and it contains this snippet: const pool = new Pool({ user: ...

Combining Summernote images with Node.js using Express.js

While there are numerous solutions available for handling the Summernote file-upload in PHP, I have struggled to find a satisfactory solution for Node.js. Here is My JavaScript: $(document).ready(function() { // $('#summernote').summernote( ...

When a node using express encounters :id, it is directed to a specific location

Currently, I am in the process of creating a small API collection to familiarize myself with nodejs using express. In my project, I have included the line app.use("/v1/phrases", phraseRouter); Within the router file, the code looks like this: co ...

Guide to ordering objects within an array by their createdAt property in mongoose

I'm attempting to organize the products array based on the createdAt date. Here is my orders model: const itemSchema = new Schema( { productId: { type: Schema.Types.ObjectId, ref: 'Product' }, quantity: { typ ...

Update Mongoose data conditionally using an array of objects

I am facing a challenge with my Cart schema in Mongoose. The CartItems are stored as an array of objects. { _id: string; items: [ { product: string; options: { size: string; color: string; } quantity: number; ...

The internal cjs loader in node threw an error at line 1078

I'm encountering an error on Windows 10 when running the npm command: node:internal/modules/cjs/loader:1063 throw err; ^ Error: Cannot find module 'D:\mobile-version portfolio\ at Module._resolveFilename (node:internal/modules/cjs/load ...

sharing functions across distinct components in react without directly passing between parent and child

I have a query about passing functions between components that are not related in a parent/child hierarchy. Here is the structure inside my App. function App() { return ( <div className="App"> <Header/> <Pfl /> ...

Evaluating server functionality within Koa framework

Currently, I am utilizing Koa for my web development tasks within NodeJS. Within my server file, the primary function is to initiate the server and set up a few essential middlewares. Below is an example of what this code looks like: server.js const Koa ...

Unable to locate "Gruntfile.js" Node module for task execution

I am currently in the process of developing a module that enables node to execute Grunt tasks via the command line. This Node module is globally installed at : C:\Users\pcharpin\AppData\Roaming\npm\node_modules\task-app ...

Retrieve information from various MongoDB collections

Greetings! I currently have a database with the following collections: db={ "category": [ { "_id": 1, "item": "Cat A", }, { "_id": 2, "item": "Cat B" ...

Executing MySQL queries synchronously in Node.js

When working with NodeJS and mysql2 to save data in a database, there are times when I need to perform database saves synchronously. An example of this is below: if(rent.client.id === 0){ //Save client connection.query('INSERT INTO clients (n ...

Validating forms in express.js

I need to validate a form that includes user details. In addition to the basic validation for checking if fields are not empty, I also want to verify if the username/email exists in the database. For the email field, I need to ensure it is not empty, follo ...

Transferring data from URL straight to S3 in Lambda with an excessive memory consumption

Utilizing AWS Lambda with node.js, I successfully streamed files directly from a URI to S3 without the need for downloading them onto disk by adapting code from this individual's sample. After making some adjustments to create a buffer from a request ...