title: Basic HTTP authentication except for localhost with Node using Express
body: <p>I am trying to set up authentication for a Node app using Express for clients that are not running on localhost.</p>
  
  <p>Basically, I have an RPi running Node and I'm using Chromium for the GUI of the device. The problem is that you can just type in the IP address to the device from any browser on the network and it will serve up the same content. This is desired in some cases, but I want to password protect it.</p>
  
  <p>This is my setup using <code>express-basic-auth</code>:</p>
  
  <pre><code>const express = require('express'),
        basicAuth = require('express-basic-auth');
  
  const app = module.exports = express();
  const server = require('http').createServer(app);
  
  // Hook Socket.io into Express
  const io = require('socket.io').listen(server);
  
  // Configuration
  app.use( basicAuth(
  {
    users: { admin: 'secret' },
    challenge: true
  }))
  
  app.use( express.static('./my_path/') );
  
  // Socket.io Communication
  io.sockets.on('connection', require('./modules/socket'));
  
  // Start server
  server.listen(3000, () =&gt; console.log("Express server listening on port %d in %s mode", server.address().port, app.settings.env));
  </code></pre>
  
  <p>This works, however, I don't want authentication for localhost.</p>
  
  <p>I can get the host from a request like this:</p>
  
  <pre><code>app.use( ( req ) =&gt;
  {
    debug( req.headers.host );
  })
  </code></pre>
  
  <p>I don't know enough about Node and Express to put it all together.</p>
  
  <p>Maybe there is something with <code>express-basic-auth</code> that I'm missing or different authorization middleware that I can use.</p>