Adding BasicAuth to the Kue Dashboard in an Express App

Do you use Kue and want to put it in its own folder that is password protected using BasicAuth or some other type of mechanism?

I know I’m not alone on this problem, yet nobody seems to have posted the concise answer. Here’s the solution.


Modules are their own little world

In Express (Node), there’s a couple of important points to know:

  1. Route declaration order matters
  2. Auth strategies are attached globally or to individual routes
  3. Modules tend to come with their own routes (Kue certainly does)

If we want to attach an auth strategy to Kue, you’d naturally want to attach an auth strategy to its entire scope. First, I tried locking down the entire module:

module.exports = function (app, config, passport) {
  var kue = require("kue");
  var auth = express.basicAuth(function(user, pass, callback) {
    var result = (user === 'username' && pass === 'password');
    callback(null /* error */, result);
  // any kue related settings can go here'title', 'Jobs');
  // create a wrapper to add auth on since without it we can't globally wrap kue's paths
  // bind the subApp to the desired path

Global auth can’t hook onto Kue

This fails to prompt for authentication. Why? Honestly, somebody better at Express can explain. I believe it has something to do with the way Kue is written since app settings are first-come first-serve.

Sub app it

In the gist above, you can see I create a sub app by passing in Express and creating an instance inside the file. I then apply the global auth settings (“subApp.use(auth)”) to this app before wrapping it. See the relevant code here:

  var subApp = express()
  // add authentication to the entire sub app
  // re-add (but dont put it in its own folder)
  // bind the subApp to the desired path
  app.use('/secret_location/kue', subApp)

Notice that I add the using a blank string as a first argument. That tells Express to put this sub-app in the same folder path as the app. Then, I bind that app to “/secret_location/kue.”

This works.