Accessing Server Variables in a NodeJS Express or Restify...

by Michael Szul on

No ads, no tracking, and no data collection. Enjoy this article? Buy us a ☕.

I've been working a lot with JavaScript, TypeScript, and Node.JS recently--even building out web services at work with Restify that I can consume on the front-end in some of our ASP.NET applications. Since we're mostly a Microsoft shop, our servers are Windows machines with IIS running. In order to get Node.JS web services working correctly, we'd need to deploy them to IIS.

This is where IISNode comes in, which is a fantastic module for delegating web requests in IIS to the Node executable.

When you're developing ASP.NET applications, however, you grow accustomed to some of the things available via IIS, including various server variables. How do you access these server variables in a Node.JS application?

When deploying to a Windows machine under the IIS web service, you're going to be using the IISNode module. Once this is installed, you can add a web.config file in the root of your application to redirect requests on that web site, or virtual directory, to your applications main entry point (e.g., the one where Express or Restify is listening for connections). What IISNode offers you are a handful of configuration options in your web.config to help pass through or alter IIS information.

One of these options is promoteServerVars. When you want to add in some custom IISNode configuration in your deployment, you add the <iisnode> element in your web.config. This goes inside of the <system.webServer> node.

The <iisnode> allows you to add IISNode configuration items, and these are attributes on the element. This is where you would add promoteServerVars. Here's an example:

<iisnode 
          nodeProcessCommandLine="C:\Program Files\nodejs\node.exe"
          promoteServerVars="HTTP_UID,LOGON_USER" />
      

In this example, my <iisnode> has two attributes. The first simply tells the module where the Node executable is. The second tells which server variables to expose. In this case, HTTP_UID and LOGON_USER.

Once exposed you can access them through custom headers within your Restify or Express application:

const user = req.headers["x-iisnode-logon_user"];
      

A couple of things to note:

  • The header will be prefixed with x-iisnode-.
  • The server variable names will all be in lowercase.