Interceptor: Intercepting third party Request and Response on the Server side

In the previous post, we have seen

1) What are the interceptors?
2) How to intercept HTTP calls at the client side in Angular2 and Angular4?

On the server side, there are scenarios where we need to do some third party requests to get the final result that our node API will serve. There are various third-party libraries that help the user to make third part rest calls from the NodeJS itself.

Libraries like request, got, reqwest, superagent and axios are popular to do the same task. These libraries have its own benefits, some of these are promise base and some of these provide you with some extra benefits like prefixing the request URL, elegant way to append query string and intercepting the request and response.

You can find the comparison of all these libraries here.

This post will guide you how to intercept request and response of third-party rest call on the server side (NodeJS).

Among all the libraries following two are widely used and most elegant to make third-party calls from the server side.

1) SuperAgent
2) Axios


SuperAgent is a small progressive client-side HTTP request library, and Node.js module with the same API, sporting many high-level HTTP client features.

It comes with different individual plugins that can be installed separately to enhance the functionality of it. Plugins like

1) superagent-promise – Simple/dumb promise wrapper for superagent

2) superagent-mock – Plugin allowing to simulate HTTP calls by returning data fixtures based on the requested URL.

3) superagent-charset – Add charset support for node’s superagent

4) superagent-rxjs – Return an RxJS v5 Observable from your superagent request

5) superagent-load-balancer – Load balancer plugin for superagent


1) Install superagent and superagent-use modules

npm install superagent superagent-use --save

superagent module is to make third-party rest APIs and superagent-use is a plugin that works as a middleware or interceptor.

2) Require the modules

var request = require('superagent-use')(require('superagent'));

3) Then define the superagent middleware

// interceptor used by superagent to add jwt in the header for each 
request.use((req) => {
   req.header.jwt =”******”;
   return req;

We have added the superagent-use plugin to append a jwt header to each third party request.

4) And then make calls

 .query({ view: 'jsonView' });

Superagent is more useful than the request-promise as this module provide the promise and rxjs base APIs, URL prefix and an elegant way to append query string.


Axios is another promise based HTTP client for the browser and server-side (NodeJS)


  • Https request from server (nodejs) and client side (browser)
  • Promise base API
  • Request can be cancelled
  • Request and Response Interceptor
  • Automatic conversion to json


1) Install the module using npm

npm install axios –save

2) Require the module

const axios = require('axios');

3) Register the interceptor

// axios interceptor
 axios.interceptors.request.use(function (config) {
     let jwt = "****";
     config.headers.common.jwt = jwt;
     // Do something before request is sent
     return config;
 }, function (error) {
      // Do something with request error
      return Promise.reject(error);

4) And then make call

axios .get('http://host:port/rest/users?id=1')

That’s all folks. 🙂  

NodeJS : Continuation Local Storage or Thread Local Storage?

Sometimes you need piece of data, most of the time request/response objects, between different events of a request where it is generally not accessible. Continuation Local Storage is a package to access the current express request/response object from a point where that is not readily accessible. 


Suppose you have a rest API (/users) that serves the user data. The handler of this API calls the service layer to get user data. The service layer calls your facade layer to get data from either directly from the database or from third party URL. After getting the data from different sources, facade layer combines the data and return to service layer that further returned to the actual API.

Now API layer accepts the cookie that contains some token to validate the request. The same token is required at facade layer. One way is to pass the token extracted from cookie at API layer to service layer that further will pass to facade layer.

In some cases, there can be other layers and events in which you need the same token or user data. Passing data, layers to layers is not a good practice and not a cleaner way.

So to sort the same problem Continuation Local Storage (CLS) comes into the picture.

What is Continuation Local Storage (CLS)?

Continuation Local Storage is a package to access the current express request/response object from a point where that is not readily accessible. It works like thread-local-storage in multithreading programming like java. As nodejs is single threaded it supports events/callbacks instead of multi-threads. And to achieve the same It uses the concept of **namespace**.

Node.js is asynchronous and uses an event loop to manage the asynchronicity, AsyncListener allows you to write software that can keep hold of information across callbacks.

What is Thread Local Storage (TLS)?

From Wikipedia

Thread Local storage (TLS) is a computer programming method that uses static or global memory local to a thread.


Let’s get started with Continuation Local Storage

1) Install the continuation-local-storage package

npm install continuation-local-storage --save

2) Create namespace that will hold the objects that we want to access at global level

let app = express();
let cls = require('continuation-local-storage');
let namespace = cls.createNamespace('com.domain');

3) Define middleware that will bind the request and response object to namespace

app.use((req, res, next) => {
   var nameSpace = cls.getNamespace('com.domain');
   // wrap the events from request and response
   // run middleware in the scope of the namespace that we have created => {
       // set data to the namespace that we want to access in different events/callbacks
       namespace.set('data', "any_data");

4) Now this data can be accessed at any layer. For demo, logging the data that was set in the namespace


var getNamespace = require("continuation-local-storage").getNamespace;
let nameSpace = getNamespace("com.domain");
let data = nameSpace.get("any_data");
console.log("data : ", data);
Nodejs Interview Questions

Important Interview Questions for Node.js

1) What is Nodejs ?

2) What is NPM ?

3) Different types of API’s exist in Node (api methods)?

4) What is event looping ?

5) What is event emmiter in node.js ?

6) What is asynchronous calls in Node.js ?

7) Suppose we have 5 apis, we have to hit fifth api when all four have been completed.How can we do it ?

8) What are promises ?

9) What is promise all in node.js ?

10) What is clustering in node js?

11) Core features in node.js ?

12) Can I send body params in GET request ? if yes then how ?

13)  What are middle-wares in node.js ?

14) What is the use of next in node.js ?

15) Different types of exit polls in node.js ?

16) Explain Process in node.js ? 

17) Why node is single threaded ?

18) New features in node.js ?

19) What are create, read streams ?

20) Inheritance in node.js ?

21) How can I secure my cookies in node.js ?

22) What is the passport in node.js ?

23) Best way to manage the session in node.js ?

24) What do you mean by child processes in node.js ?

25) What is the cross-domain problem ?

26) If I want to solve the cross-domain problem for only specific type of APIs , how can I do it ?

27) How can we integrate Third party APIs in node.js ?

28) Explain callback in node.js ?

29) What is callback-hell in node.js? how can I solve this?

30) How can we install local and global dependencies in node.js ?

31) What are streams in node.js ?  

32) Explain package.json file in node.js ?

33) What is the meaning of tilde and caret in package.json

34) How can we control versioning about packages in node.js ?

35) Difference between dependencies and dev dependencies ?

36) What is npm start ?

37) If I want to explain my own command with npm how can I do it ?

38) Explain logging in node.js ?

39) Name node.js framworks ?

40) What is express

41) How can we add the prefix in node.js apis?

42) Use of cookie-parser in node.js?

43) How to make APIs session less ?

Further Reading

Javascript Interview Questions

AngularJS Interview Questions

NPM : Node Package Manager

NPM is a node package manager for the JavaScript programming language.It is the world’s largest software registry. It consistes of a command line client also called NPM and also the default package manager for the javascript runtime environment Node.js. It also have online database of public packages called the NPM registry that hosts thousands of free packages to download and use. Moreover it consists of a command line client that interacts with a remote registry (packages in the registry are in CommonJS format and include a metadata file in JSON format).

Functionalities of NPM (Node Package Manager)

1) Command line utility to install Node.js packages
2) Provide dependency management and version management of Node.js packaged
3) provide online repositories for Node.js packages


The NPM program is installed on your computer when you install Node.js. To install node.js refer:

we can check it is installed or not by

$ which npm
$ npm --version

With Node Package Manager we can install packages in local and global mode. To install packages in local mode we need following command

npm install packagename

In local mode it installs the packages in node_modules folder in parent working directory.This location is owned by the current user.

To install packages in global mode

sudo npm install forever -g

This means you would have to use sudo to install packages globally, which could cause permission errors when resolving third-party dependencies, as well as being a security concern. Global packages are installed in {prefix}/lib/node_modules/ which is owned by root (where {prefix} is usually /usr/ or /usr/local)

To check the npm configuration we need

$ npm config list
; cli configs
user-agent = "npm/3.10.10 node/v6.10.3 linux x64"
; userconfig /home/sitepoint/.npmrc
prefix = "/home/sitepoint/.node_modules_global"
; node bin location = /usr/bin/nodejs
; cwd = /home/sitepoint
; HOME = /home/sitepoint
; "npm config ls -l" to show all defaults

This gives us information about our install. we can also get our current global location by

$ npm config get prefix

This is the prefix, we can also change the value of prefix also by using this command 
For this let first create a new folder in our home directory to save it

$ cd ~ && mkdir .global_node_modules
$ npm config set prefix=$HOME/.global_node_modules

To uninstall the packages we can use

npm uninstall packagename

To fetch the list of installed packages we can use

npm list

There are lot of commands for more info refer:



Node.js tutorial with basic Setup and Installation

What is Node.js 

Node.js is an open source cross-platform for developing server-side and networking applications. It provides runtime environment and uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. Moreover applications are written in JavaScript and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux moreover its package ecosystem, npm is the largest ecosystem of open source libraries in the world.

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Historically, JavaScript was used primarily for client-side scripting, in which scripts written in JavaScript are embedded in a web page’s HTML to be run client-side by a JavaScript engine in the user’s web browser. It enables JavaScript to be used for server-side scripting and runs scripts server-side to produce dynamic web page content before the page is sent to the user’s web browser.


Previously javascript code is in working on the client side(front end) only. But with the power of node.js, we can now play with it on the server side (backend) also to generate the dynamic content. Node.js is actually based on the event loop programming model. It repeatedly waits for events and then runs any event handlers subscribed to those events and the event loop runs in a single thread.

Events can be:

1) A new HTTP request coming our way
2) Timer wait is complete
3) Next chunk of data is ready to be written to the file

Due to this process, multiple requests are handled concurrently by a single Node.js process. As long as these event handlers are small and wait for yet more events themselves everything works out nicely and no Javascript code is ever executed in parallel, all of this runs in a single thread.

Why node is single threaded?

Node.Js was built with the intention of supporting asynchronous operations and the fact is that the asynchronous operations have better performance and scalability when they are single-threaded over multi-threaded. This is the reason the Node.Js is single threaded.

Features of Node.js

1) Server Side java Script
2) Versatile
3) High Reliability
4) Asynchronous
5) Single Threaded
6) Run Anywhere
7) No Buffering
8) Easy Integration with JS Stacks
9) Speedy Execution

Top websites powered by Node.js


For more info visit: 


For Linux follow the guide.

For Windows download the installer.

To check if nodejs is installed successfully, Open command prompt and type

node -v

What is NPM 

npm is a package manager for the JavaScript programming language. It is the default package manager for the JavaScript runtime environment Node.js. It consists of a command line client also called npm, and an online database of public packages called the npm registry.


Set up node.js application

Before create a node.js application we need to install express framework using npm command. ( Express is a lightweight and easy to use Node.js framework that helps to create and manage our apllication into MVC architecture.Express provides a robust set of features to develop mobile and web applications)


To install express run 

npm install express -g

The above command will install express globally on your machine. then type

npm install express-generator -g

It will install the express generator globally on your machine. After that to create the skeleton of node app just type 

express projectName

This will create the node.js skelton with name projectName, where project name is the name of your app skeleton. After that just go in the app structure and install the app dependencies by 

cd projectName
npm install

It will create the node modules folder where it install all the dependencies, after that just type npm start command to start the server and check it works or not. To check its proper working after run the start command just open any browser and type localhost:3000 to check the server is listening or not (3000 is the default port uses by it).

npm start

Now open any browser and hit localhost:3000

package.json : Difference between (~) tilde and caret(^)

A node application contains a file at the root level that holds the meta data related to project like project name, GitHub repository, scripts and the most important project dependencies.

The package.json manage your project dependencies with the package name and their version number.

For example:

"dependencies": {
"@angular/animations": "^4.2.5"

From the above dependency @angular/animation modules’s version consist of


Patch_Version : Some bug fixes with backwards compatibility

Minor_Version : Bug fixes + New features + Backward compatibility

Major_Version : There are breaking changes so test before applying this version

~ (tilde)

If dependency version has prefix ~ then it will lock the major and minor version and next time you run npm install or npm update, will install the latest patch version no matter what patch version is defined in dependency version.

Suppose if there is update in patch and version 4.2.6 is available then 4.2.6(latest) will be installed but major and minor version will be same.

^ (caret)

Dependency with ^ prefix lock the major version and install the latest minor version no matter what patch and minor version has defined in package.json

Without ~ and ^

If no prefix is defined then the same version will be installed as defined.

For more on the package.json visit the npm site.