To verify if a user is an admin , I'm doing the following code in all my ejs files
in node.js routes, I send the user as a parameter when I render ejs
router.get('/', (req, res) => {
res.render('index.ejs',{query: req.session.username});
});
And in my frontend, I just do :
<% if(query == 'pedrosarkis'){ %>
<li class="nav-item admin">
<a class="nav-link" href="/admin">Admin</a>
</li> <% } %>
The "problem"(i guess it is) is that I have too many pages, which means that every route I'll have to pass the username as a parameter, is there a way to pass a parameter whenever a ejs is rendered? Like a middleware or something like that
It is quite simple, Use locals object, which according to docs, is
An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.
This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
So, in your main js file (app.js, server.js, whatever you name it), before your routes definition, you can use the following middleware
app.use(function (req, res, next) {
res.locals.query = req.session.username;
next();
});
and query will be accessible in every rendered ejs file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With