A REST API to shorten long URLs, track clicks, and redirect users — built with Express.js and MongoDB.
- Node.js + Express.js — Server & routing
- MongoDB + Mongoose — Database
- nanoid — Short code generation
- dotenv — Environment variables
git clone https://github.com/your-username/url-shortener.git
cd url-shortenernpm installPORT=3000
MONGO_URI=mongodb://localhost:27017/urlshortener
BASE_URL=http://localhost:3000npm run dev| Method | Endpoint | Description |
|---|---|---|
POST |
/api/url/shorten |
Shorten a long URL |
GET |
/:shortCode |
Redirect to original URL |
GET |
/api/url/all |
Get all shortened URLs |
GET |
/api/url/stats/:shortCode |
Get click stats |
DELETE |
/api/url/:shortCode |
Delete a short URL |
POST /api/url/shorten
Content-Type: application/json
{
"originalUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
}Response:
{
"message": "URL shortened successfully",
"shortUrl": "http://localhost:3000/abc123",
"data": {
"originalUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"shortCode": "abc123",
"clicks": 0
}
}GET /api/url/stats/abc123Response:
{
"originalUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"shortUrl": "http://localhost:3000/abc123",
"clicks": 5,
"createdAt": "2024-01-01T00:00:00.000Z"
}url-shortener/
├── src/
│ ├── config/db.js
│ ├── controllers/urlController.js
│ ├── models/urlModel.js
│ ├── routes/urlRoutes.js
│ ├── middleware/errorHandler.js
│ └── index.js
├── .env
├── .gitignore
├── README.md
└── package.json