URL Shortener Microservice

Libor Marko
2 min readDec 16, 2019

--

URL stands for Uniform Resource Locator and is used to specify addresses on the World Wide Web. A typical URL has the form of http://www.example.com/index.html , which consists of a protocol (http), a hostname (www.example.com), and a file name (index.html). I learned more about the URL while creating this API URL Shortener Microservice project with Node and MongoDB. You can see the project here, see the code in this GitHub repository or on my Glitch profile.

Technologies I used

  • Node.JS
  • Express
  • MongoDB
  • Mongoose
  • API
  • JSON
  • npm
  • JavaScript
  • HTML5
  • CSS3

How it works

The app’s code contains many comments that explain each individual part of the app into detail. Here I summarize the main app’s functionality. The app takes a posted URL and returns a shortened URL in the JSON response. If a client visits the shortened URL, the app redirects the client to the original URL. In a case an invalid URL is posted, the app returns an error invalid URL message.

I used MongoDB to create a single database to store my data. A database has a simple schema containing originalURL and shortenedURL strings. The app connects to the database with the mongoose module.

First, data is posted to the path [project_url]/api/shorturl/new. The originalURL requested value is parsed from the body. The hostname of the URL is checked by dns.lookup for validity. In case the URL is invalid, we get an error JSON response. Otherwise, we get JSON response containing the original URL and the shortened URL. Both URL’s are also sent to the database, while the shortened URL is calculated with Math module functions.

Once we assigned a shortened URL and stored it to the database, we can take it and post it to the path [project_url]/api/shorturl/:URLshortcut. The get method requests the shortcut parameter and works with it to find the corresponding model in the database. Thereafter we are redirected to the original URL.

--

--

Libor Marko

Senior FrontEnd Engineer. Follow me on LinkedIn or check my web page: http://libormarko.github.io