How to use specific middleware in Express for all paths except a specific one?

Sometimes, we want to use specific middleware in Express for all paths except a specific one.

In this article, we’ll look at how to use specific middleware in Express for all paths except a specific one.

How to use specific middleware in Express for all paths except a specific one?

To use specific middleware in Express for all paths except a specific one, we can use the express-unless package.

To install it, we run

npm i express-unless

Then we can use it by writing

app.use(requiresAuth.unless({
  path: [
    '/index.html',
    {
      url: '/',
      methods: ['GET', 'PUT']
    }
  ]
}))

to only use requireAuth except for the /index.html route. or the GET or PUT / routes.

Conclusion

To use specific middleware in Express for all paths except a specific one, we can use the express-unless package.