Middleware On Res.render() When Using A Lot Of Routes
Solution 1:
If you have a bunch of pages that need to call res.render()
, but aren't passing custom options to each render, then you could isolate all those templates in their own directory and then use some middleware like this:
const path = require('path');
const fs = require('fs');
function renderStatic(dir, options) {
const regex = /^\.|\.\.|\/\.|\\\./;
options = options || {};
return function(req, res, next) {
let target = path.join(dir, req.path);
if (options.ext && !path.extname(target)) {
target = target + options.ext;
}
// don't allow leading dot or double dot anywhere in the path
if (regex.test(target)) {
next();
return;
}
fs.access(target, fs.constants.R_OK, function(err) {
if (err) {
// file not found, just move on
next();
} else {
res.render(target);
}
});
}
}
app.use(renderStatic(path.join(__dirname, "renderPublic"), {ext: ".ejs"}));
Note, you must isolate these template files in their own directory so that other files are not found there.
For safety completeness, this code also needs to filter out .
and ..
items in the path like express.static()
does to prevent an attacker from going up your directory hierarchy to get access to other files than those in the render static directory.
Then, for the routes you are using res.sendFile()
and no other logic, just isolate those HTML files in their own directory and point express.static()
at that directory. Then, the express.static()
middleware will find a matching HTML file in that directory and do res.sendFile()
for you automatically, exactly the same as it does for your CSS files.
Post a Comment for "Middleware On Res.render() When Using A Lot Of Routes"