Shawn
Shawn

Reputation: 55

Express array of routes

The express documentation says that you can supply an array for the path variable in app.use(). I'm trying to have all routes in the routes array point back to the static folder in the static variable. Here's what I have:

const static = express.static(path.join(__dirname, '../build'));
const routes = ['/','/projects','/project1','/blog']
app.use(routes, static);

These routes all do work correctly with the static folder variable if I write a seperate app.use() function for each route, but it would be a lot more maintainable if I can get the routes in an array like in the documentation. The documentation doesn't show any examples suggesting that I need to map through the array.

Upvotes: 0

Views: 7525

Answers (1)

jfriend00
jfriend00

Reputation: 708026

So, it appears (based on experimentation as this is not in the doc), that when you pass an array of routes, Express finds the first item in the array that matches the current path and calls the route handler for that one only. Even if there are other routes that would also match (as in your case), it does not call the route handler again for those.

So, because '/' matches ALL routes when used with app.use(), it will always use that one and thus the others will never work properly when using the array, but do work properly when listed as individual routes. You can fix it by making sure that the most permissive routes are last. So, change your array to this:

const static = express.static(path.join(__dirname, '../build'));
const routes = ['/projects','/project1','/blog', '/'];
app.use(routes, static);

This moves '/' to the end so the others get a chance to match before the '/' is looked at and . '/' will only get used when the path wasn't one of the others.


FYI, this is a bit of a weird structure where you're directing multiple URL path prefixes all to the same ../build directory for express.static() to look there. There's no reason you need to do it that way. This appears to be an artificially created issue because of your URL design. Doing it this way will cause URLs like /x.js, /projects/x.js and /blog/x.js to resolve to the exact same x.js file in the ../build directory.

Upvotes: 5

Related Questions