- Published on
Easy way to build your own Shorten Url WebApp with NextJS
Medium: Easy way to build your own Shorten Url WebApp with NextJS
Are you tired of sharing long and cumbersome URLs?
Do you want to create your own URL shortening service?
While there are a lot of services available that help with this, they are not free. I offer my work on creating an open source Shorten Url in order to save costs (sometimes I just need to pay for the domain name).
In this tutorial, I'll walk you through the process of building your very own URL shortening web application using Next.js, a popular React framework.
Prerequisites
Before you get started, make sure you have the following prerequisites in place:
- Node.js and npm (Node Package Manager) are installed on your computer.
- Basic knowledge of React and JavaScript
- A text editor or integrated development environment (IDE) of your choice
- A code editor such as Visual Studio Code, Sublime Text, or Atom.
- A basic understanding of how URLs work.
Step 1: Create your NextJS project
Run the below command to create your new Next.js project
npx create-next-app shorten-url-app
cd shorten-url-app
Create Routes
Define the necessary routes for your URL shortening service. You'll typically need routes for the homepage, shortening a URL, and redirecting to the original URL.
Create a file named app/index.js
for the homepage, a file named app/shorten/page.js
for the URL shortening, and a file named app/not-found.js
for redirecting.
Step 2: Building the User Interface
Let's now design the web application's user interface for URL shortening. Here's a basic example to get you started, but you can customize it to what you want.
To style your application, you can use CSS frameworks like Tailwind CSS or Bootstrap. For this project, Tailwind is my choice.
On this article, I'll ignore the homepage (depending on your creation). I'll focus on the function page, so let's start with shorten.js
// app/shorten/page.js
import React, { useState } from 'react';
export default function Shorten() {
const [originalURL, setOriginalURL] = useState('');
const [shortenedURL, setShortenedURL] = useState('');
const handleShortenURL = () => {
// URL shortening logic - handle in next step
};
return (
<div>
<h1>URL Shortener</h1>
<input
type="text"
placeholder="Enter your URL"
value={originalURL}
onChange={(e) => setOriginalURL(e.target.value)}
onSubmit={handleShortenURL}
/>
<button onClick={handleShortenURL}>Shorten</button>
{shortenedURL && (
<div className="flex justify-between items-center">
<p>
Shortened URL: <a className="text-md text-sky-500" href={shortenedURL}>{shortenedURL}</a>
</p>
<div className="w-fit rounded-md p-2 my-2 border hover:bg-slate-600">
<BunCopyButton linkValue={shortenedURL} />
</div>
</div>
)}
</div>
);
}
Step 3: Storage
Build your own database storage system.
Example basic structure data:
[
{
"origin_url": "https://example.com/long_link01",
"short_id": "DAVCZ15KJ",
"description": "This is the link of task Monday",
"created_date": "11/11/2023"
},
{
"origin_url": "https://example.com/long_link02",
"short_id": "AFDA435VF",
"description": "This is the link of task on Freshdesk",
"created_date": "11/11/2023"
}
]
Step 4: Implementing URL Shortening Logic
Generate a shortened URL
To implement the URL shortening logic, you can use a popular URL shortening service's API or build your own. Here, we'll provide a basic example of generating a shortened URL by hashing the original URL.
npm install shortid
// app/shorten/page.js
import shortid from 'shortid'
import { sql } from '@vercel/postgres'
// ...
const [originalURL, setOriginalURL] = useState('');
const [shortenedURL, setShortenedURL] = useState('');
const [shortened, setShortened] = useState('');
useEffect(() => {
if (shortened) {
setShortenedURL(`https://your_domain.com/${shortened}`);
// Save the shorten id with origin url
postData();
}
}, [shortened]);
const handleShortenURL = () => {
if (!originalURL || !isValidUrl(originalURL)) {
return false;
}
setShortened(shortid.generate()); // Generate a short ID
}
const isValidUrl = (string) => {
try {
new URL(string);
return true;
} catch (err) {
return false;
}
}
const postData = async () => {} // Handle post request
Handle URL Redirection
In the not-found.js
page, implement the logic to redirect users to the original URL when they access a shortened URL. You can retrieve the original URL from the database using the short code in the URL.
// app/not-found.js
import { useEffect } from 'react';
import { usePathname, redirect } from 'next/navigation';
const Redirect = () => {
const pathname = usePathname()
useEffect(() => {
links.forEach(item => {
if(item.short_id == pathname.replace('/','')) {
redirect(item.origin_url)
}
});
})
return (
<div className="text-white">The link could not be found.</div>
)
};
export default Redirect;
Replace https://your_domain.com/
with your own domain when deploying your app.
Step 4: Deploy Your Next.js Application
You can deploy your Next.js application on platforms like Vercel, Netlify, or Heroku. Follow their respective deployment instructions to make your URL shortening web app accessible online.
Conclusion
If you like this post and my open source, don't forget to give me support (clapp, share).
Author: bunhere.com
I am always looking for feedback on my writing, so please let me know what you think. ❤️