When utilizing Passport + Express authentication, no cookies are saved in the browser

Currently, I am in the process of developing a web API and the workflow should go like this:

User logs in to the website --> Passport authenticates the user --> Passport stores relevant user information in a persistent session --> User can access the API as long as the session remains valid.

The issue I'm facing is that I cannot seem to get Passport to create the persistent session. The login functionality works correctly (only authorized users are able to proceed), but for some reason, Passport fails to retain any session data in the client's browser. Consequently, the user loses access to the API moving forward.

The sections of code pertinent to this problem are outlined below:

Server.js:

// Import necessary packages
var express    = require('express');        
var app        = express();                 
var bodyParser = require('body-parser');    
var passport = require('passport');         
var flash    = require('connect-flash');    
var cookieParser = require('cookie-parser');

// Setup database connection
var configDB = require('./config/database.js');
var mongoose   = require('mongoose');
mongoose.connect(configDB.url);

// Include schema for training
var Training = require('./models/training');

// Configure app 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

// Required for passport
require('./config/passport')(passport); 

app.use(require('express-session')({
    cookie : {
    maxAge: 3600000, 
    secure: false
  },
    secret: 'khugugjh',
    resave: false,
    saveUninitialized: true
}); 
app.use(passport.initialize());
app.use(passport.session());
app.use(flash()); 

...

routes.js:

...

// Define the login route

router.route('/login').post(
  passport.authenticate('local-login'),
  function(req, res) {
    // If this function gets called, authentication was successful.
    // `req.user` contains the authenticated user.
    console.log('Logged in user: ' + req.user);
  });

...

passport.js:

...

// Serialization and deserialization functions for Passport

passport.serializeUser(function(user, done) {
        console.log('Serializing user: ' + user); 
        return done(null, user._id);
    });

    // Used to deserialize the user
    passport.deserializeUser(function(id, done) {
        console.log('Attempting to deserialize user.'); 
        User.findById(id, function(err, user) {
            console.log('Deserializing user: ' + user); 
            return done(err, user);
        });
    });

...

Answer №1

If you are running into problems, it could be due to how requests are being sent from the client side. When using the ES6 fetch API, make sure to include the key credentials in the options object with a value of "include".

Here's an example:

    fetch('/restricted', {
      method: 'get',
      credentials: 'include'
    });

This solution worked for me. Additionally, keep in mind that if you're using express-session v1.5.0, you don't need the cookie-parser middleware as it is included.

Hope this information is helpful.

For more resources, check out: https://developers.google.com/web/updates/2015/03/introduction-to-fetch

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

Using JavaScript Regular Expressions to locate all prefixes leading up to a specific character

Consider a scenario where you have a string consisting of terms separated by slashes ('/'), like this: ab/c/def Your goal is to identify all the prefixes of this string up to a slash or the end of the string. For the given example, the expected ...

Is it possible for a function parameter to utilize an array method?

Just starting to grasp ES6 and diving into my inaugural React App via an online course. Wanted to share a snag I hit along the way, along with a link to my git repository for any kind souls willing to lend a hand. This app is designed for book organization ...

The issue with 'DemoCtrl' defined in Angular JS is that it does not correspond to a valid argument

signup.html <div ng-controller="UniqueCtrl" layout="column" ng-cloak="" class="md-inline-form inputdemoBasicUsage" ng-app="inputBasicDemo"> <md-content md-theme="docs-dark" layout-gt-sm="row" layout-padding=""> <div> <md- ...

Displaying React components for a brief duration of time

I have an existing React component where I need to display another component for a specific duration. Upon mounting or data loading of the parent component, the child component should become visible after 1-2 seconds and then disappear after a few more sec ...

Utilizing event delegation for JavaScript addEventListener across multiple elements

How can I use event delegation with addEventListener on multiple elements? I want to trigger a click event on .node, including dynamically added elements. The code I have tried so far gives different results when clicking on .title, .image, or .subtitle. ...

Using Node.js to read from a file and write the character 'Ł' to another file

I am facing an issue with an ANSI file that contains the character 'Ł'. My goal is to extract this character and save it to another file while preserving the same encoding to retain the 'Ł' character. const fs = require('fs&apos ...

Multiple selection menus within a single module

I am working on a component with multiple dropdown menus. <div v-for="(item, index) in items" :key="index"> <div class="dropdown"> <button @click="showInfo(index)"></button> <div ...

Attempting to retrieve data from an HTML response using Node.js

My goal is to extract the Email ([email protected]) from the HTML response using cheerio and puppeteer modules. However, I am retrieving unnecessary information which I do not need at all. It is located within the Class p2 in td/tr. when passing tr a ...

What is special about this element, textarea?

Hey there, I've got this JavaScript code that currently works on all textarea elements on the site. However, I'd like it to only work on one specific element. function limits(obj, limit) { var text = $(obj).val(); var str_length = $(obj) ...

Error: The term 'function' is not recognized in this Javascript runtime

There seems to be an issue with my function being undefined, even though it is clearly defined below the content of the program. <button type="button" class="btn btn-primary" data-dismiss="modal" id="CmdBranchEditOk" onclick="CmdBranchEditOk_OnCli ...

Creating a versatile "add new entry" form in Angular that appends a new record to the parent scope

In my Angular application setup, I have an "Edit Invitation" state where a single invitation is scoped. This invitation contains a list of guests controlled by a guestList controller and iterated over in the view. <div ng-controller="guestListCtrl as g ...

Maintaining an array of data in Cordova/Phonegap that persists when the app is closed and reloads when reopened

I have set up an array in my application that looks like this [{pseudo: "test", id: 0}, {pseudo: "Lucia", id: 2}] Is there a way to preserve this array even when the app is closed? Additionally, I would like to access the array directly upon reopening th ...

Unable to conceal iFrame ribbon in Sharepoint Online

Attempting to conceal an Office 365 ribbon in SharePoint, but encountering an issue... TypeError: document.getElementById(...) is null This is the snippet I'm experimenting with; I plan to implement display:none later... document.getElementById(&ap ...

React encountered an error: Unable to destructure the property 'id' of '_ref' as it has been defined

After spending several hours trying to solve this issue, I am completely stuck. The console shows that the patch request successfully updates the information, but then my map function breaks, leading to a blank page rendering. Here is the problematic comp ...

Encountering the issue "Unable to set headers once they have been sent" while attempting to store an image and user information in a MongoDB database

I am currently working on a simple application using Node.js, Express, MongoDB, and Angular. The application includes a form where users can input data and upload an image. To handle the image upload functionality, I'm utilizing ng-file-upload. In ord ...

Enable or disable options with the user's permission

Currently, I am developing a WordPress plugin that will display a simple div on all pages. The code is set up to create the div, turn it into a shortcode, and then show it on each page. I want to include a checkbox in the admin settings so that users can ...

Dynamic stacking of buttons in response to user navigation choices

Is it possible to create a navigation bar with 5 buttons using CSS and JS? Here is what I am looking to achieve: Display 5 nav/button options When a user clicks on a button, the other buttons should transition or hide, leaving only the selected button vi ...

Display Error with Custom Alert Box

I recently implemented a customized alert box from slayeroffice's website, which you can find at slayeroffice.com/code/custom_alert/. When I view it on my browser, the alert box appears with a blue color in the center of the screen. Here is how it lo ...

Error 404: RedirectURL not found in Azure AD - OAuth/PassportJS

Recently, I've been working on setting up OAuth logging from Microsoft Azure AD to my Node application using PassportJS and passport-azure-ad. However, every time I try to send a request to my provider, the route https://localhost:3000/auth/openid/ret ...

Issues with loading JavaScript in Selenium

I have been trying to extract data that is loaded through google tag manager. Despite my efforts using both chrome and firefox, the li elements I need in the body always appear empty no matter what timing I use. import undetected_chromedriver as uc from ...