A basic URL shortener built with Express.js, MongoDB (Mongoose), and a vanilla HTML/CSS/JS frontend.
- POST endpoint to shorten a long URL
- Stores the mapping (original URL <-> short code) in MongoDB
- GET route that redirects a short code to the original URL
- Simple frontend to submit URLs and view recent links + click counts
url-shortener/
backend/
controllers/urlcontroller.js
models/url.js
routes/urlroutes.js
server.js
package.json
.env
frontend/
index.html
style.css
script.js
-
Install dependencies
cd backend npm install -
Configure environment variables The
.envfile already has sensible local defaults:PORT=5000 MONGO_URI=mongodb://127.0.0.1:27017/urlshortener BASE_URL=http://localhost:5000If you're using MongoDB Compass / local mongod, this default
MONGO_URIwill work as-is as long as your local MongoDB server is running on the default port (27017). -
Start MongoDB (if not already running)
mongod
Or just open MongoDB Compass and connect to
mongodb://127.0.0.1:27017— that's the same database the backend will write to, so you can watch theurlshortenerdatabase /urlscollection appear and update live as you shorten links. -
Run the server
npm start
or for auto-restart on changes during development:
npm run dev
-
Open the app Visit http://localhost:5000 in your browser. The Express server also serves the frontend, so no separate frontend server is needed.
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/shorten |
Body: { "originalUrl": "..." } → returns short URL |
| GET | /:shortCode |
Redirects to the original URL |
| GET | /api/urls |
Returns list of all shortened URLs |
- Short codes are 6 characters, generated with
nanoid. - If you shorten the same URL twice, the existing short code is returned instead of creating a duplicate.