Home > Software engineering >  Express middleware runs for every imported .js file, is this normal?
Express middleware runs for every imported .js file, is this normal?

Time:06-12

so I set up a basic express app that serves a static file from a directory named public.

The public directory contains 3 files "index.html", "script1.js", "script2.js", and "script3.js". The script files are just empty .js files.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
</head>
<body>
  <h1>Middleware</h1>
  <script src="./script1.js" crossorigin="anonymous"></script>
  <script src="./script2.js" crossorigin="anonymous"></script>
  <script src="./script3.js" crossorigin="anonymous"></script>
</body>
</html>

server.js

const express = require('express')
const path = require('path')

const app = express()

app.use((req, res, next) => {
  console.log('middleware was ran', new Date())
  next()
})

app.use(express.static(path.resolve(__dirname, 'public')))

app.listen(3000, () => {
  console.log('listening on port 3000')
})

Whenever I run the server.js file and visit the '/' route I get an additional "middleware was ran" output to the console for each script file that I am including. In this case my out put would be:

listening on port 3000
middleware was ran 2022-06-11T21:45:21.609Z
middleware was ran 2022-06-11T21:45:21.644Z
middleware was ran 2022-06-11T21:45:21.648Z
middleware was ran 2022-06-11T21:45:21.650Z

Why is that happening?

CodePudding user response:

Yes, this is normal. Any imported file (that isn't already cached by the brower) causes a request to your server to fetch that imported JS file. Since it appears you have your server configured to use express.static() to serve those files, then any middleware BEFORE your express.static() middleware will see those requests.

Since your express.static() middleware will "handle" the request and not continue further routing, any middleware after express.static() will not execute when a static file is served by express.static(). Middleware matches and executes in the order declared until the point where a request handler (middleware or not) sends a response and stops further routing by not calling next().

is there any way to limit that ?

If you put your express.static() middleware first, then it will satisfy these requests for static files first and any middleware following it will not execute.

const express = require('express');
const path = require('path');

const app = express();

// put this first so static files are served first
// and any other middleware after this won't execute
app.use(express.static(path.resolve(__dirname, 'public')));

app.use((req, res, next) => {
  console.log('middleware was ran', new Date());
  next();
});


app.listen(3000, () => {
  console.log('listening on port 3000');
});
  • Related