Is it possible to create two separate Express sessions simultaneously?

I am encountering an issue with my Passport-using application that has a GraphQL endpoint and a /logout endpoint. Strangely, when I check request.isAuthenticated() inside the GraphQL endpoint, it returns true, but in the /logout endpoint, it returns false.

Upon further investigation with logging (request.session.id), I discovered that there are two sessions in use. The session within the GraphQL endpoint is persistent, maintaining the same ID even after server restarts, while the session in the /logout endpoint keeps changing.

It appears that the persistent session is cookie/DB-based and persists with client requests, while the /logout session is not cookie-based and resets along with the server. However, the question remains: why are there two distinct sessions?

Below is the relevant code snippet:

// Session setup
const store = new KnexSessionStore({ knex, tablename: 'sessions' });
app.use(
  session({
    cookie: { maxAge: 1000 * 60 * 60 * 24 * 5},
    secret: `a secret`,
    store
  })
);

// Passport setup
passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((user, done) => done(null, user));

app.use(passport.initialize());
app.use(passport.session());

// GraphQL Setup
// NOTE: request.session.id from inside a function in schema = persistent session
const graphQLHandler = graphqlHTTP(request =>({ graphiql: true, schema }));
app.use('/graphql', graphQLHandler);

// Logout Setup
app.get('/logout', (request, response) => {
  // NOTE: request.session.id = non-persistent session
  response.send(`user has been logged out`); // someday do request.logout()
});

Despite calling the express session setup function (session) once, it seems like app.use(passport.session()) might be creating a separate session. While this line instructs Passport to utilize the session, it should not generate a parallel session.

If anyone can shed light on this situation or suggest where I could insert code to prompt an error whenever a new session is created (to identify the cause of the second session), it would be greatly appreciated.

Answer №1

After some digging, I finally found the solution to the issue I was facing! It turns out many others were experiencing the same problem as well. You can check out the details here: https://github.com/jaredhanson/passport/issues/244. To sum it up...

In short: The issue stemmed from my client side code where it was fetching /logout from the server without setting the { credentials: 'same-origin' } option in the fetch request. This lack of proper credentials caused Passport to create duplicate sessions silently.

Surprisingly, the problem did not lie with my server code, but rather a simple fix on the client-side resolved it:

fetch(`/logout`, { credentials: 'same-origin' });

Hopefully, the developers at Passport will include error messages or warnings to alert users in similar cases instead of leaving them puzzled by unexpected outcomes (as evidenced by the 15 thumbs up comment providing the solution).

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

Extract website addresses from a text and store them in an array

I am currently attempting to extract URLs from a string and store them in an array. I have implemented a node module to assist with this task. const getUrls = require("get-urls") url = getUrls(message.content) However, the current implementation fails to ...

Using a global variable to change the class of the <body> element in AngularJS

I've recently developed an angularJS application. Below is the index.html <html ng-app="MyApp"> <head> <!-- Import CSS files --> </head> <body class="{{bodylayout}}"> <div ng-view></div> < ...

"Learn how to capture the complete URL and seamlessly transfer it to another JavaScript page using Node.js and Express.js

Is there a way to access the token variable in another page (api.js)? I need to use it in my index.js. var express = require('express'); var router = express.Router(); router.get('/', function(req, res ...

Trigger a notification based on the selected choice

Here is some sample HTML code: <div id="hiddenDiv" style="display: none;"> <h1 id="welcomehowareyou">How are you feeling today?</h1> <select name="mood" id="mood"> <option value="" disabled selected>How are you feeling?</o ...

Tips for setting up a scheduled event on your Discord server using Node.js

Hello fellow programmers! Recently, I've been working on a Discord bot using discordjs sdk. I'm trying to implement a feature where the bot creates an event every week. I went through the discordjs guide and checked the discord api documentati ...

Trouble with Angular toggle switch in replicated form groups

Currently, I have a form group that contains multiple form controls, including a toggle switch. This switch is responsible for toggling a boolean value in the model between true and false. Depending on this value, an *ngIf statement determines whether cert ...

I do not prefer output as my optimal choice

My preference is to create drill down buttons rather than focusing on output. Currently, the output appears as: The content of index.html is as follows: <html>  <head> <script type="text/javascript" src="http://ajax.googleapis.com/ ...

Trigger event once item is selected from the jQuery combobox dropdown

I have implemented a custom autocomplete combobox using the jQuery UI library to create text fields with dropdown functionality. This hybrid input allows users to either select an item from the dropdown or enter free text manually. However, I need to trigg ...

NPM is searching for the package.json file within the user's directory

After completing my test suite, I encountered warnings when adding the test file to the npm scripts in the local package.json. The issue was that the package.json could not be located in the user directory. npm ERR! path C:\Users\chris\pack ...

Having trouble with res.render() when making an axios request?

I am encountering an issue with my axios requests. I have two requests set up: one to retrieve data from the API and another to send this data to a view route. const response = await axios({ method: 'POST', url: 'http:// ...

Steps for creating a dynamic validation using a new form control

I have an item that needs to generate a form const textBox = { fontColor: 'blue', fontSize: '18', placeholder: 'email', name: 'input email', label: 'john', validation: { required: false } ...

Comparing strings with Ajax

I have been working on a basic ajax function setInterval(function() { var action = ''; var status = ''; $('#php-data').load('../Data/Dashboard.Data.php'); $.ajax({type: 'POST', u ...

Is there a way for me to make this Select update when onChange occurs?

I am facing an issue with a react-select input that is supposed to display country options from a JSON file and submit the selected value. Currently, when a selection is made, the field does not populate with the selection visually, but it still sends the ...

Is there a way to prevent Express.js from triggering a file download in the browser?

I am attempting to preview a Word document file in the browser using an iframe: <iframe style="float:right;" src="/ViewerJS/#../demo/ohm2013.odp" width='400' height='300' allowfullscreen webkitallowfullscreen></iframe> (Fo ...

Executing cross browser testing in Node JS consecutively within a single session: A step-by-step guide

When conducting cross-browser testing, I prefer to run the tests individually rather than all together in one session. This way, I can ensure that all test results are accurately logged and generated into a single HTML report at the end of each session. I ...

The one-click button is functional on larger screens, while on mobile devices, only a double click will register

I am facing an issue in angular where a button works perfectly fine with one click on larger screens, such as Macbook. However, on iPhone, it requires a double click to function properly (it works fine on Android too). The alert triggers with a single cl ...

Utilizing the .fadeToggle() function to create a fading effect for text, which fades in and out

I am on the verge of achieving my goal, but I could use a little more assistance with this. $('.change').hover(function() { $(this).fadeToggle('slow', 'linear', function() { $(this).text('wanna be CodeNinja' ...

res.cookie function is unable to set cookies in the Chrome web browser

During development, I have a basic login page running locally on my machine (http://127.0.0.1:5500/index.html) and a simple express server running at http://localhost:3003 Despite seeing the server sending my access_token in response headers, Chrome brows ...

Toggle the opening and closing of React components with a map function using onclick

Implementing an onClick function within a map operation, I am encountering an issue where clicking the onClick button changes the state of all items in the map, instead of just the item clicked. This is being done using the useState hook. const [open, se ...

What is the process for implementing the sticky table header jQuery plugin?

I am looking to implement a sticky header on all tables in my web application, which is built on PHP. As the amount of data continues to grow, search results are fetching more records that may not be visible. I am primarily a PHP programmer and do not have ...