Using Express.JS middleware on only some routes

In Expressjs, every middleware you add, gets added to the middleware stack, i.e. FIFO.

Thus, if you have certain routes, which you'd like to have no authentication, you can simply keep their middlewares above others.

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use(<<pattern>>, authenticate)

Additionally, you can try using nodejs basic-auth module for authentication

Hope this helps!


Let's say your middleware is in "./middleware/auth"

I would create a base route for which the middleware should be applied, e.g.

app.use("/private", require("./middleware/auth"));

This will invoke your auth middleware, on any route which starts with '/private'

Thus, any API controller which requires auth should then be defined as:

app.use("/private/foo", require("./controllers/foo"));

Your middlware function will be invoked for any route within /private, before it hits your controller.

And any that do not require your middleware, should simply stay outside of the 'private' api context, e.g.

app.use("/", require("./controllers/somecontroller"));