Search code examples
node.jsexpressmiddlewarenode.js-connect

Middleware with dynamic mount point?


I would like to serve static assets for paths that begin with an cache buster:

  • example.com/40/app.js
  • example2.com/5/hello/hello.js
  • example2.com/60000/hello/world/some-file.js

Does Express support this?

I attempted to create a custom middleware that

  • creates a copy of the request object
  • strips the cache buster from req.path
  • passes the new req object to express.static

but this doesn't seem to work. It appears Express.static doesn't inspect req.path directly.

What's the best way to achieve this? Any help would be appreciated. Thanks.


Solution

  • If I understand correctly you want to filter express middleware based on the url? Mostly when you need that you wrap the middleware.

    function (req, res, next) {
        if (req.url === 'something') {
          return express.static(__dirname + '/public')(req, res, next);
        }
    
        next();
    }