typescript
40 lines · 6 steps
Generating unique URL slugs from titles
Turn a title into a clean, collision-free slug by normalizing it and probing a repository for an available variant.
Explained by
highlit
1import slugify from "slugify";
2
3interface SlugRepository {
4 exists(slug: string): Promise<boolean>;
5}
6
7const RESERVED = new Set(["new", "edit", "admin", "api"]);
8
9export function baseSlug(title: string): string {
10 const slug = slugify(title, {
11 lower: true,
12 strict: true,
13 locale: "en",
14 trim: true,
15 });
16
17 return slug || "untitled";
18}
19
20export async function uniqueSlug(
21 title: string,
22 repo: SlugRepository,
23): Promise<string> {
24 let candidate = baseSlug(title);
25
26 if (RESERVED.has(candidate)) {
27 candidate = `${candidate}-1`;
28 }
29
30 if (!(await repo.exists(candidate))) {
31 return candidate;
32 }
33
34 for (let suffix = 2; ; suffix++) {
35 const next = `${candidate}-${suffix}`;
36 if (!(await repo.exists(next))) {
37 return next;
38 }
39 }
40}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Normalizing user input first gives you a predictable starting point before enforcing uniqueness.
- 2Guarding against reserved words and empty results prevents slugs that would break routing.
- 3An open-ended counter loop reliably finds the first free variant no matter how many collisions exist.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/generating-unique-url-slugs-from-titles-explained-typescript-8388/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.