How to set caching headers on sub directories in express

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?

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

the source code of the static middleware show that it intercepts anything that looks like a filepath from the path part of the url, stats the file from the configured root directory and serves it if it exists.

There's no possibility to change the maxAge options with the vanilla middleware.

What I suggest is you make your own middleware (just a function) and create the appropriate number of static middleware (on per directory) and forward your req, res, next parameters to the correct one