Node.js - Is Local Request

  • Estimated read time: 2 min read
  • Written by Chad Campbell on Dec 27th 2014

Node.js is great for creating web apps. When creating web apps, sometimes you have code that only needs to run in production, like some web analytics or social links. Other times, you have code that should only run in your local dev environment. In either case, you need a way to detect if a HTTP request is a local request, or a remote request.

To determine if a request is local, you have multiple options. It depends on whether you are using one of Node.js's frameworks (like Express ) or pure Node.js itself. This blog post shows you how to determine if a request is local in each of these frameworks. If you find this content helpful, please link to this page or use one of the social buttons to let me know. Now, the content.

Using Pure Node.js

Some individuals like to stay close to the metal. If that's your situation, you must evaluate the address and request objects directly. The request object has connection and socket objects to help you classify the request. The following snippet adds an isLocalRequest function to the server object.

var http = require('http');
var server = http.createServer(function(req, res) {
  // ...
});

// ... 

server.isLocalRequest = function(req) {
  var clientAddress = req.connection.remoteAddress || req.socket.remoteAddress;
  var serverAddress = server.Address();  

  return clientAddress === serverAddress;
}

The snippet above shows you how to detect if a request was made locally in pure Node.js. Personally, I first ran into a need for this code when I was migrating a site from ASP.NET to Node.js. To help with that, I found the Node.js for .NET Developers course on Pluralsight helpful. I also found the Introduction to Node.js course helpful.

With Express

Express is one of the popular web frameworks used with Node.js. To detect whether a request is local or not with Express you can use req.ips. To learn more about ExpressJS, check out the Web Development with ExpressJS course. I hope you found this post helpful. If you like what you see, please tell other developers by using the toolbar below to Like or +1 this post. If you need help with your Node.js apps, feel free to contact me.


Comments

comments powered by Disqus

Chad Campbell
Chad Campbell

Chad is an independent software professional. He has been named a Microsoft MVP five times. His books have been translated into multiple languages and distributed worldwide. He holds a computer science degree from Purdue University, where he also studied psychology.

Chad has built sites, apps, frameworks, libraries, and platforms using Java, .NET, and Node. He's ran his own startups and has created software for Fortune 100 companies. In short, Chad knows how to create software. From ideation to delivery. From start-to-finish.


Follow Chad Online