How do I assign a variable to a session in Express.js?

I am currently working on a login form that prompts users to enter their username, password, and company name. The company name corresponds to the database name, so I need to store this information in the session during the login post request.

In my opinion, storing it in the session is the better option rather than using req.locals.

Initially, I attempted to set it with req.locals but encountered issues:

Here is an excerpt from my app.js file:

// Global Vars
app.use(function (req, res, next) {
  res.locals.success_msg = req.flash('success_msg');
  res.locals.error_msg = req.flash('error_msg');
  res.locals.error = req.flash('error');
  res.locals.user = req.user || null;
  res.locals.database = req.database || null;
  next();
});
// Express Session
app.use(session({
    secret: 'secret',
    saveUninitialized: true,
    resave: true
}));

When attempting to set the database name in the /login post route like this:

req.locals.database = 'db_xpto';

However, when trying to display the variable in the view, nothing was shown:

h4 Using database: #{database}

What would be the optimal solution for handling this data - utilizing local variables or sessions? And how should I go about setting it?

Note: I am implementing passport for the login process.

Answer №1

In my opinion, utilizing a session is the preferred method as it is automatically managed by the session middleware. Additionally, res.locals cannot be accessed within the session but only for that particular request. You have the option to adjust your code and incorporate the session directly in the route instead of relying on a separately defined middleware.

  res.session.success_msg = req.flash('success_msg');
  res.session.error_msg = req.flash('error_msg');
  res.session.error = req.flash('error');
  res.session.user = req.user || null;
  res.session.database = req.database || null;

This same approach can also be applied to your login route.

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

How can data be transferred from a parent component to a child component using MaterialUI's styling functionality?

Recently delving into the world of reactjs, I've been tinkering with a basic page that incorporates authentication using state. To spruce up the design, I decided to use the MaterialUI framework. The issue I'm facing is related to sending the lo ...

"Unraveling the Mystery of jQuery In

I am facing an issue with integrating jQuery into my code. I have always followed the same method, which has worked in the past, but now it seems to be causing problems for me. I suspect it may be because I am not on my usual laptop, although when I visite ...

Retrieving the selected value from a Bootstrap dropdown using JavaScript when there are multiple dropdowns present

I have created multiple rows in javascript that are being rendered to the DOM from a Firestore collection. Each row contains a Bootstrap dropdown with the same select options (".a" elements). The id attribute of each row div is dynamically set based on the ...

Create a JavaScript and jQuery script that will conceal specific div elements when a user clicks on them

Within my navigation div, there exists another div called login. Through the use of JavaScript, I have implemented a functionality that reveals additional divs such as login_name_field, login_pw_field, register_btn, do_login_btn, and hide_login upon clicki ...

Is my data secure in Node.js RAM?

I have developed a web application that enables users to create personal pages using Express and Node.JS. Each page is represented as an object, allowing for the creation of new ones with the syntax: new privatePage(name, pswd). As a result, all passwords ...

Efficient File Upload Feature Compatible with all Browsers, Including Internet Explorer versions 7, 8, and 9

Can someone assist me with a problem I'm facing? I need a code script that enables multiple file uploading on all browsers. While HTML5 supports Chrome and Mozilla Firefox, it does not support IE. I am looking for a script/jquery solution that works ...

Issue with setTimeout() function not being triggered within a VueJS method

I am currently developing an application that allows a user to reset or shutdown a particular server. I am focused on creating the interface and ensuring that the user receives appropriate messages about the actions being taken. My approach involves displa ...

perform a search query in mongoose with sorting

Having an issue with a mongo request: models.user.findOne( {}, { sort: { date_register: -1 } }, function(err, result) { console.log(err); } This error is showing up: { [MongoError: Error: Unsupported pro ...

Is there a more efficient way to optimize custom error handling middleware in Node

Hello there, I am currently developing a feature on a nodeJS platform that exposes a REST API. My task is to create custom error handlers that will execute specific business logic. Essentially, I am working on handling a POST request with content encod ...

Encountering an issue with WebDriver in the realm of JavaScript

I am struggling to use JavaScript to locate specific controls and send values to them. One example is changing the text in a textbox with the ID "ID" to "123456". Below is the code I tried: ((IJavaScriptExecutor)driver).ExecuteScript("document.getElement ...

Updating state from a React mapping component: A step-by-step guide

I am working on an API that needs data filtering and then I want to place the filtered data into a state export default class ModifyPage_Single extends React.Component { constructor(props) { super(props) this.state = {data:[],idd:" ...

Re-activate external script following a language update in Next.js

In my Next.js 13 app, I have implemented a live chat support button that is dynamically added based on the language selection. The code for rendering the button looks like this: import Script from 'next/script'; ... <div id={`onlinehelp-button ...

Is the append() function malfunctioning in jQuery?

Why is it copying two lines when I only want one line to be cloned on button click? Is there a way to make sure that only a single line is copied each time the button is clicked? Here is my code: $(function() { $('.add-more-room-btn').clic ...

Issue: [ng:areq] The argument 'HelloController' is not defined as a function, it is displayed as undefined

Struggling to integrate Angular with Django has been quite a challenge for me. After finally managing to make it work, I encountered yet another error. Each time I load the application, the following error message pops up: Error: [ng:areq] Argument ' ...

ReactJS form example: utilizing two separate submit buttons to perform distinct actions on the same form

I need to implement two submit buttons in my form. Both buttons should utilize the same inputs and form validation, but trigger different actions. export default function FormWithTwoSubmits() { function handleSubmitTask1(){ } function handleSub ...

What steps should I take to fix the Axios Network Error that keeps occurring while fetching data from my Express backend API?

I've been attempting to integrate my react native app with a database using the following code snippet: const axiosInstance=axios.create({ baseURL: config.API_URL }) try{ const res = await axiosInstance.get("/all") console.log( ...

What steps should I take to address and resolve this problem with my Angular $scope?

One of my partials utilizes a single controller named CaseNotesCtrl. However, I am encountering difficulties accessing $scope variables within this partial. Below is the code snippet: <div class="row" ng-show="$parent.loggedin" ng-controller="CaseNotes ...

I was caught off guard by the unusual way an event was used when I passed another parameter alongside it

One interesting thing I have is an event onClick that is defined in one place: <Button onClick={onClickAddTopics(e,dataid)} variant="fab" mini color="primary" aria-label="Add" className={classes.button}> <AddIcon /> & ...

Exploring the integration of data from two Firestore collections using JavaScript

I manage two different types of collections, one being called CURRENCY-PAIR and the other Alerts. The collection CURRENCY-PAIR includes the following information: Currency-Pair Name Currency-AskPrice Currency-BidPrice On the other hand, the Alerts colle ...

Interactive tooltip with hyperlinks powered by jQuery

Is it possible to create a pop-up window with links that behave like a normal tooltip but can be clicked on by the mouse? How can this functionality be achieved without losing focus when hovering over the links causing the window to close? jQuery(docume ...