One-Click English URL Slugs with Front Matter CMS + Gemini AI

·5 min

Use AI to automatically convert Chinese titles into clean English URL slugs

Why do this?

I usually write in Chinese, but when publishing articles on websites, I find that having URLs in English looks cleaner. In the past, I used tools like ChatGPT to help translate titles, but I still had to copy the title, enter commands, then paste and adjust the format. This back-and-forth felt like an extra step that interrupted my writing flow.

Recently, I found a way to use Front Matter CMS together with Google Gemini AI so that in VS Code I can just press a button and automatically generate the English URL slug.

How it works: In VS Code, just click a button, and it will automatically convert a Chinese title like “探索第二大腦:提升生產力的四個步驟” into a clean, SEO-friendly English slug like exploring-second-brain-four-steps-to-boost-productivity. The whole process requires no manual translation — just one click.

Who is this for?

  • People who write Markdown posts in VS Code
  • Articles are in Chinese (or other non-English languages) but want English URLs
  • Using Front Matter CMS to manage content
  • Want to save time on translating and formatting URL slugs

About Front Matter CMS

I only recently discovered Front Matter CMS, a VS Code extension (download here) that makes managing Markdown content much easier for static site maintainers. It offers an intuitive interface and supports custom features. The “AI-generated slug” feature is one such example, seamlessly integrating into your writing workflow once set up.

Prerequisites

Required tools and accounts

  • VS Code (with Front Matter CMS extension installed)
  • Node.js (recommended v18+)
  • A static site project (any framework)
  • Google AI Studio account (to get Gemini API Key)

Install dependencies

# npm
npm install -D @dotenvx/dotenvx @google/genai @frontmatter/extensibility

# or pnpm
pnpm add -D @dotenvx/dotenvx @google/genai @frontmatter/extensibility

# or yarn
yarn add -D @dotenvx/dotenvx @google/genai @frontmatter/extensibility

Obtain Gemini API Key

  1. Go to Google AI Studio
  2. Sign in with your Google account
  3. Create an API Key and copy it for later use

Setup steps

1. Create script

Add scripts/generate-slug-gemini.js in your project root:

import process from 'node:process'
import dotenvx from '@dotenvx/dotenvx'
import { FieldAction } from '@frontmatter/extensibility'
import { GoogleGenAI } from '@google/genai'

// Load environment variables with quiet option to suppress debug output
dotenvx.config({ quiet: true });

(async () => {
  const { frontMatter } = FieldAction.getArguments()

  if (!frontMatter) {
    FieldAction.done('Error: Front matter data not found')
    return
  }

  if (!frontMatter.title || frontMatter.title.trim() === '') {
    FieldAction.done('Error: Post title is missing or empty')
    return
  }

  const apiKey = process.env.GEMINI_API_KEY
  if (!apiKey || apiKey.trim() === '') {
    FieldAction.done('Error: GEMINI_API_KEY environment variable not found or empty')
    return
  }

  const ai = new GoogleGenAI({ apiKey })

  const model = process.env.GEMINI_MODEL || 'gemini-2.5-flash'

  const prompt = `Convert the following Chinese blog post title into a concise English URL slug.

Requirements:
- Return ONLY the slug, nothing else
- Use lowercase letters only
- Connect words with hyphens (-)
- Remove all special characters, spaces, and punctuation
- Keep it concise but descriptive
- Make it SEO-friendly

Chinese Title: "${frontMatter.title}"`

  try {
    const result = await ai.models.generateContent({
      model,
      contents: prompt,
    })

    if (!result || !result.text) {
      FieldAction.done('Error: Gemini AI returned empty response')
      return
    }

    let slug = result.text.trim()

    // Remove quotes that AI sometimes adds
    if (slug.startsWith('"') && slug.endsWith('"')) {
      slug = slug.slice(1, -1)
    }

    // Ensure slug meets URL requirements
    slug = slug
      .toLowerCase()
      .replace(/[^a-z0-9\-]/g, '-')
      .replace(/-+/g, '-')
      .replace(/^-|-$/g, '')

    FieldAction.update(slug)
  }
  catch (error) {
    FieldAction.done(`Error: Failed to generate slug - ${error.message}`)
  }
})()

2. Set API Key

Create .env in your project root:

GEMINI_API_KEY=your_api_key_here

# Optional: specify Gemini model (default is gemini-2.5-flash)
GEMINI_MODEL=gemini-2.5-flash

Make sure .env is listed in .gitignore to prevent committing sensitive information.

If .gitignore does not exist or does not include .env, you can add it with:

# Add to .gitignore to avoid committing secrets
echo ".env" >> .gitignore

💡 Model choice: The script defaults to gemini-2.5-flash, currently the best model for text generation. To try other models, see Gemini API Model Docs.

3. Configure Front Matter CMS

Edit frontmatter.json:

{
  "frontMatter.taxonomy.contentTypes": [
    {
      "name": "post",
      "fields": [
        {
          "title": "Title",
          "name": "title",
          "type": "string",
          "single": true
        },
        {
          "title": "URL Slug",
          "name": "slug",
          "type": "string",
          "single": true,
          "actions": [
            {
              "title": "Generate from Title",
              "script": "./scripts/generate-slug-gemini.js"
            }
          ]
        }
      ]
    }
  ]
}

What it looks like after setup

  1. Open a post
  2. Find the “URL Slug” field in the Front Matter panel
  3. Click the small terminal icon button ( >_ ) to the right of the “URL Slug” field
  4. The English slug will be automatically generated and filled in

Troubleshooting

Issue: Button does not appear or clicking does nothing

# Check frontmatter.json syntax
npx jsonlint frontmatter.json

# Confirm script path exists
ls -la scripts/generate-slug-gemini.js

# Reload Front Matter CMS
# Run "Front Matter: Refresh Front Matter Settings" from the Command Palette

Issue: Error GEMINI_API_KEY environment variable not found

# Check if .env is in project root and formatted like below
cat .env
# Should see: GEMINI_API_KEY=your_api_key_here
# After changes, fully restart VS Code

Issue: Error The script did not return a field value

Remove all console.log / console.error statements. Front Matter only accepts output from FieldAction.update() and FieldAction.done().

Issue: Gemini returns empty response

Check your API Key validity and quota at Google AI Studio.

Conclusion

Since setting up this feature, my writing workflow has become smoother. Although manually translating slugs is a small task, automating it lets me focus more on the content itself. Sometimes, the smoothness of writing comes from these small but meaningful improvements.


Resources:

Thanks for reading! If you find my sharing meaningful, please consider supporting me by buying me a Boba 🧋: https://anna.bobaboba.me