nodeJs/Express dealing with missing static files nodeJs/Express dealing with missing static files express express

nodeJs/Express dealing with missing static files


The way that the express.static() middleware works by default is that it looks for the file in the target directory and if it is not found, then it passes it on to the next middleware.

But, it has a fallthrough option that if you set it to false, then it will immediately 404 any missing file that was supposed to be in the static directory.

From the express.static() doc:

fallthrough

When this option is true, client errors such as a bad request or a request to a non-existent file will cause this middleware to simply call next() to invoke the next middleware in the stack. When false, these errors (even 404s), will invoke next(err).

Set this option to true so you can map multiple physical directories to the same web address or for routes to fill in non-existent files.

Use false if you have mounted this middleware at a path designed to be strictly a single file system directory, which allows for short-circuiting 404s for less overhead. This middleware will also reply to all methods.

Example:

app.use("/public", express.static("/static", {fallthrough: false}));