"A simple yet powerful URL shortening service that allows users to transform long URLs into short, shareable links. Along with URL shortening, this service provides insightful analytics, giving users the ability to track and monitor their shortened URLs' performance."
by Karan Kumar Gautam
02/03/2025
Welcome to this comprehensive guide on building a URL Shortener API using Node.js, Express, and MongoDB. This project demonstrates how to create a RESTful backend for shortening URLs, redirecting to original URLs, and tracking analytics.
The URL Shortener API is a backend service that allows users to:
This project is ideal for learning how REST APIs work, managing a MongoDB database using Mongoose, and structuring a scalable Node.js backend.
To run this API on your machine, follow these steps:
git clone https://github.com/gautamkaran/URL-Shortener-api.git
cd URL-Shortener-api
npm install
.env
FileAdd your MongoDB URI and port in a new .env
file:
PORT=3000
MONGODB_URI=mongodb+srv://your-username:your-password@cluster0.lxl3fsq.mongodb.net
CORS_ORIGIN=*
npm run dev
The server will start on http://localhost:3000
Endpoint: POST /api/shorten
Request Body:
{
"originalUrl": "https://www.example.com/very/long/url"
}
Response:
{
"shortUrl": "http://localhost:3000/abc123"
}
Accessing the short URL will redirect you to the original URL.
Example:
GET http://localhost:3000/abc123
Endpoint: GET /api/analytics/:shortId
Response:
{
"originalUrl": "https://www.example.com/very/long/url",
"shortUrl": "http://localhost:3000/abc123",
"clicks": 10
}
URL-Shortener-api/
β
βββ public/ # Static files
βββ src/ # Source code
β βββ controllers/ # Route controllers
β βββ models/ # Mongoose models
β βββ routes/ # API routes
β βββ utils/ # Utility functions
βββ .env # Environment variables
βββ package.json # Dependencies
βββ README.md
User sends a POST request to /api/shorten
User accesses the short URL
User sends a GET request to /api/analytics/:shortId
Karan Kumar Gautam
π GitHub | π LinkedIn
MIT β Use it freely in your projects
This URL Shortener API project is a great way to get hands-on experience with REST APIs, MongoDB, and Node.js. Itβs clean, easy to extend, and ready to be used in real applications.
Happy coding!