A modern, production-grade URL shortening service built with Node.js, Express.js, and MongoDB. In addition to standard short link redirection and analytics, every link is automatically inspected via web scraping (axios) and summarized using Google Gemini 1.5 Flash to generate human-readable titles and one-sentence summaries.
π Deep Technical Specification: For an exhaustive, line-by-line backend architectural breakdown, schemas, and sequence diagrams, refer to BACKEND_DOCUMENTATION.md.
- Features
- Tech Stack
- System Architecture
- Directory Layout
- Quick Start & Installation
- Environment Configuration
- API & Route Reference
- AI Summarization Pipeline
- Testing
- AI Agent & Contributor Operational Guide
- License & Author
- Automated AI Link Summarization: Uses Google Gemini 1.5 Flash to automatically generate a catchy title (max 60 chars) and concise 1-sentence summary (max 150 chars) for every shortened URL.
- Webpage Scraping: Fast metadata crawler using
axioswith desktop browser user-agents and timeout guards. - Stateful Redirection & Click Analytics: Captures millisecond-precision click history timestamps and counts upon each redirection.
- Stateless JWT Authentication: Secure user session tracking stored in HttpOnly cookies with 24-hour expiration.
- Cryptographic Security: Automatic salted password hashing via
bcryptjsusing Mongoose pre-save hooks. - Ownership Protection: URL analytics and deletion are strictly authorized per-user.
- Interactive UI: Server-side rendered EJS templates with modal click analytics, live search filtering, and one-click copy.
| Domain | Technology | Purpose |
|---|---|---|
| Runtime | Node.js | Server runtime |
| Framework | Express.js 4.x | HTTP routing and middleware pipeline |
| Database | MongoDB & Mongoose 8.x | Document database and object modeling |
| AI Model | Google Gemini (gemini-1.5-flash) |
Structured JSON title and summary generation |
| Web Scraping | Axios | HTML fetching with timeout and user-agent emulation |
| Auth & Security | JWT (jsonwebtoken) & bcryptjs |
Stateless session tokens and password hashing |
| ID Generator | nanoid (v3) |
Unique 8-character URL slugs |
| View Engine | EJS | Server-side rendered responsive user interface |
| Testing | Mocha, Chai, Supertest | Unit and integration testing |
+-------------------------------------------------+
| Browser Client |
+-------------------------------------------------+
|
HTTP Requests / Cookies
v
+---------------------------------------------------------------------------------+
| Express Application (index.js) |
| |
| [Global Middlewares] |
| - express.json() & express.urlencoded() |
| - cookieParser() |
| - checkAuth (Populates req.user from JWT cookie) |
| |
| [Routes & Middlewares] |
| - /user ββββββββββββββ> user.js (Signup / Login / Logout) |
| - /url ββ[restrict]ββ> url.js (Create, Analytics, Delete) |
| - / ββββββββββββββ> staticRouter.js (Landing / Dashboard views) |
| - /:shortId βββββββββββ> redirect.js (Atomic click track & 302 redirect) |
+---------------------------------------------------------------------------------+
| | |
v v v
+-----------------------+ +--------------------+ +--------------------+
| MongoDB (Mongoose) | | Axios Web Scraper | | Google Gemini API |
| - users collection | | (HTML Title Match) | | (1.5 Flash Model) |
| - urls collection | +--------------------+ +--------------------+
+-----------------------+
.
βββ config/
β βββ db.js # MongoDB connection handler (mongoose.connect)
βββ controllers/
β βββ redirect.js # Handles /:shortId redirection & $push click history
β βββ url.js # Short URL creation (AI-backed), analytics, deletion
β βββ user.js # User registration, login verification, logout
βββ middlewares/
β βββ auth.js # Auth guards (checkAuth, restrictToLoggedinUserOnly)
βββ models/
β βββ url.js # URL Schema (shortId, redirectUrl, visitHistory, etc.)
β βββ user.js # User Schema with bcrypt pre-save hashing
βββ routes/
β βββ staticRouter.js # View rendering routes (GET /, GET /signup, GET /login)
β βββ url.js # Authenticated URL actions (/url)
β βββ user.js # User auth endpoints (/user)
βββ services/
β βββ auth.js # JWT signing (setUser) and token parsing (getUser)
β βββ urlAnalyzer.js # Axios crawler + Gemini 1.5 Flash JSON analyzer
βββ test/
β βββ user.test.js # User API integration tests (Mocha/Chai/Supertest)
βββ views/
β βββ home.ejs # Logged-in user dashboard and management UI
β βββ landing.ejs # Public showcase page for unauthenticated visitors
β βββ login.ejs # Login form
β βββ signup.ejs # User registration form
βββ .env.example # Sample environment template
βββ BACKEND_DOCUMENTATION.md # Detailed technical specification
βββ index.js # Main server entrypoint
βββ package.json # Project dependencies and npm scripts
βββ README.md # Primary overview and guide
- Node.js (v18.x or higher recommended)
- MongoDB running locally on port
27017or a MongoDB Atlas connection string - Google Gemini API Key (Free from Google AI Studio)
-
Clone the Repository
git clone https://github.com/Devcodes06/URL-Shortener.git cd URL-Shortener -
Install Dependencies
npm install
-
Configure Environment Variables Create a
.envfile in the root directory (copy from.env.example):PORT=8001 MONGODB_URI=mongodb://localhost:27017/short-url JWT_SECRET=your_super_secret_jwt_key GEMINI_API_KEY=your_google_gemini_api_key
-
Run the Application
# Development mode with Nodemon auto-reload: npm run dev # Production mode: npm start
-
Access the Web Interface Open your browser and navigate to:
http://localhost:8001
| Variable | Required | Default Value | Description |
|---|---|---|---|
PORT |
Optional | 8001 |
HTTP listening port for Express server |
MONGODB_URI |
Optional | mongodb://localhost:27017/short-url |
MongoDB connection URI |
JWT_SECRET |
Optional | your-very-secure-secret |
Cryptographic secret for signing JSON Web Tokens |
GEMINI_API_KEY |
Optional* | None | Gemini API Key for AI titles & summaries (*gracefully falls back if missing) |
| Method | Endpoint | Auth | Request Body | Description & Response |
|---|---|---|---|---|
POST |
/user |
No | { name, email, password } |
Registers user, hashes password, sets uid cookie, redirects (302) to /. |
POST |
/user/login |
No | { email, password } |
Validates credentials, sets uid cookie, redirects (302) to /. |
POST |
/user/logout |
No | None | Clears uid cookie and redirects (302) to /. |
β οΈ Note on Signup Route: The registration endpoint isPOST /user, not/user/signup.
All /url endpoints require an active authenticated user session (uid cookie).
| Method | Endpoint | Auth | Parameters / Body | Description & Response |
|---|---|---|---|---|
POST |
/url |
Yes | Body: { url: "https://example.com" } |
Scrapes target, runs Gemini AI, creates short URL, redirects (302) to /?id=<shortId>. |
GET |
/url/analytics/:shortId |
Yes | Param: shortId |
Returns { totalClicks, analytics: [{ timestamp }] } for user's own URL. Returns 403 if unauthorized. |
DELETE |
/url/:shortId |
Yes | Param: shortId |
Deletes the short URL document. Returns { message: "URL deleted successfully" }. Returns 403 if unauthorized. |
| Method | Endpoint | Auth | Description |
|---|---|---|---|
GET |
/:shortId |
No | Atomically pushes { timestamp: Date.now() } to visitHistory and redirects (302) to original target URL. |
GET |
/ |
Optional | If logged in: renders home.ejs with user's links. If logged out: renders landing.ejs. |
GET |
/signup |
No | Renders user signup form (signup.ejs). |
GET |
/login |
No | Renders user login form (login.ejs). |
When a user submits a URL via POST /url:
services/urlAnalyzer.jsissues an Axios GET request with a 5-second timeout and realistic desktop User-Agent.- It captures the
<title>tag via regex and takes the first 10,000 characters of the HTML document. - It passes the snippet to Google Gemini 1.5 Flash with
responseMimeType: "application/json". - Gemini returns a structured JSON payload containing a human title (
max 60 chars) and summary (max 150 chars). - Fallback Guarantee: If scraping or Gemini fails (network timeout, invalid key, rate limit), the service catches the error and assigns fallback values (
"Unknown Title"and"No summary available."). The URL shortening process never fails due to AI downtime.
The repository includes an automated integration test suite written with Mocha, Chai, and Supertest:
# Run all tests
npm test- User signup with successful creation, redirect, and cookie issuance.
- Form validation (returns 400 when name/email/password are missing).
- User login with credential validation and cookie setting.
- Bad credential rejection (returns 400 for wrong password).
- User logout and cookie clearance verification.
If you are an automated AI agent or human contributor working on this repository, strictly observe these rules:
- Module System: This project is CommonJS (
"type": "commonjs"). Useconst x = require('x')andmodule.exports = .... Do not use ES6import/export. - Wildcard Route Ordering: In
index.js,app.get('/:shortId', handleRedirect)is a catch-all route for short links. Any new static or API route must be declared above this line, or it will be intercepted as ashortId. - Password Updates: The user password hashing hook in
models/user.jstriggers only on documentsave(). Updating passwords withUser.findOneAndUpdatebypassesbcryptand leaves passwords unhashed. - Foreign Key Integrity: In
models/url.js,createdByis configured withref: "users". If calling.populate("createdBy"), ensure the model name matches your schema. - Form Action Paths:
- Signup form posts to
/user. - Login form posts to
/user/login. - Logout form posts to
/user/logout. - URL creation form posts to
/url.
- Signup form posts to
- Graceful Failures: Keep external AI/scraping service failures isolated within
try/catchblocks so user actions (like shortening a URL) remain dependable.
This project is licensed under the MIT License.
Devcodes06
- GitHub: @Devcodes06