Is there a way to show a pre-set username value to prevent receiving an error message that says it's undefined?

My navigation bar is set up to show the following on the right side of the screen:

Welcome, <%= user %>

The issue is that I can only access the user data if I render it in the following way:

router.get("/", function (req, res, next) {
  const user = req.user.username;
  res.render("index", user);
});

The problem arises when I'm not logged in, preventing the webpage from loading and showing an undefined error:

TypeError: Cannot read properties of undefined (reading 'username')
. Is there a solution to adding a default value for user or displaying a Sign Up button instead to prevent this TypeError?

Answer №1

Utilize the Nullish coalescing assignment (??=)

Instead of:

const user = req.user.username;

Use:

const user = req.user.username ?? 'default username';

documentation

Answer №2

I finally figured out a solution to this issue. Initially, I believed the only way to retrieve the user value was by rendering it in my index.js file. However, utilizing user.username in my ejs file allowed me to access the same value both when logged in and not logged in, resulting in successful page loading.

<% if (isAuthenticated) { %>
          <li class="dropdown">
            <a class="nav-link">
              <%= user.username %>
            </a>
          </li>
       <% } %>

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

Struggling to display array components from a MongoDB record using express-edge templating

I am currently working through a blog tutorial to learn backend development using nodejs and mongodb. The tutorial seems a bit outdated as I have had to make some tweaks to get things to work properly. However, I am not following the tutorial exactly. Inst ...

Differences Between Jade's Express Template Engine and grunt-contrib-jade

Forgive me for my lack of expertise in this area, but I have a question that may seem somewhat naive. As I work on developing a web application using the standard MEAN stack (Mongo, Express, Angular, Node), I find myself configuring the template engine in ...

Ways to ensure all images have been successfully uploaded to Firebase before executing a function

Here's a function I've created that takes image URIs from the state, uploads them to Firebase Storage, and then updates the state with the download URLs: uploadImages = async (userID) => { // Loop through each image for (var index = 0 ...

Optimizing search queries by implementing MongoDB indexing on the IdAccount field for improved efficiency

I have been storing data in my MongoDB following a specific structure: Each customer has their own database There are around 40 collections per customer In total, there are 50 customers with approximately 2000 collections The combined size of all databas ...

Cookies are failing to be saved upon reloading the page

I found this snippet of code $(document).ready(function () { var d = new Date(); var newMinutes = d.getTimezoneOffset(); var storedMinutes = getCookieValue("tzom"); if (newMinutes != storedMinutes) { setCookie("tzom", newMinutes) ...

I am experiencing difficulty transferring the files to my API by using multer

For my car listing project, I am trying to set up a photo upload system. This is my first time using multer and I can't seem to figure out what's going wrong. I've done research, checked tutorials, and reviewed the documentation before reach ...

What are the disadvantages of using getBoundingClientRect() in ReactJS?

I recently incorporated the getBoundingClientRect() method into my project. However, a fellow React developer expressed concerns about its browser compatibility. In theory, shouldn't Webpack or Babel handle such compatibility issues? ...

Trigger a jQuery click event to open a new tab

On a public view of my site, there is a specific link that can only be accessed by authenticated users. When an anonymous user clicks on this link, they are prompted to log in through a popup modal. To keep track of the clicked link, I store its ID and inc ...

Encountering a DNS_PROBE_FINISHED_NXDOMAIN error when trying to use EC2 for Google OAuth

While utilizing an Ubuntu EC2 instance for my Google OAuth 2.0 strategy with the Google API platform, I keep encountering the DNS_PROBE_FINISHED_NXDOMAIN error. After choosing the desired Gmail account for authentication, the /google/callback is not funct ...

Why do certain URLs bypass the filters despite not meeting the criteria in the Chrome extension?

I am currently developing a Chrome extension that is designed to automatically close tabs when specific URLs are visited, helping me stay focused and avoid distractions. The list of sites that should trigger tab closures includes: YouTube Facebook Reddit ...

Optimizing the rendering of Font-awesome CDN JS for better performance on Pagespeed Insights

Instead of directly linking to the Font Awesome CSS, I have chosen to leverage the JavaScript provided by the trustworthy and efficient Font Awesome CDN. This allows for asynchronous loading of icons on my homepage, ensuring a seamless user experience. How ...

Customizing Javascript for Mouse Exiting Browser Window

I have implemented a JavaScript function on my website to display a lightbox when the visitor's mouse goes beyond the browser window. You can check it out here: [http://mudchallenger.com/index-test2.html][1] However, there seems to be an issue where ...

What is the best way to prevent a window from opening when the required form fields are left blank?

Currently, I have a submit button on my form that triggers a jQuery function to open a window based on the user's selection. However, I only want the window to open if all the necessary fields are filled out. I have the existing code for this function ...

How to manage simultaneous requests in Parse Server Cloud Code

Imagine having some Cloud Code running on a Parse Server: Parse.Cloud.beforeSave("UserProfiles", function(request, response) { const query = new Parse.Query("UserProfiles"); query.equalTo("user", request.user); query.count({ success: f ...

What is the process for generating a file in Node and Express on my server and subsequently transmitting it to my client for download? My technology stack includes NextJS for both frontend and backend operations

How can I generate a file using Express and Node on my server, and then successfully download it to the client? My tech stack includes NextJS for both frontend and backend, and with React as the frontend framework. I'm facing difficulty figuring out h ...

Transitioning from a traditional CURL method to utilizing AJAX and XMLHttp

I'm currently facing a challenge converting the curl code from an API named TextRazor to AJAX XMLHttp due to limitations on the platform I am working with. Despite trying various solutions shared by the community, I have been unsuccessful in retrievin ...

create an HTML element using JavaScript to display a box with dimensions of n

I am attempting to create a grid in an HTML document using only plain JavaScript. The idea is to take a number from a URL and use that as the basis for generating the grid. For example, if my URL looks like this: abc.html?num=5, then I would need to creat ...

Include draggable functionality to a seating chart that is generated dynamically

I developed a function that generates table seats dynamically with equal spacing. The issue arises when I try to drag names from a list and drop them onto the seats as children. Unfortunately, I can't seem to achieve this functionality with the dynami ...

Exploring the differences between two CSS style attributes using JQuery

Can someone help me with a quick question about CSS? I need to compare two style attributes, specifically margin-left. If the margin-left is less than 500px, I don't want to make any changes. However, if it's greater than 500px, I want to add ano ...

Error: Invalid character encountered during login script JSON parsing

I found this script online and have been experimenting with it. However, I encountered the following error: SyntaxError: JSON.parse: unexpected character [Break On This Error] var res = JSON.parse(result); The problem lies in the file below as I am unf ...