I have an express application that I want to port to AWS Lambda. It uses handlebars as middleware. I started out following this guide: https://dev.to/brightdevs/how-to-convert-an-express-app-to-aws-lambda--44gc
The difference between this and my code is handlebars. When I try to GET / for example, I get:
Error: /var/task/views/index.hbs: The partial include could not be found
at Object.invokePartial (/var/task/node_modules/handlebars/dist/cjs/handlebars/runtime.js:266:11)
at Object.invokePartialWrapper [as invokePartial] (/var/task/node_modules/handlebars/dist/cjs/handlebars/runtime.js:68:39)
at Object.eval [as main] (eval at createFunctionContext (/var/task/node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js:254:23), <anonymous>:8:28)
at main (/var/task/node_modules/handlebars/dist/cjs/handlebars/runtime.js:173:32)
at ret (/var/task/node_modules/handlebars/dist/cjs/handlebars/runtime.js:176:12)
at ret (/var/task/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:525:21)
at /var/task/node_modules/hbs/lib/hbs.js:63:19
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3)
My folder structure looks like this:
/server.js
/views/index.hbs
/views/partials/include.hbs
The relevant parts of server.js:
const express = require('express'),
hbs = require('hbs'),
app = express();
hbs.registerPartials(__dirname +'/views/partials');
app.set('view-engine', 'hbs');
app.get("/", (req, res) => {
res.render('index.hbs', {});
});
const PORT = process.env.PORT || 8080;
const isInLambda = !!process.env.LAMBDA_TASK_ROOT;
if (isInLambda) {
const serverlessExpress = require('aws-serverless-express');
const server = serverlessExpress.createServer(app);
exports.main = (event, context) => serverlessExpress.proxy(server, event, context)
} else {
app.listen(PORT, ()=>{
console.log('Server is up, listening on port ' + PORT);
});
}
I would expect index.hbs to be rendered as it does if I run the code locally with node .\server.js. Instead I got the could not be found error I pasted above. Any clues are appreciated.
I ended up solving it, but wanted to post the resolution since I spent a lot of time with this issue and putting the question together.
What did it: Requiring the "express-handlebars" instead of "hbs". I don't know why it did not work with hbs, but I don't want to spend any more time on investigating this.
I hope this might be useful for someone in the future.