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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Normalizing user input first gives you a predictable starting point before enforcing uniqueness.
  2. 2Guarding against reserved words and empty results prevents slugs that would break routing.
  3. 3An open-ended counter loop reliably finds the first free variant no matter how many collisions exist.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Generating unique URL slugs from titles — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code