How does a URL shortener work?

Question

In this lesson, we utilize a URL shortening service to create an application. How does a URL shortener work?

Answer

A URL shortener is a service that generates a unique short URL, usually around ~10 characters long, which is mapped to a longer URL and leads to the same destination as the longer URL. The information is typically stored in a table or hash map in key-value pairs, where keys are the short URL, and the values are the original, longer URL.

For example, say you used the bit.ly URL shortening service to shorten some long URL that is 100’s of characters long. The service will generate a unique code comprised of alphanumerical characters (A-Z, a-z, 0-9) for the key. The short URL is typically the domain name, 'bit.ly', plus the generated code, like 'abc123', making the full URL 'bit.ly/abc123'. Then, the original, longer URL will be mapped to this shortened URL in the database. It will look something like the following,

TABLE:
short URL       long URL
bit.ly/abc123   example.com/verylongURL...
...

Now, when anyone goes to the short URL, it will direct them to the same destination as the long URL it is mapped to.

The uniqueness of short URL’s is usually guaranteed because of the sheer number of possible combinations of alphanumerical characters as codes. And, on the small possibility of a collision, the service would usually just regenerate a new code until it finds one that is not yet taken.

8 Likes

How long will the shortened URL be valid? Dose this depend on the company that converted it? e.g. https://goo.gl/ vs https://bitly.com/.

1 Like

You raise an interesting question. We have all seen platforms come and go. All the apps I ever built are gone now because the hosts were bought up or pushed out and I never followed the migration instructions. The stuff is plainly gone, now. My bad. Still really miss a couple of the apps and don’t have the motivation to ressurect them. Again, my bad.

Bottom line, shortened URLs have an immense value, and for the short term the major providers should be trusted to keep their DB alive through the interim.

6 Likes

Maybe another meaning for the word short in this instance is: ‘short-term’.

5 Likes

Hi

I have question regarding the flow of program. I am getting confused maybe someone can point me to right sequence of steps.

?How do XMLHttpRequest know which is the api url and api key to use?

XHR Post Requests III

Question: I am not sure why we calling this function renderResponse(xhr.response); and passing the response. How we got the response i am not getting it becuase we didn’t pass the data variable or accessing URL and API to get response. Sorry i am getting confused what happening there.

I am thinking this part of code will bring the shorturl because we are passing data variable here

xhr.open('POST', url);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.setRequestHeader('apikey', apiKey);
xhr.send(data);

Full Code

// Information to reach API
const apiKey = 'a2754c2cfed049a794fc362f379e22fc';
const url = 'https://api.rebrandly.com/v1/links';

// Some page elements
const inputField = document.querySelector('#input');
const shortenButton = document.querySelector('#shorten');
const responseField = document.querySelector('#responseField');

// AJAX functions
const shortenUrl = () => {
  const urlToShorten = inputField.value;
  const data = JSON.stringify({destination: urlToShorten});
  const xhr = new XMLHttpRequest();

  xhr.responseType = 'json';
  xhr.onreadystatechange = () => {
    if (xhr.readyState === XMLHttpRequest.DONE) {
  		renderResponse(xhr.response);
		}
  }
  xhr.open('POST', url);
  xhr.setRequestHeader('Content-type', 'application/json');
	xhr.setRequestHeader('apikey', apiKey);
  xhr.send(data);
  //console.log(xhr);
}
// Clear page and call AJAX functions
const displayShortUrl = (event) => {
  event.preventDefault();
  while(responseField.firstChild){
    responseField.removeChild(responseField.firstChild);
  }
  shortenUrl();
}

shortenButton.addEventListener('click', displayShortUrl);

Kind Regards
Atif

@object8545111749

at the bottom the shortenUrl function we specified the type of request “POST” and the url which is the rebrandly url that we are to make the post request to.

You specified the apikey to use and url of the website you want to make the request to At the top of main.js.
So I believe the above answers part of your question.
Now to how we get the shortened url

The inputField variable stores whatever you type in the input field provided in the mini browser.

    <input type="text" id="input" value="">

    <button id="shorten">Shorten</button>

  </form>

This is because,the inputField is tied to the input tag that has and id of “input”,you’ll see this in the index html file for the lesson.

Next we extract the value from inputField and store this in a variable urlToShorten.
Then we create an object with property of destination and a value of the url we want to shorten, we save all this in the data variable.


We did this because as you can see above, it is the format required by rebrandly api.
Think about it like this. If you want to buy a cup of coffee in the U.S, you cannot pay with Cedis or Naira because that’s not the valid or acceptable currency over there, so you’ll have to pay in Dollars.
or if you go to a shop and the owner only speak french,in order to make a request you’ll have to translate what you want to say from english to french for the owner to understand you.

Here the conditional if statement checks if the request is done processing and the renderResponse is a helper function we created to display the url returned from rebrandly in the fromat we like. For instance the api from rebrandly might be returned with a lot of curly braces or brackets, we use this function to display it in a manner the user can easily understand.
Imagine I want to make a request to an api and we assume it only understands french
myscript = “My name is ruronite”
myConvertedJscript = “Je m’appelle ruronite”
xhr.send(myConvertedJscript)
//now the api returns a response.
actualResponse = “bienvenue ruronite”
//the we convert this with our renderResponse function
renderResponse(actualResponse)
//outpurs “welcome ruronite”.
I hope that helps

1 Like

I think it would depend on the api you’re dealing with. But then again most people don’t really use a shortened api for the long haul,sometimes it’s just a quick and convenient way to market your products on social media.

Thanks a lot. This helped to clarify a lot. and your Analogy was awesome!!!