'How to know the url that I will be redirected to? [nodejs] [node-fetch]

I am trying to load a JSON file from a url in google cloud. I am using the node-fetch package and it works fine for a couple of hours. The problem is that google changes the redirected url frequently. How can I make a get request to the url I will be forwarded to? Or at least know what url I will be forwarded to? I see there is also a package called request, but its deprecated.

This is the code

var express = require('express');
var router = express.Router();
var fetch = require('node-fetch');

router.get('/', async (req, res) => {
  
  const url = 'https://storage.cloud.google.com/blablabla/config.json';

  fetch(url)
    .then((res) => {
      if (res.ok) {
        return res.json();
      }
    })
    .then((data) => res.send({ data }))
    .catch((err) => res.send(err));
});

module.exports = router;


Solution 1:[1]

You can look up the final URL in the response headers. In your case res.headers.get('location') should do the trick.

Solution 2:[2]

The Response object has an undocumented url property. So, let's say you call

const response = await fetch(url, {
    redirect: 'follow',
    follow: 10,
});

response.url will be the URL of the last redirect that was followed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 thr0n
Solution 2 Dmitry Minkovsky