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

The external javascript file is unable to recognize the HTML table rows that are dynamically inserted through an AJAX request

I have a situation where I'm pulling data from an SQL database and integrating it into my existing HTML table row. Here's the code snippet: Using Ajax to fetch data upon clicking analyze_submit: $(document).ready(function(e) { $('#anal ...

Preserve the visibility of a text input form while the checkbox is selected

Within my HTML code, there is a form that includes a checkbox labeled "other." When this checkbox is selected, a textbox will appear. If the user types in text and submits the form, the textbox disappears, but the checkbox remains checked (as saved in loca ...

"When using `app.use(express.static`, it appears that the functionality is not working properly when the app is a sub

I attempted to implement something similar to this: var main = express(); main.use(express.static(path.resolve('./asset'))); main.route('someroute', someHandle); var app = express(); app.use(express.static(path.resolve('./asset&ap ...

What is the best way to ensure that this <span> maintains a consistent width, no matter what content is placed inside

So here's the deal, I've got some dynamically generated html going on where I'm assigning 1-6 scaled svgs as children of a . The span is inline with 2 other spans to give it that nice layout: I want these "boxes" to all be the same width be ...

The Bootstrap Navbar is causing the navigation bar to span across two lines

I'm having an issue with my navbar taking up two lines on desktop resolution, but fitting perfectly on mobile. I've spent hours going through the code with no success. Any help would be greatly appreciated. The HTML code is provided below. <! ...

Guide to setting up a datePicker in a cellEditorSelector

In my grid, I want to have different editors for different rows within the same column. The ag-Grid documentation provides information on how to achieve this using colDef.cellEditorSelector as a function: link I have successfully created unique editors fo ...

Managing the jQuery.noConflict function

Upon review, I noticed that the scripts I inherited start like this: var $j = jQuery.noConflict(); The purpose behind this code is not clear to me. While I understand the intent is to avoid conflicts, I am uncertain about the specific conflict it aims to ...

Managing Emitted Events in Vue.js Components within Components: A Guide

I have created a Toolbar Item component as follows: <template> <div class="flex cursor-pointer items-center justify-center rounded-full border-2 border-gray-300 p-1 shadow-sm transition-all duration-300 hover:scale-110 hover:bg-black ho ...

What is the best way to create fading text effects in an AngularJS application?

Running an AngularJS web application that showcases three words for 5 seconds each: Hello, World & Goodbye. The controller setup is as follows: self.currentIndex = 0; self.myTexts = ['Hello', 'World', 'Goodbye']; self.cu ...

Error: Unable to access null properties while attempting to address Readonly property error by implementing an interface

Here is the code snippet I am working with: interface State { backgroundColor: boolean; isLoading: boolean; errorOccured: boolean; acknowledgment: string; } export class GoodIntention extends React.Component<Props, State> { ... onCli ...

One the year is chosen, it will be automatically hidden and no longer available for selection

<div ng-repeat="localcost in vm.project.localCosts" layout="column"> <md-select name="localcost_{{$index}}"ng-model="localcost.year" flex> <md-option ng-repeat="years in vm.getYears()" ng-value="years">{{years}}< ...

a single button with dual functionalities

I am new to the development field and have a question about jQuery. I want a single button to perform two different actions. For example, let's say we have a button labeled Pause/Resume. When I click on the button, it should first display "Pause", and ...

Problem with BehaviorSubject: next() method is not functioning as expected

My goal is to utilize an angular service for storing and communicating data via observables. Below is the implementation of my service: public _currentLegal = new BehaviorSubject({ name: 'init', _id: 'init', country: 'init& ...

Troubleshooting Cross-Origin Resource Sharing problem with Stripe API integration in Angular

I am diving into the world of Stripe API and CORS for the first time. I've set up a POST request from Angular to my Node.js server. Since the client origin differs from the server destination, I have implemented CORS on the server side. When inspectin ...

ng-repeat did not properly listen for changes in the radio box selection

Feeling a bit confused here. I'm trying to call a function on change and pass the obj to it. From what I understand, since it's bound to the selected obj, I should be able to just use ng-model. However, in this situation, nothing happens when I s ...

What exactly do bootstrap, javascript, jquery, and ajax entail?

Exploring the world of client-side scripting to enhance web page dynamism and data collection has piqued my interest. I have come across programming languages like JavaScript, Ajax, and jQuery. However, uncertainty clouds my understanding as concepts remai ...

Using Node.js to retrieve a user's group memberships with NTLM authentication

I am currently utilizing express-ntlm for domain controller authentication, which is working smoothly. However, I now need to access the group details of the authenticated user, with authorization limited to a specific group. I have come across some examp ...

The contact form displays a confirmation message indicating successful submission, however, it fails to actually send the email

Having issues with a PHP script I created for the contact page on my website. After a user fills out and submits the form, they see a success message but the email is not sent. Can someone review this script and point out where I went wrong? <?php ...

Using the increment operator within a for loop in JavaScript

this code snippet causes an endless loop for (let i = 0; ++i;) { console.log(i) } the one that follows doesn't even run, why is that? for (let i = 0; i++;) { console.log(i) } I want a thorough understanding of this concept ...

Is there a way to retrieve all "a" tags with an "href" attribute that contains the term "youtube"?

My goal is to capture all a tags that have the href attribute containing the word youtube. This task requires the use of jquery. ...