Directus Flows slug generator

Use Directus Flows to create slugs

Directus Flows slug generator
const slugify = text =>
  text
    .toString()
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .toLowerCase()
    .trim()
    .replace(/\s+/g, '-')
    .replace(/[^\w-]+/g, '')
    .replace(/--+/g, '-');

module.exports = async function(data) {
    // if title not passed
    if (data.$trigger.payload.title === undefined) return data.$trigger.payload;
    // if user entered slug themselves...
    if (data.$trigger.payload.slug !== undefined) return data.$trigger.payload;
    /// generate slug
    const slug = slugify(data.$trigger.payload.title);
    return {...data.$trigger.payload, slug};
}

How to Use it

For this example, we'll create a collection called posts, and inside this collection, we'll add two input fields:

  1. title
  2. slug

Now go to flows and create a new flow.

1

Create a blocking flow

Set the flow to blocking, to run during create and update, (or just on create).

2

Create a Run Script Block

Drag the arrow and choose run script.

3

Copy the code in to the code block and hit save.

Now when a new post is created or a post is updated, the flow will run and update the slug field as long as the title isn't empty and the slug is also empty.