How to set caching headers on sub directories in express
caching, express, node.js
Solution
Express tests the middleware in order so if you put the most specific express.static call first, then it should work, i.e.
app.use(express.static(path.join(__dirname, 'public/images/icons'), { maxAge: 12345 }));
app.use(express.static(path.join(__dirname, 'public/images'), { maxAge: 1234567 }));
app.use(express.static(path.join(__dirname, 'public/else'), { maxAge: 9874567 }));
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));
etc.
Edit:
This won't maintain the paths, so I would do
function static(dirname, age) {
return express.static(path.join(__dirname, dirname), { maxAge: age });
}
and then call
app.use('/public/images/icons', static('public/images/icons', 12345));
app.use('/public/images/', static('public/images', 1234567);
etc.
The reason behind this is that my previous solutions mounts all of the static files at the root, whereas this solution mounts each directory at that file path with the correct maxAge
Problem
When using express with node.js, you can control the caching headers for public resources like this: ``` app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 })); ``` That sets up everything under the public folder to be statically available with a cache timeout of 1 year. But what if i want to set a different timeout value for other files under public? Say I have some images under public/images/icons that I want to have a smaller value that 1 year? I tried adding a second call to static like this: ``` app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 })); app.use(express.static(path.join(__dirname, 'public/images/icons'), { maxAge: 12345 })); ``` but it didn't work. It seems to just ignore the second statement. Thoughts?