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 { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
typescript
import { Component, Input } from '@angular/core'; interface Order { id: string;
How Angular ICU plurals localize an order summary
i18n
pluralization
standalone-component
Intermediate
8 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable, catchError, concatMap, finalize } from 'rxjs'; import { DataSource, QueryRunner } from 'typeorm';
Wrapping requests in a transaction with NestJS
interceptors
transactions
rxjs
Advanced
7 steps
python
from functools import wraps import asyncio from fastapi import APIRouter, FastAPI, Request
Per-route request timeouts in FastAPI
decorators
async
timeouts
Intermediate
6 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
Intermediate
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.