Learning JWT Part 11 - Check current user and conditional rendering
===

---
###### tags: `JWT`
## What is `res.local`?
The `res.locals` is an **object** that contains the local variables for the response which are scoped to the request only and therefore **just available for the views rendered during that request or response cycle**.
## Check current user
Now we can log in and log out user, but what if user never loges out, but he/she/they might close browser accidentally, does he/she/they need to log in again?
Here is the basic flow:
- Is the user has token?
- Yes, then verify the token.
- Is the token valid?
- No, then set user to be `null`
- Yes, find the user ID from token and set local res as user
- No, then set user to be null.
```javascript!
// authMiddleware.js
...
// check current user
const checkUser = (req, res, next) => {
// grab token from browser
const token = req.cookies.jwt;
// Check if token exists and is verified
if (token) {
jwt.verify(token, process.env.JWT_SECRET, async (err, decodedToken) => {
if (err) {
console.log(err.message);
res.locals.user = null;
next();
} else {
let user = await User.findById(decodedToken.id);
res.locals.user = user;
next();
}
});
} else {
res.locals.user = null;
next();
}
};
...
```
Where should we place `checkUser`?, we need to check every route.
```javascript
// app.js
const { requireAuth, checkUser } = require("./middleware/authMiddleware");
// routes
app.get("*", checkUser);
app.get("/", (req, res) => res.render("home"));
app.get("/smoothies", requireAuth, (req, res) => res.render("smoothies"));
app.use(authRoutes);
```
Now the `checkUser` will check if user is valid in every route, so let's move on to frontend side to make conditional rendering for the `header.ejs`.
Here is the flow:
- If user is log in
- Show `Welcome, user's email`
- Hide `Log in` and `Sign up`
- User loges out
- Show `Log in` and `Sign up`
```htmlembedded
// header.ejs
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Smoothies!</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<nav>
<h1><a href="/">Ninja Smoothies</a></h1>
<ul>
<% if (user) { %>
<li>
Welcome, <%= user.email %>
</li>
<li>
<a href="/logout">Log out</a>
</li>
<% } else { %>
<li>
<a href="/login">Log in</a>
</li>
<li>
<a href="/signup" class="btn">Sign up</a>
</li>
<% } %>
</ul>
</nav>
```