Skip to content

res.locals value not available in template engine #5081

Closed
@NazCodeland

Description

@NazCodeland

Hey, I have this middleware in app.js

app.use("*", isUserLoggedIn);

within isUserLoggedInMiddleware.js I have

import User from "../../../model/usersSchema.js";
import jwt from "jsonwebtoken";

export default function isUserLoggedIn(req, res, next) {
	const jsonWebToken = req.cookies.jwt;

	if (jsonWebToken) {
		//
		jwt.verify(jsonWebToken, process.env.JWT_SECRET, async (error, decodedToken) => {
			//
			if (error) {
				console.log(error.message);
				res.locals.user = "";
				next();
			} //
			else {
				const user = await User.findById(decodedToken.id).lean();
				res.locals.user = user;
				next();
			}
		});
	} //
	else {
		console.log("user is not logged in");
		res.locals.user = "";
		next();
	}
}

in my navigation.hbs template file I have

<nav>
	<h1><a href="/">Ninja Smoothies</a></h1>
	<ul>
			{{#if user}} 
				<span>Welcome, {{user.email}}</span>
				<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>
			{{/if}}
	</ul>
</nav>

prior to to upgrading to express@>=5.0.0-beta.1, once a user logged in, the navigation would only show the Log out option, but after upgrading, it still shows the Log in and Sign up options when a user is logged in.

I tried to see if I could access the user on res.locals.user = user within the template engine, and it seems like it's not avaialble within it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions