Passport req.user data not persisting throughout consecutive requests

When using the local strategy in passport.js, I'm attempting to access req.user to get the current user ID for storing recipes in the database. However, I'm facing an issue with deserialization in the passport.js file within my app's config setup. Every time I navigate to the /api/saveRecipe route, the req.user seems to disappear.

Important Note: The authentication process is being handled on the backend server while using React on the frontend.

Below is a snippet of my server.js file:

The main problem lies in req.user being accessible after calling passport.authenticate('local'), but it somehow becomes unavailable once the api/saveRecipe route is triggered.

I've done some research on this topic on various platforms like Stack Overflow, and it seems that the issue often relates to the order of setup in the server file. Even though I've reviewed my setup thoroughly, I still can't pinpoint the exact mistake...

const express = require("express");
const bodyParser = require("body-parser");
const session = require("express-session");
const routes = require("./routes");

// Requiring passport as we've configured it
let passport = require("./config/passport");

const sequelize = require("sequelize");

// const routes = require("./routes");
const app = express();
var db = require("./models");
const PORT = process.env.PORT || 3001;

// Define middleware here
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// passport stuff
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));

// We need to use sessions to keep track of our user's login status
// app.use(cookieParser('cookit'));
app.use(
  session({ 
    secret: "cookit", 
    name: "cookit_Cookie"
   })
);
app.use(passport.initialize());
app.use(passport.session());

// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/public"));
}

// the view files are JavaScript files, hence the extension
app.set('view engine', 'js');

// the directory containing the view files
app.set('pages', './');

// Add routes, both API and view
app.use(routes);

// Syncing our database and logging a message to the user upon success
db.connection.sync().then(function() {
  console.log("\nDB connected\n")
  // Start the API server
  app.listen(PORT, function() {
    console.log(`🌎  ==> API Server now listening on PORT ${PORT}!`);
  });
});
module.exports = app;

Here is a portion of my passport.js code:

//we import passport packages required for authentication
var passport = require("passport");
var LocalStrategy = require("passport-local").Strategy;
//
//We will need the models folder to check passport against
var db = require("../models");

// Telling passport we want to use a Local Strategy. In other words, we want login with a username/email and password
passport.use(
  new LocalStrategy(
    // Our user will sign in using an email, rather than a "username"
    {
      usernameField: "email",
      passwordField: "password",
      passReqToCallback: true
    },
    function(req, username, password, done) {
      // console.log(`loggin in with email: ${username} \n and password: ${password}`)
      // When a user tries to sign in this code runs
      db.User.findOne({
        where: {
          email: username
        }
      }).then(function(dbUser) {
        // console.log(dbUser)
        // If there's no user with the given email
        if (!dbUser) {
          return done(null, false, {
            message: "Incorrect email."
          });
        }
        // If there is a user with the given email, but the password the user gives us is incorrect
        else if (!dbUser.validPassword(password)) {
          return done(null, false, {
            message: "Incorrect password."
          });
        }
        // If none of the above, return the user
        return done(null, dbUser);
      });
    }
  )
);

// serialize determines what to store in the session data so we are storing email, ID and firstName
passport.serializeUser(function(user, done) {
  console.log(`\n\n        serializing ${user.id}\n`)
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  console.log(`\n\n        DEserializing ${id}\n`)
  db.User.findOne({where: {id:id}}, function(err, user) {
    done(err, user);
  });
});
// Exporting our configured passport
module.exports = passport;

const router = require("express").Router();
const controller = require("../../controllers/controller.js");
const passport = require("../../config/passport");

router.post(
  "/login",
  passport.authenticate("local", { failureRedirect: "/login" }),
  function(req, res) {
    console.log(`req body -${req.body}`);
    res.json({
      message: "user authenticated",
    });
  }
);


router.post("/saveRecipe", (req, res) => {
  console.log(req.user)
  if (req.isAuthenticated()) {
    controller.saveRecipe;
  } else {
    res.json({ message: "user not signed in" });
  }
});

module.exports = router;

Answer â„–1

Your router.post('login') code needs to be updated. Here is a better way to do it:

  app.post('/login', passport.authenticate('local-login', {
    successRedirect: '/profile',
    failureRedirect: '/login/failed'})
  )

By making this change, the req.user will be properly set for your future requests!

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

Utilizing a single mysql connection across client and server JavaScript files within a node.js environment

I have come across similar questions on this platform, but none exactly like mine, so I hope I am not repeating something that has already been asked before. As a newcomer to node.js & socket.io, I ask for your patience as I attempt to build a multi-c ...

The command is failing to include functionality with the yarg npm package

I have been attempting to incorporate a command using yargs, however, after executing my code, the command does not seem to be added successfully. Below is the snippet of what I am attempting: const yargs = require('yargs') //create add command ...

Error in AWS Lambda response

I currently have an AWS Lambda function set up to retrieve data from a MariaDB and return the fetched rows as a JSON object. There are a total of 64,000 items in the JSON array. However, I am encountering the following error: { "error": "body size is too ...

Bluebird Alert: a commitment was forged within a handler but failed to be returned from it

My current task involves iterating through an array of filenames using the async module for node. async.eachSeries(imageStore, function(imageDetails, callback){ mongoMan.updateCollection('imageStore', imageDetails, {_id: image ...

Steps for navigating the user from the login screen to the home page using react-native

I am currently working on a mobile app using Expo and Node.js (express). I have created the home screen, profile screen, and implemented navigation using the Drawer. Additionally, I have built the log in and sign up screens. My concern now is how to manag ...

What is the best way to determine the range in which the value falls?

Currently, I am working on validating whether a User has the required karma (reputation) to perform certain actions, such as placing a bid on an item. The karma value falls within the interval [-25; 100]. Additionally, it is noted that as a user accumulate ...

Verify if the document is already present, and if not, generate a new one

I am currently learning how to use expressjs with mongo. My goal is to verify if a user's data is already in the database after logging in with Steam using passport, and if not, create a new record for them. To achieve this, I have implemented a stat ...

Is there a way to fix an npm install error without having to remove my package-lock.json file?

I encountered an issue while working on a project in create-react-app and attempting to install react-router-dom. Unfortunately, the installation failed with the following error message: npm ERR! Cannot read property 'match' of undefined Many ot ...

The specified argument for "listener" in Node.js must conform to type Function

I have been attempting to develop a proxy update code using node.js, but I encountered the following error: events.js:180 throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'listener', 'Function'); ^ TypeError [E ...

What is the best way to ensure a cron job executing a Node.js script can access variables stored in an .env file?

Currently, I have a scheduled job using cron that runs a Node.js script. This script utilizes the dotenv package to access API keys stored in a .env file. Running the Node.js script from the command line retrieves the variables from the .env file successf ...

Using references to pass variables in JavaScript - passing variables to an external test in Mocha

When dealing with primitive datatypes in JavaScript, passing by reference doesn't work. One common workaround is to wrap them in an object. However, what happens if a variable starts as null and then gets reassigned as an Object before being passed to ...

Troubleshooting issues with uploading an image file to Cloudinary using Node JS and encountering buffer-related errors

Whenever I attempt to upload an image file (buffer) to Cloudinary, my code encounters some errors. const cloudinary = require("cloudinary").v2; However, when I store images in the MongoDB database, everything works perfectly. I have set up a user registra ...

Powershell throwing error due to unsigned Firebase script

While setting up a new project with Firebase, I encountered an issue after running the firebase init functions command. The error message displayed is as follows: firebase : File C:\Users\fudge\AppData\Roaming\npm\firebase.ps ...

Alert: Route.get() is requesting a callback function, but is receiving an [object Undefined] while attempting multiple exports

I'm attempting to export the middleware function so that it can be called by other classes. I tried searching on Google, but couldn't find a solution that worked for my situation. Below is the code snippet: auth.js isLoggedIn = (req, res, nex ...

Occasional occurrences of NGINX Errors/Timeouts while proxying to a Node/Express upstream (connection timeout occurred when connecting to upstream server)

Our Express web API is running on an EC2 Ubuntu server, receiving a relatively small amount of traffic (approximately 10 requests per second on average) and accessed through NGINX. Occasionally, a request hangs, resulting in the following error message bei ...

Setting up a retrieval callback in mongoose and storing it in a global variable

Is there a way to set the value of db as a global variable? I am having trouble with getting the console output of name outside of the findOne function, it keeps showing me undefined. Any suggestions on how to fix this issue? var name; schema.findone({na ...

Removing items from Google Cloud Storage using Google Cloud API, Node.js, and the request.del() method

I am facing an issue while trying to delete an object using request and the Google API. Despite following the instructions provided by Google Cloud Platform, I am unable to get it working. Could someone please assist me in resolving this problem? Thank y ...

The function os.platform in React and Electron mistakenly identifies the browser as the operating system instead of the actual OS

In my quest to locate the appdata folder for the application, I encountered a challenge where each operating system has a different path for the appdata or application support folder. To address this, I attempted to identify the OS type in order to deter ...

Loop through an array of objects, then store each one in MongoDB

If I receive an Array of Objects from a Facebook endpoint, how can I save each Object into my MongoDB? What is the best way to iterate over the returned Array and then store it in my mongoDB? :) The code snippet below shows how I fetch data from the Face ...

Contrast between using "export { something }" and "export something" in JavaScript modules

Can you explain the difference between the following code snippets: import something from "../something"; export { something }; vs import something from "../something"; export something; I noticed in the react-is package from react, there is an export ...