Sharing session data between controller and view in an Express.js application

When logging in with the code below in the express controller to redirect to the main page:

 req.session.user = user.userLogin;
 if (req.session.user=='Admin') {
    global.loggedAdmin = user.userLogin;
 }
 else {
    global.loggedUser = user.userLogin;
 }   
 res.redirect('/');

In the main menu, we can check if a user is logged in with the following code:

nav#menu.panel(role='navigation')
    ul
        li
        if loggedUser
            li
                span.setting Welcome #{loggedUser}
                    a(href='/account')
                        i.fa.fa-cog
            li
                hr
            li
                a(href='/logout') Logout
            li
        else if loggedAdmin
            li
                span.setting Welcome #{loggedAdmin}
                    a(href='/account')
                        i.fa.fa-cog
            li
                hr
            li
                a(href='/articles') Articles
            li
                hr
            li
                a(href='/files') Files
            li
                hr
            li
                a(href='/users') Users
            li
                hr
            li
                a(href='/logout') Logout
        else
            li
                a(href='/login') Log in
            li
                hr
            li
                a(href='/register') Register

In app.js, make sure to include the session setup:

app.use(session({
    secret: 'sdfghjkl2345678tyu',
    unset:'destroy',
    resave: false,
    saveUninitialized: false
}));

If there are issues when logging in as an Admin and accessing the website from another device where the menu displays the user as an Admin, it is possible to pass session variables to the Pug template without using globals in the controller. To achieve this, you need to find a way to manage sessions across devices effectively.

Answer №1

It is crucial to implement app.use() middleware before the app.router() middleware for optimal functionality.

You can set up middleware in the following manner within the app:

app.use((req, res, next) => {
    res.locals.myVar = 'sample value';
    next();
});

To access the value of myVar, utilize the following code snippet in your index.jade file:

index.jade

extends layout
block content
    value of myVar is #{myVar}

Hooray!!!

However, it may be a good idea to reconsider the current procedure being used as it may not be the most secure or efficient method. Consider rendering the page with the appropriate JSON value instead.

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

What is the best way to obtain the value of a Promise within a function?

When working with Promises, accessing the value inside the .then method is simple. Take a look at this example: const Promise = require("bluebird"); const fs = Promise.promisifyAll(require('fs')); const mergeValues = require('./helper' ...

Use CSS specifically for codeigniter viewpage

I am unsure if it is possible, but I would like to load CSS and JavaScript within a view page instead of on include.php. Currently, the CSS file is loading on include.php and it is working correctly. What I want to achieve now is to load it directly inside ...

Transfer attributes, but have exclusions in React

At times, we all have a common practice of wrapping DOM elements in custom components. <CustomComponet id="abc" title="abc" nonDomProp="abc" ...andsoforth /> In this example, the custom component wraps a button with pr ...

Make sure a specific piece of code gets evaluated in a timely manner

To ensure the default timezone is set for all moment calls in the app's lifetime, I initially placed the setter in the entry point file. However, it turns out that this file is not the first to be evaluated. An issue arose with one of my reducers wher ...

Ways to update all URLs on a page with ajax functionality

My userscript is designed to modify the href of specific links on an IP-direct Google search page: // ==UserScript== // @name _Modify select Google search links // @include http://YOUR_SERVER.COM/YOUR_PATH/* // @include http://62.0.54.118/* // ==/Us ...

Having trouble with the `npm run dev` command in a Laravel project? You may be encountering a `TypeError: program.parseAsync is not

Recently, I integrated Vue.js into my ongoing Laravel project using npm to delve into front-end development with the framework. Following the installation, the instructions guided me to execute npm run dev in order to visualize the modifications made in . ...

Having trouble getting Material-UI classes to work with external SVG icons?

I recently crafted a Material-UI persistent drawer that contains a list item component designed to alter the icon color upon user interaction. However, my styling adjustments only seem to apply to Material-UI icons and not external SVG ones. If you'r ...

Utilizing Angular and Express for routing with the seamless integration of html5mode

I'm facing an issue with making angular and express routing work together with html5mode enabled. When I change state from '/' to my admins state, everything works fine until I refresh the page. Then I only get a json result of admins but my ...

Simplify a JSON array in JavaScript by removing nested layers

Looking to flatten a JSON nested array object into a flat array The key and value pair should be dynamic based on user input array I attempted to write the code myself but I'm not very familiar with JavaScript functions like concat, push, or others. ...

Struggling to update a document fetched through a Mongoose model and handled as a promise

Check out update #2 for more detailed information I am encountering difficulties while trying to make a simple update to a document that has been retrieved by querying a container through a Mongoose model. The query using find has two populations, but oth ...

Tips for efficiently storing data in a PostgreSQL database with Prisma's ORM

I need help figuring out how to save a buffer of data (image file) sent from a client to a PostgreSQL database. The data is stored as an Oid in the database, but I'm unsure of how to save the buffer of data as an Oid. Here's the model that Prism ...

Can anyone please guide me on how to extract the IP address of a specific individual using Node.js?

There's an individual running some kind of exploit scanner on my server. I'm receiving strange requests like: IP ADDRESS: ::ffff:127.0.0.1 www-0 (out): POST /cgi-bin/php5?%2D%64+%61%6C%6C%6F%77%5F%75%72%6C%5F%69%6E%63%6C%75%64%65%3D%6F%6E+%2D%64 ...

Determine in React whether a function returns a true value, and execute the code for false regardless

I have a hunch that this is related to the concept of asynchronicity. Essentially, I'm trying to validate whether a string (an answer to a question) already exists. If it does, the page should just show a message; otherwise, it should add the new que ...

Proper method for incorporating loading and error messages with the help of useContext and react hooks

Currently, I have a context.js file that makes an ajax call and stores the data in an array to be shared across components. While adding some 'loading ...' text during the loading process using axios, I feel there might be a better way to handle ...

Combining various functions into a single button

I am currently working on creating a full-screen menu that functions like a modal. Everything seems to be working fine, except for the fadeOut animation. Can someone please help me understand what is causing issues with my scripts/codes? I want the content ...

Ways to create a fixed button positioned statically at the bottom of a page

Currently, I am utilizing tailwind CSS to create a webpage with Next and Back buttons for navigation. However, an issue arises when there is minimal content on the page as the button adheres to the top. For visual reference, please view the image linked be ...

There is no data in the JSON object of the ExpressJS req.body

After sending JSON to my POST endpoint using Postman, my expressJS application incorrectly detects the JSON as an empty object. Versions: express: "4.17.1" npm: '7.11.1' node: '15.12.0' Code: index.js const express = requi ...

Tips for resolving a 401 Unauthorized Error when working with PayPal Webhooks in Node.js with Axios

When trying to integrate PayPal Webhooks into my Node.js application using Axios, I keep receiving a 401 Unauthorized error. The error message states: Error data: { name: 'UNAUTHORIZED', message: 'Authorization failed due to insufficient ...

Is it possible to utilize a single Promise multiple times?

// App.js sites[site_name].search(value).then(function(results) { console.log(results); }); // SearchClass.js Search.prototype.search = function(search) { var self = this; this.params['wa'] = search; return new Promise(function ...

Incorporating the Angular "dist" build file into the Node.js server.js script

Having some trouble deploying my MEAN stack app on Heroku. Managed to commit the app, but struggling to connect the ng build "dist" file to my server.js file. This is the snippet from my server.js file where I'm attempting to link the file: var dist ...