Trace Redirect Urls NPM Request

I'm open to new opportunities! For a full-time role, contract position, or freelance work, reach out at talha@talhaawan.net or LinkedIn.

With NPM request module it is quite easy to observe and trace all the intermediate urls before the final url is reached. We can do that using followRedirect option, which takes either true or false, or a function that should return a boolean value. The function takes a single argument response, that we can use to log the url the request is currently visiting.

For example, let’s try https://google.com

const request = require("request");

request({
  url: "https://google.com",
  method: "GET",
  followRedirect: function(response){ 
    console.log("REDIRECTED FROM: ", response.request.href)    
    return true
  }
}, function(error, response, body){
  console.log("ENDED AT: ", response.request.href);
})

The result will show the intermediate url it went through before reaching the correct https://www.google.com

  REDIRECTED FROM:  https://google.com/
  ENDED AT:  https://www.google.com/

Similarly, it also works for multiple redirects. Here’s an example of redirecting localhost links till /a4 link is arrived at.

const request = require("request");

request({
  url: "http://localhost:8080/a1",
  method: "GET",
  followRedirect: function(response){ 
    console.log("REDIRECTED FROM: ", response.request.href)    
    return true
  }
}, function(error, response, body){
  console.log("ENDED AT: ", response.request.href);
})
  REDIRECTED FROM:  http://localhost:8080/a1
  REDIRECTED FROM:  http://localhost:8080/a2
  REDIRECTED FROM:  http://localhost:8080/a3
  ENDED AT:  http://localhost:8080/a4

The above redirecting links/apis can easily be generated for testing in node express router as below.

router.get("/a1", (req, res, next) => {
  return res.redirect("/a2");
});

router.get("/a2", (req, res, next) => {
  return res.redirect("/a3");
});

router.get("/a3", (req, res, next) => {
  return res.redirect("/a4");
});

router.get("/a4", (req, res, next) => {
  return res.json({success: true});
});




See also

When you purchase through links on techighness.com, I may earn an affiliate commission.
We use cookies to enhance your experience. By continuing to visit this site you agree to our use of cookies. More info cookie script