So I'm serving a web page on the root route '/', and this page had an authentication middleware. Using regular
app.use('/', authorizeFront, express.static('../client/dist'));
would cause every route to be authenticated, which is what I'm trying to avoid. I've also tried using regex to match exactly '/' but it doesn't seem to be working.
app.use('/^/$/', authorizeFront, express.static('../client/dist'));
Is there any official way to do this? Thanks!
app.use does a partial match. Use app.get instead.
When using app.use("/") this will match any path and method that starts with "/",
This happens because app.use() is intended for global middlewares.
Instead you can use app.get("/", yourTargetedMiddlewaer) to target a specific route and a specific method (GET) in this case.
Another way to do this could be:
app.use("*", (req, res, next) => {
if (req.baseUrl === "") { // For / requests baseUrl will be empty
// Call authenticator and then call next() if auth succeeds else call next(err)
} else {
console.info("Bypassing Authentication");
next();
}
});
This will hit the middleware for all requests, but you have the control for which request you want to call the authenticator.