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
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 myindex.js
file. But by usinguser.username
in myejs
file I was able to get the same value after logging in and when I'm not logged in, the page loads just fine.simply use Nullish coalescing assignment (??=)
Change:
by
doc