ngrok: Lightweight Tool to Expose Localhost Server to Internet

Ngrok is a lightweight command line tool to expose your local running server to  the internet by providing public URL. It creates a secure tunnel to your local running server and then the same server can be accessible over the internet on different machines for testing and development purposes.

Download and Setup

You can download the command line tool from this link. A zip file will be downloaded that contains the command line tool. And that’s all.

To expose your localhost server to internet you tell where your local server is running and the port number. Hit the following command to expose your localhost server to internet

ngrok http 3000

Ngrok is the command and the second parameter is the protocol and the last is port where your application is running.  After running the above command you will see the following output on the console

It will show the following detail




Session status

It could be online|offline. Status of your application is it running on not?

Session expires

When will the ngrok session expires default is 8h


Version of the tool


Where is the public server is running that is pointed to your localhost server

Web interface

Web interface of tool where you can check no of connections to your app and monitor the traffic


Public URL of local server


No of connections to your application


The public url will be like You can specify your subdomains but for that you have to upgrade your account.


For more detail

ngrok Documentation

ngrok Official Website

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. 🙂  

Http Interceptor : Intercepting HTTP requests and response in Angular4

In the previous post, we have seen how to intercept the http request and response by extending Http class from @angular/http module.
To recall an http interceptor is

Interceptors are components that intercept calls and are used for logging, auditing, security and to implement authentication.

An Http interceptor is a middleware that can hijack http request/call before it reaches to the server and its response before it reaches the actual targeted function.

In Angular2 there was no cleaner way to implement interceptors, But Angular4 has an elegant and cleaner way to do this.  

What are we going to do?

We will create an interceptor class that will intercept the response object to check if the response status is 401 that is Unauthorized then the user will be redirected to the login page.


To Create interceptor we will create a class HttpServiceInterceptor that will implement the HttpInterceptor interface from @angular/common/http module and register the same as providers in app.modules.ts. Following are simple steps to achieve the same

1) Create a class (HttpServiceInterceptor) and implement HttpInterceptor interface

export class HttpServiceInterceptor implements HttpInterceptor { }

2) Provide definition to intercept method of HttpInterceptor interface

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

And the full code

// http-service-interceptor.ts
import { Injectable, Inject } from "@angular/core";
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from "@angular/common/http";
import { DOCUMENT } from "@angular/common";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/do";
export class HttpServiceInterceptor implements HttpInterceptor {
    constructor( @Inject(DOCUMENT) private document: any) { }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).do(
            (event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                    return event;
            (err) => {
                if (err instanceof HttpErrorResponse) {
                    if (err.status === 401) {
                        this.document.location.href =

3) Import HttpClientModule and HTTP_INTERCEPTORS from @angular/http/common module

import { HttpClientModule,HTTP_INTERCEPTORS } from "@angular/common/http"; // to make http request
import { HttpServiceInterceptor } from "../interceptors/http-service-interceptor"; // response interceptor

4) Make an entry for HttpClientModule in imports array

imports: [

5) Add provider for HTTP_INTERCEPTORS and use the class (HttpServiceInterceptor) that we created for interception

providers: [{
   useClass: HttpServiceInterceptor,
   multi: true

6) Then use HttpClient instead of http as your http service

import { HttpClient } from "@angular/common/http";

7) Inject in the constructor

constructor(private http: HttpClient) { }

That’s all folks!! Isn’t it easy? Oh yes..

Http Interceptor : Hijack http request and response in Angular 2

Interceptors are components that intercept calls and are used for logging, auditing, security and to implement authentication.

An Http interceptor is a middleware that can hijack http request/call before it reaches to the server and its response before it reaches the actual targeted function.

One of the most famous usages is to implement authentication. Interceptors are very useful when one wants to append a header in each request or want to manipulate the response before it reaches the actual calling party. It can also be used to show and hide loader on the screen based on http call.

Another use is to return json object as response as we use the .map method in every request’s response to return res.json, so the response can be hijacked or intercepted to do the same for all the requests.

Angular2  has not implemented the concept of interceptor but this can be done by extending the HTTP service. There are few steps that you need to follow to make this working.

1) Extend Http Service to provide your own functionality

// http-interceptor.ts
import { Injectable } from'@angular/core';
import { Http, XHRBackend, ConnectionBackend, RequestOptions, RequestOptionsArgs, Response, Headers, Request } from '@angular/http';
import{ Observable } from'rxjs/Observable';
import 'rxjs/Rx';
export class HttpInterceptor extends Http {
     constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
         super(backend, defaultOptions);
     * Error handler to handle is there is any error 
     * @param error 
     * @param caught
     * @returns {ErrorObservable}
     private onCatch(error: any, caught: Observable<any>): Observable<any> {
         if (error.status === 500) {
             return Observable.throw(newError(error.status));
         else if (error.status === 401) {
             return Observable.throw(newError(error.status));
      // interceptor method to intercept request and response
     get(url: string, options?: RequestOptionsArgs): Observable<any> {
         // options and url can be updated here to append new headers
          options.headers = {'Authorization' : 'token'};
         return super.get(url, options)
                     .map((res: Response) => {
                         // on sucess return res.json
                         return res.json();
                      }, (error: any) => {
                           console.log("On error :(");
                     .finally(() => {
                         console.log('After the requset has been completed :)');

2) Add this extended service in app.module.ts

providers: [{
    provide: HttpInterceptor,
    useFactory: httpInterceptor,
    deps: [XHRBackend, RequestOptions]

Where httpInterceptor is an exported function that returns the new instance of extended HttpInterceptor class.

// to return an instance of HttpInterceptor class
export function httpInterceptor (backend: XHRBackend, defaultOptions: RequestOptions) {
    return new HttpInterceptor(backend, defaultOptions);

Instead of creating this function one can directly use the function in provider section but this creates problem while bundling the project. The following error can be encountered

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference
to an exported function (position 45:5 in the original .ts file), resolving symbol AppModule in D:/SK/Study/Material/MDCAngular/src/app/app.module.ts

Now to use this extended class inject the implementation of HttpInterceptor class like this where you want to inject http service

constructor (private http: HttpInterceptor) { }

Further Reading