1

Hello I have express app where i need to plug a custom middleware/logic before accessing static folder for serving files, how i can achieve that without applying this middleware on every route. For now code looks like:

function middleware() {
  console.log('hello');
}

app.use(middleware).use(express.static('public'));

app.listen(8000, () => {
  console.log('server running on 8000');
});

app.get('/hi', (req, res) => {});

Issue is when hi is called middleware is executed as well and I want to execute it only if static files from public folder are called

1
  • There is a contradiction in your question. You say I want to execute something BEFORE static middleware, but I want it only happen if static middleware decides to serve a file. Commented Feb 10, 2021 at 17:47

2 Answers 2

1

first of all create a middleware.js in the middleware you can impalement business logic

module.exports = (req, res, next) => {
  let substring = ".html"; // static files
  if (req.originalUrl.includes(substring)) {
    console.log("hello");
  }
  next();
};

in app.js

const middleware = require('./middleware');

app.use(middleware).use(express.static('public'));

app.listen(8000, () => {
  console.log('server running on 8000');
});

app.get('/hi', (req, res) => {});
Sign up to request clarification or add additional context in comments.

Comments

0

I see 2 options:

  1. either your middleware first checks that the requested file exists

     app.get('*', myMiddleware, express.static('public'))
    
  2. or you run your middleware and static middleware if the path LOOKS like the static

     app.get('*(png|jpg|css)', myMiddleware, express.static('public'))
    

In both cases you can chain middlewares together (note multiple params in app.get). So that they are executed in this order and you can control the chain by using next() and next('route')

Your middleware would look like this:

    function myMiddleware (req, res, next) {
      // optionally check if file exists depending if you take option 1
      if (/* file exist check based on req.path */) {
        // if file doesn't exit, go to next router
        next('route') // here 'route' is a magic word, see https://expressjs.com/en/guide/using-middleware.html
      }

      console.log('hi')
      next() // don't forget this!
    }

NOTE: next('route') in option 1 only works with app.get not simple app.use, but i hope you only need GET for your static

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.