URL Shortener API
A URL shortener is a common backend coding project.
It tests routing, validation, database design, redirects, and edge cases.
Core routes
POST /urls
GET /:slug
GET /urls/:id/stats
Create short URL
Input:
{
"longUrl": "https://example.com/some/long/path"
}
Response:
{
"slug": "aB12xY",
"shortUrl": "https://short.ly/aB12xY"
}
Data model
const urlSchema = new Schema(
{
longUrl: { type: String, required: true },
slug: { type: String, required: true, unique: true },
clickCount: { type: Number, default: 0 },
createdBy: { type: Schema.Types.ObjectId, ref: 'User' },
expiresAt: Date,
},
{ timestamps: true },
)
Useful indexes:
urlSchema.index({ slug: 1 }, { unique: true })
urlSchema.index({ createdBy: 1, createdAt: -1 })
Slug generation
Simple version:
function createSlug(length = 6) {
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
let slug = ''
for (let i = 0; i < length; i += 1) {
slug += chars[Math.floor(Math.random() * chars.length)]
}
return slug
}
In real code, handle collision by checking whether the slug already exists.
Redirect flow
When user visits:
GET /aB12xY
Server:
- finds slug in database,
- increments click count,
- redirects to long URL.
res.redirect(url.longUrl)
Edge cases
Handle:
- invalid URL,
- duplicate slug,
- missing slug,
- expired links,
- analytics count,
- malicious URLs if required.
Test cases
- creates short URL for valid long URL,
- rejects invalid URL,
- redirects existing slug,
- returns
404for missing slug, - increments click count after redirect,
- handles slug collision.
Interview angle
Explain slug generation, uniqueness, redirect route, validation, database schema, and analytics. Mention that high-scale URL shorteners need caching and collision handling.