How I created a simple URL Shortener using React and Node
— Url Shortener, React.js, Node.js, MongoDB — 2 min read
URL Shorteners are very useful if you want to remember a large URL of some website. They trim down the huge URLs into really small URLs which are easier to remember and share. Here will be creating one using React and Node.
How does it work?
- You enter your long lengthy URL in the input field and the slug that you want to have in your trimmed URL on the website and hit submit.
- As soon as you hit submit, the backend logic fires a POST request which makes an entry in the database of the URL. Also, at the same time, if you have not entered a custom slug for your URL, it generates a random id consisting of 6 digits. This id is mapped with the long URL and stored in the database. Otherwise a database query first checks that the slug you entered is not persent in the database. (Necessary because the slug needs to be unique) If it is present, you notifies you to enter a new slug.
- After this step, the URL along with the slug or the random ID is stored in the database.
Following Code shows the backend logic which handles the requests coming from the frontend.
Use of MERN stack
- Node.js along with its Express framework helps in creating routes quickly without worrying. Also, Node.js provides a lot of packages which help to create the application fast by focusing on the meat of the application and leave the unimportant things.
- MongoDB as the database is super easy to use and deploy. Also since we do not need to do complex queries, there is no harm in using NoSQL database.
- Finally using React helps us to greatly reduce the loading time as it only re-renders the components whose state changes.
Further tasks
Ideally, URL Shorteners are huge systems and are a good question in System design interviews. So what all things can we do to improve our current system:
- Use Redis/ other caching database. Accessing the main database for each GET request is not efficient. So we can use some caching algorithm such as LRU or FIFO and based on that we can put data in Redis which is caching database. So before accessing the main database, the system queries the cache database. If the data is not found in the cache, then only the main database is queried.
- As it is possible that lot many people can access that site and make GET requests. So in such case, we may need to implement a load balancer too.
- Also, we can have the user create an account and display only those short URLs that he has created. This would enforce security.