Creating a Profile View
Build the profile page with EJS — display the logged-in user name, conditionally show login and logout links in the navbar.
Creating a Profile View
Let us build the profile page that displays the logged-in user's information and create a navbar that changes based on whether the user is logged in.
Profile View
<!-- views/profile.ejs -->
<html>
<head>
<title>Profile - OAuth App</title>
</head>
<body>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/auth/logout">Logout</a></li>
</ul>
</nav>
<h2>Welcome, <%= user.username %></h2>
<p>Google ID: <%= user.googleId %></p>
</body>
</html>
Conditional Navbar
<!-- Show login or logout depending on user state -->
<nav>
<ul>
<li><a href="/">Home</a></li>
<% if (user) { %>
<li>Logged in as <%= user.username %></li>
<li><a href="/auth/logout">Logout</a></li>
<% } else { %>
<li><a href="/auth/google">Login with Google</a></li>
<% } %>
</ul>
</nav>
Passing user to Views
// Home route — user may or may not be logged in
app.get('/', function(req, res) {
res.render('home', { user: req.user });
});
// Profile route — user is always logged in (auth guard)
router.get('/', authCheck, function(req, res) {
res.render('profile', { user: req.user });
});
Updated Home View
<!-- views/home.ejs -->
<html>
<head>
<title>OAuth App</title>
</head>
<body>
<nav>
<ul>
<li><a href="/">Home</a></li>
<% if (user) { %>
<li><a href="/profile">Profile</a></li>
<li><a href="/auth/logout">Logout</a></li>
<% } else { %>
<li><a href="/auth/google">Login with Google</a></li>
<% } %>
</ul>
</nav>
<h1>Welcome to the OAuth App</h1>
</body>
</html>
Key Takeaways
- Pass
req.userto views as a template variable - Use EJS conditionals (
<% if %>) to show login or logout links req.useris undefined when not logged in — check before using- The profile page is protected by the auth guard middleware