πŸ‹
Menu
Best Practice Beginner 1 min read 299 words

Slug and URL-Safe String Generation Best Practices

Slugs transform human-readable titles into URL-safe strings. Proper slug generation handles unicode, special characters, and collisions while preserving readability.

Key Takeaways

  • A slug is a URL-safe version of a string, typically derived from a title or name.
  • Convert accented characters to ASCII equivalents: ΓΌ β†’ u, Γ± β†’ n, ΓΈ β†’ o.
  • Two different titles can produce the same slug.
  • Keep slugs under 80 characters for readability and under 255 characters for filesystem compatibility.
  • Generate slugs on creation, not on every request

What Is a Slug

A slug is a URL-safe version of a string, typically derived from a title or name. 'How to Merge PDF Files' becomes how-to-merge-pdf-files. Slugs appear in URLs, filenames, and database identifiers.

Generation Rules

Step Input Output
1. Lowercase 'Hello World' 'hello world'
2. Transliterate 'cafΓ© rΓ©sumΓ©' 'cafe resume'
3. Remove special chars 'hello! world?' 'hello world'
4. Replace spaces 'hello world' 'hello-world'
5. Collapse hyphens 'hello--world' 'hello-world'
6. Trim hyphens '-hello-world-' 'hello-world'

Unicode Handling

Transliteration

Convert accented characters to ASCII equivalents: ΓΌ β†’ u, Γ± β†’ n, ΓΈ β†’ o. Libraries like python-slugify and slugify (npm) handle this automatically with locale-aware rules.

CJK Characters

Chinese, Japanese, and Korean characters do not transliterate to Latin. Options:

  • Keep original characters in the URL (modern browsers display them correctly)
  • Romanize: 東京 β†’ tokyo (requires language-specific romanization libraries)
  • Use a numeric or UUID identifier instead

Collision Handling

Two different titles can produce the same slug. Handle collisions by appending a counter:

  • my-article
  • my-article-2
  • my-article-3

Check for existing slugs in the database before saving. Use a unique constraint as a safety net.

Length Considerations

Keep slugs under 80 characters for readability and under 255 characters for filesystem compatibility. Truncate at word boundaries to avoid cutting words in half.

Implementation Tips

  • Generate slugs on creation, not on every request
  • Make slugs immutable after creation (changing them breaks URLs)
  • If a title changes, keep the old slug and add a redirect to the new URL
  • Store slugs in a dedicated indexed column for fast lookups