A minimal, easy-to-read URL shortener built with Node.js, Express and MongoDB. It provides API endpoints to create short URLs, redirect to the original URL, and fetch basic analytics for each short link.
- Create a short URL for any target link (POST /url)
- Redirect shortId to the original URL and record visits (GET /:shortId)
- View analytics for a short URL (GET /url/analytics/:shortId)
- Simple MongoDB-backed persistence using Mongoose
- Node.js
- Express
- MongoDB (Mongoose)
- shortid (for generating short IDs)
- Node.js (v16+ recommended)
- MongoDB (local or remote)
- Clone the repository
git clone https://github.com/AK-RoXX/URL-Shortener-using-NodeJS-and-Mongo.git
cd url-shortener- Install dependencies
npm install- Start the server
npm startBy default the server listens on port 8001 and connects to a local MongoDB instance at mongodb://localhost:27017/url-shortener (see index.js). You can modify the connection URL or port directly in index.js, or extend the project to read configuration from environment variables.
Base path: http://localhost:8001
- Endpoint:
POST /url - Request body (JSON):
{ "url": "https://example.com/some/long/path" }- Response:
{ "id": "shortId" }Example using curl:
curl -X POST -H "Content-Type: application/json" -d '{"url":"https://example.com"}' http://localhost:8001/url- Endpoint:
GET /url/analytics/:shortId - Response:
{
"totalClicks": 5,
"analytics": [{"timestamp": 1650000000000}, ...]
}Example:
curl http://localhost:8001/url/analytics/abcd12- Endpoint:
GET /:shortId - Behavior: redirects to the original URL and adds a visit entry with a timestamp to the
visitHistoryarray.
Example:
# In the browser visit http://localhost:8001/abcd12
curl -v http://localhost:8001/abcd12The URL model (in models/url.js) has the following structure:
shortId(String, required, unique)redirectUrl(String, required)visitHistory(Array of objects{ timestamp: Number })createdAt,updatedAt(timestamps generated by Mongoose)