post

Building a URL Shortener with Node.js, MongoDB, and Vercel in 30 Minutes

Today, I’ll show you how to build a practical URL shortener with click analytics using modern web technologies. This project is perfect for developers looking to create something useful while learning about Node.js, MongoDB, and serverless deployment.

Why Build a URL Shortener?

Before diving in, you might wonder: why build yet another URL shortener? Here’s why this project is valuable:

  1. You own your data and links
  2. You can track click analytics
  3. You’ll learn modern web development practices
  4. It’s a perfect serverless deployment example
  5. You can extend it with custom features

The Tech Stack

We’re using a modern, lightweight stack:

  • Node.js & Express: For our backend API
  • MongoDB Atlas: For data persistence
  • Vercel: For serverless deployment
  • Tailwind CSS: For a clean, responsive UI

Key Features

Our URL shortener includes:

  • URL shortening with nanoid for unique IDs
  • Click tracking
  • Real-time statistics
  • Mobile-friendly interface
  • Clean, RESTful API

The Implementation

Here’s the interesting part – how we built it. Let’s break down the key components:

1. The Data Model

We kept the MongoDB schema simple but effective:

const urlSchema = new mongoose.Schema({
  originalUrl: String,
  shortUrl: String,
  clicks: { type: Number, default: 0 },
  createdAt: { type: Date, default: Date.now }
});

2. URL Generation

Instead of using complex algorithms, we opted for nanoid, which provides:

  • Short, unique IDs
  • No collisions (practically)
  • URL-safe characters

3. The API

We implemented three main endpoints:

// Create short URL
app.post('/api/shorten', async (req, res) => {
  const shortUrl = nanoid(8);
  const urlDoc = await Url.create({
    originalUrl: url,
    shortUrl
  });
  res.json(urlDoc);
});

// Get URL stats
app.get('/api/stats/:shortUrl', async (req, res) => {
  const urlDoc = await Url.findOne({ shortUrl: req.params.shortUrl });
  res.json(urlDoc);
});

// Handle redirects
app.get('/:shortUrl', async (req, res) => {
  const urlDoc = await Url.findOne({ shortUrl: req.params.shortUrl });
  urlDoc.clicks++;
  await urlDoc.save();
  res.redirect(urlDoc.originalUrl);
});

4. Serverless Deployment

Vercel made deployment incredibly simple. The key was properly configuring our Express app for serverless:

// Handle both API and static files
app.use(express.static('public'));
export default app;

Challenges and Solutions

During development, we encountered and solved several interesting challenges:

  1. MongoDB Connection: Initially, we had issues with MongoDB connections in the serverless environment. The solution was proper connection handling and error management.
  2. Route Handling: Vercel’s routing needed special attention to handle both API endpoints and the frontend correctly.
  3. Statistics Updates: Ensuring atomic updates for click counting required careful consideration of MongoDB operations.

Future Improvements

The current implementation is solid but could be enhanced with:

  1. Custom short URLs
  2. User authentication
  3. QR code generation
  4. Advanced analytics
  5. API rate limiting

Try It Yourself

The project is open source and available on GitHub: URL Shortener Project

You can see it in action here: Live Demo

Conclusion

Building a URL shortener was both fun and educational. It demonstrates how modern web technologies can come together to create something useful in a short time. The serverless deployment aspect makes it particularly interesting, as it shows how to build scalable applications without managing servers.

What features would you add to this URL shortener? Let me know in the comments below!


P.S. All the code is available on GitHub, and I encourage you to fork it, enhance it, and make it your own. If you build something cool with it, I’d love to hear about it!

Co-written with Claude 3.5 Sonnet

This post and the accompanying URL shortener project were developed in collaboration with Claude 3.5 Sonnet, an AI assistant from Anthropic. Claude helped architect the solution, write the code, and structure this blog post. While I implemented and tested the solution, made key technical decisions, and deployed the final product, I believe in being transparent about AI collaboration in both development and content creation.

The complete source code is available on GitHub.

post

The Miracle Morning

Here is a summary of the Life S.A.V.E.R.S technique, to be done immediately after awakening and 30 minutes before your normal waking time: 

  • Silence – prayer/meditation
  • Affirmations – describe the highest vision for yourself
  • Visualization – visualize what success looks like and the actions to get there
  • Exercise – 10 minutes to get the blood flowing. Try a push-up/sit-up/air-squat/pull-up circuit
  • Reading – self-help/motivational books
  • Scribing – check out the 5 minute journal

From the “The Miracle Morning” by Hal Elrod

Listen to Hal’s explanation on the Smart Passive Income podcast.

post

Best Productivity Hack of 2014: Touch ID

Touch_ID_iPhone_5s

Touch ID iPhone 5s” by Pixeden.com – http://www.pixeden.com/psd-mock-up-templates/iphone-5s-psd-vector-mockup. Licensed under CC BY 3.0 via Wikimedia Commons.

I had given up on fingerprint readers in the 90s when I first used a Dell laptop with a built-in fingerprint reader. At the time, you had to swipe your finger downward across the sensor and most times it would take several swipes to work. Probably because I did not RTFM, I could only use the fingerprint reader to unlock the laptop, though my goal was to login to websites with a swipe of my finger. One could dream …

[Read more…]

post

Import an OmniFocus Completed Task Report into Evernote via AppleScript

This OmniFocus AppleScript (based on this code) allows you to specify a time frame (e.g. Today, Yesterday, Last Week, etc.) of completed OmniFocus tasks to export into Evernote.

This is what the report looks like:

OmniFocus Completed Task Report Imported to Evernote

Here are some ideas to expand this script:

* organize the results by Folder
* make the note title start with YYYY-MM-DD
* send this report via email

post

Food ID

I *really* want this idea to become reality. Check it out and let me know what you think.

post

How can I be productive on the Internet?

This is the question I answered over on medium.

To me, opening up a web browser is like walking into a large library. The potential is overwhelming and a strategy is necessary to maximize the amazing opportunity before you. Check out my strategy and let me know what you think.

post

Talk: A Personal Life API

Yesterday, I had the pleasure of presenting a 40 minute tutorial on how to create your own Personal Life API at API World in San Francisco.

The talk consists of the slides, documentation (on APIary) and code (on GitHub, written in Python/Flask).

Big thanks to API World for offering a platform to express these ideas and SendGrid for sponsoring my attendance.

post

Terror and Fiction

Last night, I woke up in a state of terror several times, with no real reason I can remember. Perhaps I should not have watched The Leftovers right before going to sleep.

When I awoke for the day ahead, I was determined to carpe diem, even though I was feeling weary due to lack of sleep. And in fact, today ended up being among my most productive days.

[Read more…]

post

Chaos Proof Your Habits and Routines

When I became a Developer Evangelist at SendGrid (one of the best jobs on the planet), I learned just how difficult keeping habits and routines while traveling really is. While I still struggle with this challenge, there are a few tips I’d like to pass on to help you keep moving towards your goals, posthaste.

Enjoy and pass along to your chaotic good friends.

[Read more…]

post

Have you created your own Personal API?

If so, tell me about it 🙂

If not, head on over and read my latest blog post, Quantify Thyself: Creating a Personal Life API, that describes how to create one.