Sometimes you may need to send a URL to several people, and this URL may have additional parameters, which tends to make it quite long. This can be quickly resolved using URL shorteners. URL shorteners are tools used to create a unique URL that will redirect a user to a specified URL. This new URL is shorter and contains the URL shortener's site address with a combination of random characters. In this article, we will build a URL shortener web application using React.js and Shrtcode URL shortener.
What is a URL Shortener?
URL shortening is a web technique in which a Uniform Resource Location (URL) can have a substantial reduction in length, providing a new unique URL that still directs to the specified web page. The general idea is to reduce long web addresses into a shorter format that is easier to remember, track, share in messages or use in print work.
URL shorteners are websites that offer the service of URL shortening. These sites offer a service that maintains the connection between the original and shortened URLs. They are responsible for redirecting users to the desired web page. The new shortened URL contains the URL shortener's domain address, plus a combination of characters and numbers. Some examples of popular websites that offer URL shortening services are Shrtco.de (which we'll be using), Bit.ly, T.co, Tiny URL, Rebrandly, and Tiny.cc.
- Shortened URLs are particularly desirable when a web page address contains parameters such as search query, pagination, or session data. These parameters make URLs span several characters long and difficult to distribute, share or memorize, hence, the need for URL shorteners.
- When writing books, either soft or hard copies, long URLs may span more than one line and, in the case of hard copies, will be difficult to copy out into a web browser.
- Some messaging platforms also have a character limit to messages, which can make sending long URLs challenging.
- URL shorteners make URLs more appealing and can increase conversion rates.
- URL shorteners offer service to money the traffic rate, i.e., the number of shares or clicks carried out on the shortened URL.
- URL shorteners are easy to use and can shorten URLs with just a button click.
- Shortened URLs can prevent you from spooking people by sending chunky URLs which may look suspicious.
For this tutorial, we will build a URL shortener using Shrtco.de. Shrtco.de offers a free, easy-to-use API for shortening URLs, with no prior authentication methods needed to access it. It is secure and privacy-friendly. Below are a few reasons why you should consider using Shrtcode to shorten URLs:
- Shrtco.de continuously ensures shortened URLs always redirect to the desired page. Over the years, various URL shortening services have been targets of hackers and have been made to redirect users to sites other than the desired result.
- All shortened URLs are periodically scanned as a pre-emptive measure against malware.
- Shrtco.de cares about privacy. It does not track visitors to shortened URLs and also provides a security feature to add a password to shortened URLs to prevent people from accessing your site without authorization.
- Shrtco.de can make shortened URLs even shorter by replacing the "shrtco.de" part in the link with "9qr.de" if the user so desires.
- Apart from text URLs, Shrtco.de can also generate emoji links as shortened URLs if you desire a fun-looking link.
Building the URL shortener
For the URL shortener, we will be using the React.js framework. We will require a simple user interface featuring an input field, a button to submit the URL to be shortened, a box to display the shortened URL, and a copy to clipboard
button. We will use TailwindCSS
for easy styling of the application. We can create this in the App.js
file as shown below:
import "./App.css";
import {React, useState} from "react";
function App() {
return (
<div className=" container h-screen flex justify-center items-center">
<div className=" text-center">
<h1 className=" text-2xl font-medium text-blue-500 mb-4">
Our <span className=" text-yellow-400">URL Shortener</span>
</h1>
<div>
<input
className="outline-none border-2 border-blue-500 rounded-md backdrop-blur-xl bg-white/20 shadow-md px-3 py-3"
type="text"
placeholder="Enter link to be shortened"
/>
<button className=" bg-blue-500 text-white px-8 py-3 ml-4 rounded-md">
Submit URL
</button>
</div>
</div>
</div>
);
}
export default App;
In the code above, we have a simple input field and a button. If we run the code with the npm start
command, we get a result similar to the below image:
To handle user input in the field, we will create a state to manage this.
const [userInput, setUserInput] = useState("");
We can append this to the input field value
and onChange
properties:
<input
//...
value={userInput}
onChange={(e)=>{setUserInput(e.target.value)}}
/>
Open Source Session Replay
OpenReplay is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.
Start enjoying your debugging experience - start using OpenReplay for free.
Link Preview Area
Next, we will add an area where the shortened URL will be displayed.
const [shortenedLink, setShortenedLink] = useState("")
Then, we add the preview area and "copy to clipboard" button after the submit URL
button.
//...
<div className="mt-5">
{shortenedLink}
<button className="border-2 border-blue-500 text-blue-500 font-medium px-5 py-2 ml-4 rounded-md">
Copy URL to Clipboard
</button>
</div>
We will use the' react-copy-to-clipboard' package for the "copy to clipboard" feature. We will add an import for this package at the top level of our code:
import CopyToClipboard from "react-copy-to-clipboard";
We will use it as shown in the code block below:
<CopyToClipboard text={shortenedLink}>
<button className="border-2 border-blue-500 text-blue-500 font-medium px-5 py-2 ml-4 rounded-md">
Copy URL to Clipboard
</button>
</CopyToClipboard>
Here, the text
property references what would be copied when the button is clicked.
ShrtCo.de Setup
To set up Shrco.de, we will create a function using axios
fetch:
import axios from 'axios';
//...
const fetchData = async () => {
try {
const response = await axios(
`https://api.shrtco.de/v2/shorten?url=${userInput}`
);
setShortenedLink(response.data.result.full_short_link);
} catch (e) {
console.log(e);
}
};
Finally, we will add this function to the Submit URL
function:
<button
className=" bg-blue-500 text-white px-8 py-3 ml-4 rounded-md"
onClick={() => {
fetchData();
}}
>
Submit URL
</button>
Now, if we add a link in the input field and click the submit button, we get a shortened link.
Conclusion
In this tutorial, we learned about URL shorteners, their benefits, and how we can easily build one using React.js and Shrtco.de.
The entire source code used in this tutorial can be found here.