skip to Main Content

I have a navbar which displays the following on the right side of the screen:

Welcome, <%= user %>

But in order for me to get the user I need to render it like so

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

There’s obviously a problem with this as if I am not logged in, I’m not able to load the web page at all due to getting an undefined error: TypeError: Cannot read properties of undefined (reading 'username'). Is there a way for me to add a default value to user or even display a Sign Up button so I stop getting the TypeError?

2

Answers


  1. Chosen as BEST ANSWER

    I found out how I can fix this. I thought the only way for me to get the user value was to render it in my index.js file. But by using user.username in my ejs file I was able to get the same value after logging in and when I'm not logged in, the page loads just fine.

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

  2. simply use Nullish coalescing assignment (??=)

    Change:

    const user = req.user.username;
    

    by

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

    doc

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search