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

Comparing throwing exceptions in Node.js and Gevent

During a recent tech gathering, I heard an interesting claim about the behavior of callbacks and exceptions in Node.js and Gevent. The person mentioned that if a callback throws an exception in Node.js, it can crash the entire process, whereas in Gevent, a ...

res.redirect() not working after first form submission

I have encountered a strange issue that seems to only occur with specific users. When these users attempt to log in using ActiveDirectory on Google Chrome, the first login attempt does not trigger the redirect properly. However, if they try again after wai ...

Sorting through items based on several URL parameters

In an effort to be concise yet clear, I am working on an ecommerce website using Next.js and Shopify. This site features products that need to be filterable based on certain attributes. I retrieve products from the Shopify API, each with its own Product Ty ...

JavaScript - exploring techniques to alter the relationship between parents and children

I'm facing an issue with transforming the parent-child relationship in my data structure. Currently, it looks like this: { "id": 7, "name": "Folder 1", "parent_folder": null, "folders": ...

Is it possible to capture "global" events while handling nested iframes?

My dilemma involves capturing a keypress event, but the user can potentially be navigating through multiple layers of iframes nested within each other. Initially, I attempted to add the event listener to the document, only to realize that it wouldn't ...

What is the best way to access nested callback results from another file in a Node.js environment?

My API code can be found in the file api.js This is the content of api.js: var express = require('express'); var Vimeo = require('vimeo').Vimeo; var lib = new Vimeo('dfdfdfdfdfdfd', 'WDIt+kEVudfghjklkjhgfdfghjkjhgfMaG9X ...

When using AngularJS, the templateUrl feature delays the initialization of the controller, causing issues with dependent code

Recently, I began experimenting with AngularJS and so far, everything seems to be going smoothly except for one small issue. Let's consider a scenario where I have two directives, with one directive relying on the other, like this: angular.module(&ap ...

Vue Checkboxes - Maintain selection unless a different checkbox is selected

I have implemented a checkbox system with radio button behavior, but I am facing an issue where I want to keep the checkbox checked until another checkbox is selected (which will then uncheck the first one). I do not want the ability to deselect the checkb ...

What is the most effective way to use a withLatestFrom within an effect when integrating a selector with props (MemoizedSelectorWithProps) sourced from the action?

I am struggling to utilize a selector with props (of type MemoizedSelectorWithProps) in an effect inside WithLatestFrom. The issue arises because the parameter for the selector (the props) is derived from the action payload, making it difficult for withLat ...

Is there a way to store image URLs in a fashionable manner?

Hey there! I've been working on creating a HTML page that showcases multiple images. Everything is running smoothly on my localhost, but when I try to access it online, the images take forever to load. Any suggestions on how I can cache image URLs in ...

The Angular JS Factory fails to send data back to the controller

When I call the method getPopularMovies in my factory using the controller, it returns undefined. I'm not sure what mistake I've made here. Please help me figure it out. My Factory angular.module('ngMovies').factory('moviesFactor ...

React Issue: Make sure to assign a unique "key" prop to each child element within a mapped list

I encountered the error message below: react Each child in a list should have a unique "key" prop. Here is my parent component code snippet: {data.products .slice(4, 9) .map( ({ onSale, ...

Tips for adjusting the language settings on a date picker

Is there a way to change the language from English to French when selecting a month? I believe I need to configure something in the core.module.ts. How can I achieve this? https://i.sstatic.net/Cpl08.png @NgModule({ declarations: [], imports: [ Co ...

req.user is limited to containing only the username field

I recently started using passport js and encountered an issue. When I console.log req.user, it only displays the username field as {username: 'a'}. Other fields like email are not shown in the output. Below is the content of index.js file: const ...

Reverse the order of jQuery toggle animations

Looking for something specific: How can I create a button that triggers a script and then, when the script is done, reverses the action (toggles)? (I am currently learning javascript/jquery, so I am a beginner in this field) Here's an example: ...

Unable to locate a declaration file for the 'mymodule' module

After attempting to import my test module by installing it with npm i github.com/.../..., the code is functioning properly. However, when I opened it in VSCode, an error message popped up: Could not find a declaration file for module 'estrajs'. & ...

Storing segments of URL data for future use in React applications

Is there a way to extract information from a URL? I wish to utilize the appended details in this URL http://localhost:3000/transaction?transactionId=72U8ALPE within a fetch API. My goal is to retrieve the value 72U8ALPE and store it either in a state var ...

Create personalized styles for each item within a stack with specific spacing using the @mui library

Is there a way to change both the background color and spacing area when hovering over each item in my list? https://i.stack.imgur.com/87TST.png <Stack spacing={4} divider={<Divider variant={`fullWidth`} orientation={`horizontal`} flexItem/>}> ...

Can CSS Variables be changed globally using jQuery?

How can I dynamically change CSS Variables globally using jQuery? Check out this code snippet: $("div").click(function() { // Update the global variable "--text_color: rgb(0, 0, 255);" to a new value like "--text_color: rgb(0, 255, 255);" }); :roo ...

Identifying the various types in Typescript

In the process of developing a solution for Excel involving data from an Office API, I encountered the challenge of distinguishing between different types that a function can return. Specifically, the data retrieved as a string may belong to either a "Cell ...