Exclude a route from middleware

prevent middleware from running defined express routes

Thu, 03 Jan 2019

I had to implement this on one of my routes in a project that I’m currently working on. I use jwt tokens to make sure only authorized users can access my api and recently I needed to have a route that required no auth. I used this method to implement that while keeping my middleware active on all other routes.

Installation

We’re going to use Express Unless to implement that functionality. Express Unless conditionally skips a middleware on a route when a specific condition is met.

yarn add express-unless

or

npm i express-unless —save

Code

var unless = require('express-unless');
var cors = require('cors');
var express = require('express');

var app = express();

app.use(cors()).unless({ path: ['/online']}));

router.route('/online').post(function(req, res) {
  // Do Something
  res.status(200).end();
})

In the example above we defined express-unless, express and cors. Cors is our example middleware, you can switch that out for the middleware of your choosing.

Normally if we wanted to have include cors in all of our routes we would use the following line

app.use(cors())

To exclude the middleware from a specific route we would add in the unless function

.unless({ path: [‘/online’]}));

Now when we run our server, the route /online will not be affected by cors. The path field is also an array, meaning we can add in as many routes as we would like.

Buy Me A CoffeeDigitalOcean Referral Badge
Loading...
Edward Beazer

Edward Beazer - I just like to build shit. Sometimes I get stuck for hours, even days while trying to figure out how to solve an issue or implement a new feature. Hope my tips and tutorials can save you some time.

DigitalOcean Referral Badge