Resolving unexpected behavior with res.locals and pug integration

I have a function in my app.js that allows the user-id to be accessible in pug templates.

app.use(function (req, res, next) {
  res.locals.currentUser = req.session.userId;
  next();
});

When logged in, I can access the id. However, when not logged in, the conditional statement in my pug template does not work as expected. Here is my code in the pug template:

if {currentUser}
    //do something
else
   //do something else.

The else part does not execute. I have checked and found that the variable currentUser is an object. Using JSON.stringify({currentUser}) from the pug template outputs {}.

When logged in, currentUser returns a string id, and when logged out, it returns an empty object. Both conditions satisfy the if{currentUser} clause.

Can anyone offer some help with this issue?

Answer №1

The issue lies in the if statement within your pug template:

With if {currentUser}, the condition will always be true. This is because if {currentUser} translates to if({}) when currentUser is undefined, resulting in a truthy value that evaluates to true.

This is due to the fact that an empty object {} is considered a truthy value that evaluates to true when coerced into a boolean.

if ({}) console.log('yes')

console.log(Boolean({}))

To resolve this issue, simply change it to if currentUser without the curly braces.

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

Ways to launch numerous URLs in express.js

I am currently developing a service similar to a URL shortener. While a typical URL shortener redirects the user to one page, my service needs to open multiple URLs simultaneously. When a user clicks on a link from my website, I want it to open multiple l ...

Enhancing presentation with a multitude of pictures

I am currently in the process of developing a slideshow feature that includes an extensive collection of images for users to navigate through using 'next' and 'previous' buttons. At the moment, each time a user clicks on the navigation ...

Creating a Commitment - Resolving the "Expected ')' after argument list" Error

Can someone please help me locate the syntax error in this code snippet? I've been searching for ages! An error occurred: Uncaught SyntaxError: missing ) after argument list promiseArray.push( new Promise(function (resolve, reject) { ...

Handling exceptions in AngularJS router-ui resolve functionality

In my app, I have the parent route listed below: .state('app',{ url: '/app', templateUrl: 'views/app.html', resolve: loadSequence('modernizr','moment'), ...

Cross-Origin Resource Sharing Problem - Angular version 8 with NodeJS and ExpressJS

I've attempted various solutions from different sources and have a feeling that I may be overlooking something minor here. In my setup, I have an AngularJS 8 application running on Node 10 with ExpressJS. The specific issue I'm encountering rela ...

I can't seem to figure out what's causing this error to pop up in my coding setup (Tailwind + Next.js). It

I've been struggling with this problem for a week now and despite my efforts, I haven't been able to find a solution yet. However, I have made some progress in narrowing down the issue. The problem arises when I try to execute the yarn build comm ...

What is causing a 500 internal error in Django when using Ajax?

Can someone help me troubleshoot why I keep receiving a 500 internal error when trying to execute an Ajax function? I attempted to send the response from view.py to the Ajax function in two different ways: using JsonResponse (see 'else' section i ...

Discover the steps for integrating an object into a Ext.grid.Panel using Sencha Ext Js

Currently, I am utilizing Sencha Ext Js 4 and have integrated an Ext.grid.Panel into my project. I am interested in adding another element inside the header, such as a textbox. Is this achievable? {filterable: true, header: 'Unique' /*Here i w ...

JavaScript loop used to create markers on Google Maps

I am currently in the process of developing a basic Google map which includes markers and involves looping through the data source for the markers. When I replace key.lng or key.lat with hardcoded values in the code below, everything functions correctly. ...

Handling Forms with Node and Express

I'm currently following a guide to create a node/express application using the jade template engine. I've encountered a 404 error when trying to submit a form. In my routing, I have this line: app.post('sign_up', sign_up); which is caus ...

loop through the links using their unique identifiers

Here is my current code in Jade/Pug: #pm_language.dropdown(aria-haspopup='true', aria-expanded='false') button#langbutton.btn.btn-primary.dropdown-toggle(type='button', data-toggle='dropdown') Lang [RU] ...

next.js experiencing hydration issue due to using div tag instead of main tag

I've come across an issue with hydration in NextJS and after debugging, I discovered that using the div tag instead of the main tag is causing this problem. The error message I'm receiving Here is the code snippet that triggered the error impo ...

Tips for preventing the loss of ajax calls when an Oauth access-token expires

As the creator of a JavaScript browser application (SPA) that communicates with a server protected by OAuth 2, I encounter the challenge of using short-lived access tokens and longer-lived refresh tokens. While this specific scenario involves my own server ...

How can Cheerio help you effortlessly and stylishly locate tags that meet various specific criteria?

I am attempting to scrape data from the webpage . Specifically, I am looking for all the <li> tags that are nested within an <ul> tag, which in turn is located inside a div with the class mw-parser-output and has a property of title. Is there ...

React - triggering a router link action before the link is assigned a value

In this scenario, the issue arises because the URL changes before the link receives a value. The state is being received directly through the component but by the time it happens, the component has already been clicked. This results in the value being as ...

What is the process for changing proxy settings through the command line when using Create React App?

I recently created a React project using Create React App and set up the development server to proxy API requests through the proxy setting in my package.json: ... "proxy": "https://dev-backend.example.com" ... However, I am looking ...

What could be causing the issue with res.download() function not functioning properly while passing a file path?

Hey there! I'm working on a cool project that involves allowing users to input a file path and then download it. I've set up a form with a text input field for the path, and am using Node.js and Express router to handle both the get and post requ ...

Enhance your textbox with more detailed descriptions than just displaying NaN

I am working on a form that includes select boxes. If a user selects an option from "Convert From" and another option from "Convert To" but does not enter a number in the input field, instead of displaying NaN in the result text box, I would like to show ...

I possess a solitary div element that requires dynamic replication

I have a single container and an unspecified number of rows of data. I want to display this data on HTML cards that are generated dynamically based on the number of rows. For example, if there are 10 rows of data, I need to create 10 card elements with ea ...

"Discovering a button press using the Gamepad API: A Step-by-Step Guide

I'm currently building a web page that can detect button presses on an Xbox controller and display a boolean value based on the pressed button. Right now, I have successfully managed to detect when a controller is connected and show it as a string. Ho ...