Go back to archives

Automate Slug Generation in Directus Using Flows

In this tutorial, I'll show you how to automatically create a slug from a title using Directus Flows. We’ll automate this action within the Flow. For this example we will be building a blog collection.

Creating a Data Model Collection

Start by creating a new collection for your blogs via the Data Model. Name it "blogs". You don’t need to add optional fields, but make sure to create two fields: one called "title" and another called "slug".

Now, you have everything set up for a basic start.

Adding your first Flow

When creating a Flow, give it a name, for example; "Blog Title to Slug," and add an icon if you like.

Event Hook

  • Event: Select "Triggers on platform or data events."
  • Action: Select "Non-Blocking."
  • Scope: Choose the actions for which this function will trigger (we’ll use items.create and items.update).
  • Collection: Select the blogs collection.

You should now see a checkmark icon and a plus icon on the right. Click the plus to add a new operation.

Creating a slugify Operation

Name the operation slugify_me and rename the key to the same. We will be using this later.

Now, select "Run Script" and delete the default content. Add this script:

Code
js
module.exports = async function (data) {
    // Index data to get the string you want to slugify
    const text = data.$trigger.payload.title;

    const slug = text
        .toLowerCase()
        .trim()
        .replace(/[^\w\s-]/g, '')   // Remove unwanted characters
        .replace(/[\s_-]+/g, '-')   // Replace spaces/underscores with hyphens
        .replace(/^-+|-+$/g, '');   // Remove leading/trailing hyphens

    return slug;
};

Testing the Flow

To test if this works, create a new operation on the both + and - and select "Log to Console." Add these logs:

Succes console log
js
Succes {{$last}}, {{$trigger}} {{slugify_me.id}} - {{operation_key}}
Error console log
js
Error {{$last}}, {{$trigger}}

Updating the Slug

Next, create an operation to update the slug. Here’s how:

  • Collection: Press { } and select the current collection used in the trigger ({{$trigger.collection}}).
  • Permissions: Set them to "From Trigger."
Payload
bash
{
    "slug": "{{ slugify_me }}"
}

Query Filter

To specify the correct colection item being updated, add this filter:

Query
bash
{
    "filter": {
        "id": {
            "_eq": "{{ $trigger.keys[0] }}"
        }
    }
}

Verifying Success

Finally, add another "Log to Console" operation to verify success. You can name it Success or anything you would like.


That’s it! You’ve created an automated slug generator using Directus Flows. If you found this tutorial helpful, please upvote it to help others find it.

Like this blog? Click the button above to upvote it!