"Encountering issues with express-session failing to store information

I am developing a basic MEAN application and I am interested in creating a custom user authentication system. My plan is to store the userId in the session upon login, and then verify the existence of the userId in the session on each page request (such as when accessing the list of all users).

Backend - server.js:

const express = require("express");
const session = require("express-session");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();

var MemoryStore = session.MemoryStore;
app.use(
  session({
    name: "app.sid",
    secret: "my_s3cr3t",
    resave: true,
    store: new MemoryStore(),
    saveUninitialized: true
  })
);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());

const dbConfig = require("./config/database.config.js");
const mongoose = require("mongoose");

mongoose.Promise = global.Promise;

mongoose
  .connect(dbConfig.url)
  .then(() => {
    // ...
  })
  .catch(err => {
    // ...
    process.exit();
  });

require("./app/routes/user.routes.js")(app);
require("./app/routes/task.routes.js")(app);
require("./app/routes/login.routes.js")(app);

app.listen(3333, () => {
  console.log("Server is listening on port 3333");
});

Upon clicking the Login button, a function from the frontend controller is triggered:

Frontend - login.controller.js:

vm.login = function() {
    userService.getUserByUsername(vm.username).then(user => {
      if (user.password === vm.password) {
        console.log("Login successful");
        loginService.login(user).then(($window.location.href = "/#!main"));
      } else {
        console.log("Login failed");
      }
    });
  };

Backend - login.controller.js:

exports.login = (req, res) => {
  req.session.userId = req.body._id;
  req.session.save(function(err) {
    console.log(err); 
  });
  console.log(req.session);
  res.status(200).send({
    message: "Login successful"
  });
};

The frontend LoginController logs "Login successful" (assuming correct credentials are entered) and redirects to the "main" page which utilizes main.controller.js:

Meanwhile, the backend login controller outputs:

Session {
  cookie:
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true },
  userId: '5b4746cafe30b423181ad359' }

At this point, the session contains the userId. However, upon redirection to main.html and activation of main.controller.js, it executes:

loginService.getSession().then(data => console.log(data));

(The goal is to confirm the presence of userId in the session for further actions)

The getSession() function in the frontend LoginService simply performs an $http call:

function getSession() {
    return $http.get("http://localhost:3333/session").then(
      function(response) {
        return response.data;
      },
      function(error) {
        console.log(error.status);
      }
    );
  }

This triggers a method defined in the backend LoginController:

exports.getSession = (req, res) => {
  console.log(req.session);
  if (req.session.userId) {
    res
      .status(200)
      .send({ message: "Session found with userId " + req.session.userId });
  } else {
    res.status(404).send({ message: "Session not found" });
  }
};

In the frontend, a status code of 404 is displayed while the backend output is:

Session {
  cookie:
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true } }

(userId is absent...)

Additionally, some tutorials suggest using cookie-parser. However, implementing it results in only static text being displayed without any data retrieved from the database. Therefore, I have temporarily excluded it from server.js.

EDIT:

I attempted to integrate MongoStore into my application:

const MongoStore = require("connect-mongo")(session);
...
app.use(
  session({
    name: "app.sid",
    secret: "G4m1F1c4T10n_@ppL1c4t10N",
    resave: true,
    saveUninitialized: false,
    cookie: { maxAge: 600000 },
    store: new MongoStore({ url: "mongodb://localhost:27017/myAppDb" })
  })
);

However, there was no noticeable change.

How can I ensure that my sessions are functioning correctly?

Answer №1

After consulting with multiple individuals, I learned that sessions are becoming outdated and tokens are now the preferred method for managing these operations. Therefore, I transitioned to JWT and have been pleased with the results.

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

Encountered an OpenAI GPT-3 API issue with the error message: "TypeError: Converting circular structure to JSON" while utilizing ExpressJS

Currently in the process of experimenting with OpenAI's API and successfully have a basic express app set up and running. However, I am facing an issue where it is failing to send an appropriate response with a simple input. To test and troubleshoot ...

What causes the Express router to automatically convert my personalized Error object into a String?

In my node.js (0.8.12) application with express (2.5.8), I am utilizing custom Error objects. However, when errors occur, these custom Error objects get converted to Strings before being routed to my custom error handler, unlike native Error objects which ...

Issue with express.js: "express deprecated res.sendfile: It is recommended to use res.sendFile instead"

How should I correctly set the path? In my application, I am using this code to set the path for sending a file. app.get('/', function(req, res) { res.sendfile(__dirname + '/client/views/index.html'); }); However, I am getting thi ...

Issues arise when attempting to make a SOAP request in NodeJS, as opposed to PHP where it functions seamlessly

As I work on integrating a SOAP-API to access data, I encounter an error when trying to implement it in my ExpressJS-Service using NodeJS. The API documentation provides examples in PHP, which is not my preferred language. My PHP implementation works flawl ...

What is the best way to retrieve the request object within a Mongoose pre hook?

Is there a way to have the merchantID in documents automatically set to the logged-in user found in req.user when saving them? product.model.js: const ProductSchema = new Schema({ merchantId: { type: ObjectId, ref: "Merchant", requ ...

Building a Multipage Express web app with the power of Webpack 2

Our team is in the process of transitioning our web application from ASP.NET and jQuery to Node.js with Express and React. We have decided to stick with a typical multipage application architecture (MVC) for some specific reasons, such as SEO consideration ...

Regular Expressions in Express.JS to match `example.com/:username` pattern

// For example: http://example.com/john_smith app.get('/^(a-z)_(0-9)', function(req, res) { res.send('user'); }); // Another example: http://example.com/john_smith/messages/1987234 app.get('/^(a-z)_(0-9)/messages/:id', f ...

Tips on retrieving a single matching record in a many-to-many relationship using Postgres

In an effort to retrieve a user's pet based on the user's id and the pet's id. Description of my tables: CREATE TABLE pet_owner ( id serial PRIMARY KEY, first_name varchar(100) NOT NULL, last_name varchar(100) NOT NULL, phone_number ...

Express.js and Node.js middleware for validating all form submissions

Are there any middleware functions available for validating all form entries in node.js and express.js? I am interested in checking for special characters without having to validate each individual form field every time. Thank you! ...

What is preventing me from turning the express route into a synchronous one?

Although I have identified the issue with my code and researched the best solution, due to my limited experience, I am struggling to find a suitable answer. The primary goal is to ensure that my first route (/data) is fully executed before the second rout ...

Leveraging AngularJS html5mode in conjunction with express.js

Client-side: when("/page/:id", { templateUrl: "partials/note-tpl.html", controller : "AppPageController" }); $locationProvider.html5Mode( true ); Html: <a ng-href="/page/{{Page._id}}">{{Page.name}}</a> Server-side: app.use("/pag ...

What is the ideal location for integrating modular logic?

As I delve into the world of Node and Express, a simple query arises. It's so fundamental that giving it a title is proving to be challenging. My goal is to create a modular logic unit using multiple JavaScript files neatly organized within one direct ...

It appears as though the promise will never come to fruition

I am currently developing an application that is designed to search for subdomains related to a specific domain and store them in a database. The application retrieves data from crt.sh and threatcrowd. One of the functions within the application parses th ...

Control the access to shared resources when dealing with asynchronous functions in JavaScript

Currently, I am developing a node.js server script that will utilize a shared text list for multiple clients to access asynchronously. Clients have the ability to read, add, or update items within this shared list. static getItems(){ if (list == undef ...

Unable to logout with ExpressJS passport-local

After pasting the passport-local app into my own, I noticed something interesting: I managed to successfully log in users, but for some reason, I can't seem to get them logged out. app.get('/logout', function(req, res){ req.logout(); r ...

Node Express functioned as a pushState-enabled server, capable of serving any static resource without the need for a path

I am in the process of creating a one-page web application using either Ember.js or Backbone.js for the front end MVC, and express.js (node.js) as the back end server. server/app.js code snippet: app.use(bodyParser.json()); app.use(express.static(path.j ...

Having trouble resolving '___' from the 'home' state? Dealing with an angular ui-router complication?

I am a newcomer to angular and currently following the instructions outlined in this tutorial: https://scotch.io/tutorials/angularjs-multi-step-form-using-ui-router However, I am facing challenges while injecting this module into an existing module. Des ...

Why are Font Files causing permissions problems in my Openshift application?

Currently, I am in the process of working on a node.js project utilizing OpenShift. Everything is running smoothly except for the fact that I keep encountering a 404 error with my font awesome files. Upon SSHing into the system, I can see... ls app-deploy ...

Leveraging Next Js with an external REST API for streamlined authentication and authorization functionality

I am currently working on transitioning my existing application that was developed with Node.js and Express, along with a front end built using create-react-app with Redux, to Next.js. However, I have hit a roadblock as I am unsure of the correct method ...

The Node.js REST API encountered an issue with the message "Unable to submit /api/v1/product."

I'm currently working on setting up a post method for a REST API using Node.js. I'm encountering an issue where Postman is saying "cannot post /API/v1/product," but there are no errors showing up in the console. Can anyone provide assistance with ...