Build a free link shortener with Next.js and Vercel Postgres
Create a link shortener with Next.js and Vercel Postgres. Learn dynamic routing, database connection, and domain customization.
Monday, August 21, 2023
TL;DR
Check the demo here
Check the source code here
Introduction
Link shorteners have become a go-to solution for sharing lengthy URLs, especially on platforms where character count matters. They're simple, efficient, and incredibly handy. In this blog post, we're diving into the creation of a simple and free link shortener using Next.js and Vercel Postgres.
Vercel Postgres is my new go-to solution for free Postgresql database hosting. It offers a generous free tier for small projects and is easy to set up.
Since Vercel hosting is also free, we can build and deploy our app without any cost.
Our demo will showcase the following features:
- Automatic redirection to the target link when a slug is accessed
- Track the number of visits for each link
- Display the stats of the links from the database
Prerequisites
In addition to the requirements for creating a typical NextJS app, you'll also need a Vercel account. If you don't have one, you can register here.
Installation
The easiest way to follow this guide is to degit a Nextjs boilerplate.
bash1
I will be using TailwindCSS and TypeScript due to personal preference, but you can use plain CSS and JavaScript if you want.
Install dependencies
bash1
Remove unused files
Delete everything under the app
and components
folders
bash1
Setting Up NextJS - Part 1
Making a Placeholder Route Resolver
In a link shortener app, a 'slug' is a unique name for each shortened link. This slug helps the app send users to the right URL when they click on the shortened link.
We'll use NextJS's dynamic routes to make a route for our unique slug. For now, we'll keep it basic and just make any slug redirect to one page.
app/[slug]/route.ts123
After running the app with npm run dev
, we can go to http://localhost:3000/xyz
and it should redirect to Google's home page.
Initial Deployment
Deploying our app first will simplify the process. Vercel provides an easy way to connect an existing project to a database, which we'll create later.
Installing the Vercel CLI
Start by installing the Vercel CLI:
bash1
Login to Vercel
Next, log into your Vercel account:
bash1
Deploying the App
Finally, deploy the app:
bash1
For more information on deploying with Vercel CLI, check out this guide
Setting Up the Database
Creating the Vercel Postgres Database
First, log into your Vercel account, navigate to the dashboard, and select the Storage
tab. Then, click on the Create Database
button.
A dialog box will appear. Choose the PostgreSQL
option and click Continue
.
You'll see another popup. If you agree with the terms, click Accept
. Then, set your database name and click Create
.
Creating the Links Table
Currently, Vercel PostgreSQL doesn't offer a built-in interface for various operations. So, we'll use the query runner for now.
sql123456
The query above will create a table with the following columns:
- id: A unique identifier for each link
- alias: The slug that will be used to create the shortened link
- target: The destination URL
- visit_count: The number of times the link has been visited
We can add other tracking information like the source host, the user agent, etc. but for this demo, we'll keep it simple.
Adding a New Link Entry
To test our setup, let's add a new link entry using the following query:
sql12
We can browse the table using the Browse
tab.
Setting Up NextJS - Part 2
Installing the Vercel Postgres Package
Start by installing the Vercel Postgres package:
bash1
Connecting the Project
Follow these steps to connect your Vercel project to the database:
- Connect your Vercel project to the database
- Pull the latest environment variables
Vercel simplifies the process of loading environment variables from the database. You can do this by running the following command:
bash1
- Install the Vercel Postgres package
bash1
- Update the route handler
Next, replace the content of app/[slug]/route.ts with the provided code.
app/[slug]/route.ts1234567891011121314151617181920212223242526272829
Once the app is running, visiting http://localhost:3000/nggyu
should redirect us to the target link.
We're seeing a 404 page because we haven't created a home/index page yet.
Setting Up a Default Page (Optional)
In cases where no slug is provided, the app will attempt to resolve the root route, which isn't defined. However, you're free to customize this behavior as needed. For this demo, I'll set up the root route to display basic statistics for all the links in the database.
Create the layout component
app/layout.tsx1234567891011121314
Create the home page
This page will display the stats of all the links in the database in a table format.
app/page.tsx123456789101112131415161718192021222324252627282930313233343536373839404142
Upon running the app, each visit to the alias should increase the visit count.
Customizing the Domain
Without customizing our domain, we might end up with a longer link, which defeats the purpose of a link shortener. For instance, the default domain provided by Vercel for this demo is https://demo-nextjs-link-shortener.vercel.app/nggyu.
With Vercel
Vercel allows us to modify our domain. Here's the process:
- Navigate to the
Settings
tab - Select
Domains
- Choose the domain you wish to modify
- Hit
Edit
- Enter the subdomain you wish to use and click
Save
With a DNS Provider
The previous option is great, but there is Vercel branding in the domain. If you want to remove it, you can use your own domain.
Remember, this isn't free as you'll need to purchase a domain. I got mine from NameCheap
To set it up:
- If you're using NameCheap, go to the
Advanced DNS
tab on the Dashboard.
If you are using a different provider, you can google how to add a
CNAME Record
in<your provider>
.
- Create a new record
- To direct all traffic to Vercel, I added an
A Record
with Host@
and Value76.76.21.21
- Next, I added a
CNAME Record
with Hostlinks
and Valuecname.vercel-dns.com
To add the custom domain in Vercel:
- Go to the
Settings
tab - Click on
Domains
- Enter the domain you wish to add in the text field
- Click on
Add
It may ask if you want to redirect your existing traffic to the new domain which I recommend doing.
Once set, you should have a fully functional link shortener app that's ready to be shared with the world.
Conclusion
In conclusion, we've explored how to build a link shortener using Next.js and Vercel Postgres, set up dynamic routes, connect to a database, and track link visits. We also delved into customizing the domain with Vercel and a DNS provider, demonstrating the flexibility of our setup. Remember, while this demo is basic, it opens the door to endless possibilities for expansion. Happy coding!