0

This is the home page or ('/') on localhost:3000. I wanted this home page to work in a way so that when a user logs in they will have their username displayed. Currently, this only works when the user logs in. However, I want to ignore the error if they are not logged in so that anyone could access the page without being logged in. I am using passport to authenticate users across a session if that help and you can view my home route and the snippet of where I'm executing the ejs in home.ejs file.

//Home page route in js

app.get('/',(req, res) => {
  res.render('home.ejs', {name: req.user.username})
})


//.ejs file snipped
       <li>
         <%if(locals.name){%>
         welcome <%=name %>
         <form class="" action="/Users/logout?_method=DELETE" method="post">
           <button type="submit" name="button">Logout</button>
         </form>
         <%}%>
       </li>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80

2 Answers2

3

You can use the optional chaining operator along with the nullish coalescing operator.

app.get('/',(req, res) => {
  res.render('home.ejs', {name: req?.user?.username ?? ''})
})
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • 1
    Note that support is good, but some people on mobile platforms might be stuck with a browser that still doesn't support the _optional chaining_ or _nullish coalescing_ operators. That doesn't matter if you're doing this on the nodejs side of things. +1 — I would use it anyway. – Stephen P Jul 16 '20 at 00:22
  • @hev1 you should check his nodejs version before use it. https://stackoverflow.com/questions/59574047/how-to-use-optional-chaining-in-node-js-12 – Ahmed ElMetwally Jul 16 '20 at 00:30
  • Thank you very much for the response! I took a look at the link that Ahmed provided and found that I am runnin node 12.18.0. Once I update it I will give it a try. Once again thank you! – Elijah Hernandez Jul 16 '20 at 02:50
  • @ElijahHernandez No problem. – Unmitigated Jul 16 '20 at 02:50
0

This should work :)

app.get('/',(req, res) => {
  res.render('home.ejs', {
    name: req.user !== undefined ? req.user.username : ""
  })
})
Tymur Taraunekh
  • 219
  • 1
  • 4