What is the best way to pass and save information across different routes in Express using Node.js?

Let's delve into the specific functionalities I envision for my server. Essentially, my project involves user registration and login processes.

The URLs for these routes are as follows - localhost:3000/login and localhost:3000/register

Upon successful login using their credentials (POST), users should be directed to localhost:3000/home, a personalized page. Instead of passing data via templating engines, I aim to make this data accessible across all routes for flexible usage.

The challenge I'm facing currently is regarding session storage. The user data, stored in a session upon logging in, isn't transferable between routes. This means that the session set up for the /login route is not usable for the /home route or any other route, for that matter. Is there a feasible way to save a session whenever a user logs in (using POST) and ensure that the session data is accessible throughout all routes?

server.js


var express = require('express');
const path = require('path');
const fs = require('fs');
const session = require('express-session');
const { v4: uuidv4 } = require('uuid');
const app = express();

app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public/auth-pages')));

// Additional code and route handling methods as per requirements

Answer №1

One way to maintain user data between routes is by utilizing cookies.

If you prefer not to store all the data in the browser, you can save the user id in cookies and keep the rest of the data in a repository object.

For instance: create a class that manages the state of logged-in users and make it accessible across routes. Instantiate this class and export its object.

(Note that this method only keeps the state in memory and will be lost upon service restart/shutdown. To preserve the state after such events, consider storing it in a database like Redis or MongoDB).

Repository class:

class UserRepo {
   constructor() {
       this.users = {};
   }

   set(user) {
       this.users[user.id] = user;
   }

   get(userId) {
       return this.users[userId];
   }
}

let repo = new UserRepo();
module.exports = repo;

Route handler:

const express = require('express');
const router = express.Router();
const repo = require('./userrepository.js');

router.post('/login', (req, res, next) => {
  // Perform login logic here and obtain user id
  let user = ...
  let loggedIn = ...

  if (loggedIn) {
      res.cookie('userId', user.id)
      repo.set(user)
  }
});

route.get('/home', (req, res, next) => {
      let userId = req.cookies.userId 
      let user = repo.get(userId);
});

Answer №2

To tackle this issue, consider implementing a system where user data is stored in a centralized database rather than relying on individual server instances. By creating a class to manage user information across servers, you can avoid the pitfalls of potential failures and scalability limitations. For example, if multiple servers are handling requests with load balancing, having a shared repository for user data ensures consistency and availability regardless of which server processes each request.

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

Guide to creating a Foreach loop in EJS code

Whenever I attempt to use a Foreach loop statement in my ejs code, I encounter an error message indicating that "songs.foreach is not a function" <% songs.foreach(function(song){ %> <li><%= song.name %> - <%= song.year %></ ...

Break down React website into distinct modules and bundle them as npm dependencies within a single package

Currently, I am developing a React website that includes distinct sections such as contact management and message management. Each of these sections is quite extensive. To navigate to these sections, we use a single dashboard for control. Since separate ...

issue with mongoose virtual populate (unable to retrieve populated field)

During my project using mongoose with typescript, I encountered an issue with adding a virtual called subdomains to populate data from another collection. Although it worked without any errors, I found that I couldn't directly print the populated data ...

What method can I use to adjust the font style when it overlays an image?

Sorry if this is a bit unclear, but I'm trying to figure out how to change only a section of my font when it overlaps with an image while scrolling. If you visit this example website, you'll see what I'm referring to: For a visual represen ...

Customizing ExtJS 4.1: Mastering field overrides

Seeking guidance on applying a plugin to all fields(numberfield, textfield, datefield, etc.) within the ExtJS 4.1 library. Does anyone have suggestions on how to achieve this? I understand that all fields are derived from BaseField. I attempted the follow ...

Upon upgrading to Angular 8, the function this._delegate.setNgStyle is not recognized

Following the update of my project from Angular 7 to Angular 8 and resolving all errors caused by breaking changes, I am encountering a new issue: <div fxFill ngStyle.xs="overflow:auto"> This line is resulting in the following error: ERROR Type ...

Encountering the error `ReferenceError: document is not defined` when trying to deploy a Next.js project on Vercel

I recently worked on a Next JS project and deployed it to Vercel. Initially, everything was running smoothly, so I didn't check the website status for a while. I was just developing it locally and pushing updates to GitHub. However, when I finally rev ...

My ng-view html is unexpectedly displaying as plain string. What steps should I take to resolve this issue?

Why is my ng-view HTML displaying as plain text? How can I resolve this issue? I have encountered an error, here is the screenshot for reference: Unfortunately, I am unable to upload images at the moment. ...

Utilize the power of REACT JS to transform a specific segment within a paragraph into a hyperlink. Take advantage of the click event on that hyperlink to execute an API request prior to

In React JSX, I'm encountering an issue trying to dynamically convert a section of text into an anchor tag. Additionally, upon clicking the anchor tag, I need to make an API call before redirecting it to the requested page. Despite my attempts, I have ...

What is the best way to capture user input using an onClick event in JavaScript and then display it on the screen?

I'm in the process of upgrading a table, and while most of it is working fine, there is one function that's giving me trouble. I want this function to return an input with an inline onClick event. The actual return value is displaying correctly, ...

What steps can be taken to resolve an error encountered when attempting a dynamic data POST request from the body

Whenever I attempt the post method to fetch data on Postman and store it in a local MongoDB database, I encounter an error. The error message indicates a bad request with a status code of 400. *The following is app.js: var express = require('express& ...

How can the jQuery click() method be utilized?

Currently working on a web scraping project, I have managed to gather some valuable data. However, I am now faced with the challenge of looping through multiple pages. Update: Using nodeJS for this project Knowing that there are 10 pages in total, I atte ...

What is the process for including a class on a div element?

I have written a code that displays a series of images in a sequence. Once the last image appears, I want to switch the class from .d-none to .d-block on the div Can this be achieved? onload = function startAnimation() { var frames = document.getE ...

Error: The term "Image" is unrecognizable

I'm in the process of creating a website where I want to display images via links. If the image is missing or only 1 pixel wide, I need the site to show an alternative image. My technology stack includes Jade/Pug and JS. Before rendering the links on ...

Implementing Node.js with Express to handle app.get requests that include multiple query parameters

I am trying to utilize the Yelp API with the following route: app.get("/yelp/term/:term/location/:location", yelp.listPlaces) However, when I send a GET request to http://localhost:3000/yelp?term=food&location=austin, An error occurs stating Canno ...

Exploring the Fusion of Material UI Searchbox and Autocomplete in React

Looking for help with my AppBar component from Material UI. I want the Searchbox field to function similarly to what is seen on https://material-ui.com/. It should appear as a Searchbox but display selectable options like Autocomplete after entering input. ...

The AJAX query for validating IDs in a JSP page consistently produces identical outcomes

I have been implementing a feature to check IDs using AJAX in JSP. When a user tries to create a new account, they enter the desired ID and AJAX checks if the ID already exists in the database. If the ID is found, it returns 'n' which is then dis ...

a guide to caching a TypeScript computed property

I have implemented a TypeScript getter memoization approach using a decorator and the memoizee package from npm. Here's how it looks: import { memoize } from '@app/decorators/memoize' export class MyComponent { @memoize() private stat ...

What is the best way to title an uploaded chunk with HTML5?

Here is the script I am working with: function upload_by_chunks() { var chunk_size = 1048576; // 1MB function slice(start, end) { if (file.slice) { return file.slice(start, end); } else if (file.webkitSlice) { ...

Showing the number of times a button has been pressed

I have written some HTML code to create a button and now I am looking for guidance on how I can use Vue.js to track how many times the button has been clicked. Here is what I have so far: <div class="123"> <button id = "Abutton&q ...