A simple and fast URL shortener REST API built with Node.js, Express, and MongoDB.
- Shorten long URLs into compact 6-character codes
- Redirect and retrieve original URLs
- Update or delete shortened URLs
- Track access statistics per link
- Runtime: Node.js
- Framework: Express 5
- Database: MongoDB (via Mongoose)
- ID Generation: nanoid
git clone https://github.com/your-username/url-shortener.git
cd url-shortener
npm installCreate a .env file in the root directory:
MONGO_URI=your_mongodb_connection_string
PORT=3000# Development (auto-restart with nodemon)
npm run dev
# Production
npm startBase URL: http://localhost:3000/api/url
| Method | Endpoint | Description |
|---|---|---|
POST |
/ |
Create a shortened URL |
GET |
/:shortUrl |
Get the original URL |
PUT |
/:shortUrl |
Update the original URL |
DELETE |
/:shortUrl |
Delete a shortened URL |
GET |
/:shortUrl/stats |
Get access stats for a URL |
curl -X POST http://localhost:3000/api/url \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com/very-long-url"}'Response 201 Created
{
"url": {
"_id": "...",
"url": "https://example.com/very-long-url",
"shortUrl": "a1B2c3",
"accessCount": 0,
"createdAt": "...",
"updatedAt": "..."
}
}curl http://localhost:3000/api/url/a1B2c3curl -X PUT http://localhost:3000/api/url/a1B2c3 \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com/new-url"}'curl -X DELETE http://localhost:3000/api/url/a1B2c3curl http://localhost:3000/api/url/a1B2c3/statsurl-shortener/
├── src/
│ ├── app.js # Express app & MongoDB connection
│ ├── controllers/
│ │ └── short.js # Route handlers (CRUD + stats)
│ ├── models/
│ │ └── Url.js # Mongoose schema
│ └── routes/
│ └── shorten.js # API route definitions
├── .env
├── .gitignore
└── package.json
ISC