I was wondering if using res.locals like in this code example is bad practice or if there can occur any problems if you use it this way:
app.use((req, res, next) => {
const session = req.cookies.session
if (session) {
db.admin.auth().verifySessionCookie(session, true)
.then((decodedData) => {
res.locals.userId= decodedData.uid
next();
})
.catch(() => {
res.locals.userId = false
next();
})
} else {
res.locals.userId = false
next();
}
app.get("/", async (req, res) => {
console.log(res.locals.userId)
res.render("home.hbs")
})
Basically I:
- I verify the session-cookie in app.use (Im using firebase auth)
- I set the res.locals.userId = userId
- And then use the local i just set in the app.get
(I need to do it this way because I need the userId in my view, otherwise I need to run the verifySessionCookie function 2 times to get the userId which I want to avoid)