Custom Aliases and Vanity URLs
You'll learn how to let users pick memorable short codes while preventing conflicts and abuse.
The Core Idea
Up until now, your URL shortener has assigned short codes automatically (via hash, counter, or random generation). But premium users or brands often want custom aliases—like yoursite.com/nike instead of yoursite.com/a3X9k. This requires validating user input, handling collisions when someone else already claimed that alias, and blocking reserved keywords.
Plain-English Explanation
Think of custom aliases like personalized license plates. The DMV (your system) normally assigns random plates, but you can request "ILOVENY" if it's available, not offensive, and not a reserved code like "POLICE." Your system must:
- Check availability: Query the database to see if
nikeis already taken. - Validate input: Enforce length limits, character restrictions (alphanumeric only? case-sensitive?), and profanity filters.
- Reserve keywords: Block system routes like
admin,api,stats, or future features. - Handle collisions gracefully: If taken, suggest alternatives (
nike2,nike-official) or reject the request.
When a custom alias request comes in, look it up before inserting. Use a unique constraint on the short_code column to prevent race conditions where two users claim the same alias simultaneously.
Integration with Existing Flow
Custom aliases skip your auto-generation logic. The user provides the short code directly. You still store it in the same urls table with the same schema—just the source of the short code differs.
Key Takeaway:
Custom aliases require availability checks, input validation, reserved-word filtering, and database-level uniqueness constraints to prevent collisions and abuse.