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
request objects directly. The
request object has
socket objects to help you classify the request. The following snippet adds an
isLocalRequest function to the
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.
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.