Search code examples
expressstatic-files

Express serve static file and run piece of code at /


I need to serve a folder of static files containing HTML and js which I achieve by

app.use('/', express.static('./public'));

I also need to run a piece of code whenever user enters the site, which I try to accomplish by

app.get('/', function (req, res) { // Piece of code });

But the piece of code doesn't executed

how to achieve them both


Solution

  • Have the middleware with the piece of code first and end it with a call of next(). This will pass control to the next middleware, that is, the express.static one:

    app.get('/', function (req, res, next) {
      // Piece of code
      next();
    });
    app.use('/', express.static('./public'));