Reputation: 2946
Question: With Express, How can I alter the maxAge header for only files within a certain sub-folder, or filetype (ie. Images only)
I tried the following which did not work:
// Setting the app router and static folder
var fiveDays = 432000000;
// Use maxAge 0 for everything
var app = express();
app.use(express.static(path.resolve('./public'), { maxAge: 0 }));
// only cache images for 5 days
app.use(express.static(path.resolve('./public/modules/core/img'), { maxAge: fiveDays }));
app.use(express.static(path.resolve('./public/modules/filters/img'), { maxAge: fiveDays }));
app.use(express.static(path.resolve('./public/modules/spotlights/img'), { maxAge: fiveDays }));
app.use(express.static(path.resolve('./public/modules/users/img'), { maxAge: fiveDays }));
Result:
All resources return back with maxAge = 0.
Expected:
Images would have a maxAge header of 432000000.
I know its possible calling use on two seperate folders, my problem is that the images I want to alter the header on are inside a sub folder of my main express.static call.
Upvotes: 0
Views: 182
Reputation: 2946
Ended up using the serve-static module to accomplish this based on mime-type:
var serveStatic = require('serve-static');
app.use(serveStatic(path.resolve('./public'), {
maxAge: '5d',
setHeaders: setCustomCacheControl
}));
function setCustomCacheControl(res, path) {
if (serveStatic.mime.lookup(path) === 'text/html') {
// Custom Cache-Control for HTML files
res.setHeader('Cache-Control', 'public, max-age=0')
}
}
Upvotes: 1
Reputation: 4462
My guess is this is because every resource request is caught and processed by your first middleware. Have you tried putting this:
app.use(express.static(path.resolve('./public'), { maxAge: 0 }));
at the end of your snippet (after more specific mappings)?
Upvotes: 0