Express Handlebars Won't Render Data Express Handlebars Won't Render Data express express

Express Handlebars Won't Render Data


I had the same issue when I upgraded the handlebars package. To get your system back online as quick as possible remove the handlebars entry in package.json And then insert this line in its place.

"handlebars": "4.5.3",

From version 4.6.0 onward Handlebars forbids accessing prototype properties and methods of the context object by default. This is related to a security issue described here: https://mahmoudsec.blogspot.com/2019/04/handlebars-template-injection-and-rce.html

Refer tohttps://github.com/wycats/handlebars.js/issues/1642

An example from the above URL shows the Mongoose response converted into JSON:

app.get('/test', function (_req, res) {    Kitten.find({}).then(kittens => {        res.render('test.hbs', {            kittens: kittens.map(kitten => kitten.toJSON())        })    })});

If you are certain that only trusted developers and no end users have access to the handlebars templates it's possible to allow prototype access by installing the following package:

npm install @handlebars/allow-prototype-access

Here is an example of it's use:

const express = require('express');const Handlebars = require('handlebars')const expressHandlebars = require('express-handlebars');const {allowInsecurePrototypeAccess} = require('@handlebars/allow-prototype-access')const app = express();app.engine('handlebars', expressHandlebars({    handlebars: allowInsecurePrototypeAccess(Handlebars)}));app.set('view engine', 'handlebars');...

Another option is to use the mongoose .lean() function. This has the benefit of being much faster than a traditional mongoose query. But it does have some cons as well. By default, Mongoose queries return an instance of the Mongoose Document class. These objects contain a lot of internal state for change tracking and have additional methods such as .save(). Enabling the lean option tells Mongoose to skip instantiating a full Mongoose document and just return the plain javascript object.


Correct! I used to work with Sequelize and toJSON() did the trick.

If you tried it already and it didn't work, I think the same result in Mongoose could be achieved by using lean – mas 2 hours ago

I added .lean between .sort() and .then(), This worked!