I've successfully created my first web application using Node, EJS and MongoDB.
I want to hide my login/sign up links when user logs in and want to display logout button in my header file.
Anybody got a solution? I've already tried Expressjs how to show / hide a div in case user its logged But for some reason, the user variable in ejs file is initialising to null, so only one case is exectuting
Here is my header.ejs file:
<h1><a href="/">RideShare</a></h1>
<ul>
<li><a href="/find">Find a ride</a></li>
<li><a href="/create">Create a ride</a></li>
<li><a href="/myrides">My rides</a></li>
<%if (!user) { %>
<li><a href="/login">Sign in</a></li>
<li><a href="/register">Sign Up</a></li>
<% }else{ %>
<form action="/logout?_method=DELETE" method="POST">
<button type="submit">Log Out</button>
</form>
<%}%>
</ul>
i think you should set user data after login in local session
server.js
app.use(function (req, res, next) {
res.locals.session = req.session;
next();
});
headers.ejs
<h1><a href="/">RideShare</a></h1>
<ul>
<li><a href="/find">Find a ride</a></li>
<li><a href="/create">Create a ride</a></li>
<li><a href="/myrides">My rides</a></li>
<%if (!locals.session.loggedin) { %>
<li><a href="/login">Sign in</a></li>
<li><a href="/register">Sign Up</a></li>
<% }else{ %>
<form action="/logout?_method=DELETE" method="POST">
<button type="submit">Log Out</button>
</form>
<%}%>
</ul>
and put this in your login API
router.post('/login', (req, res) => {
req.session.loggedin = true
})