DEV Community

Cover image for Create a slug system with Strapi v4
Oscar Bustos
Oscar Bustos

Posted on

5 3

Create a slug system with Strapi v4

Let's create a slug system with Strapi V4.

1 Create a new file following this structure

./src/api/[api-name]/content-types/[content]/lifecycles.js
Enter fullscreen mode Exit fullscreen mode

We can control the lifecycle on this file, so we can transform our information on several events. Check the documentation.

2 Install slugify dependency

yarn add slugify
Enter fullscreen mode Exit fullscreen mode

3 Add code on your lifecycle file.

const slugify = require("slugify");

module.exports = {
  beforeCreate(event) {
    const { data } = event.params;
    if (data.title) {
      data.slug = slugify(data.title, { lower: true });
    }
  },
  beforeUpdate(event) {
    const { data } = event.params;
    if (data.title) {
      data.slug = slugify(data.title, { lower: true });
    }
  },
};

Enter fullscreen mode Exit fullscreen mode

As you can see the slug is based on our title.

That's it!

So easy

Top comments (3)

Collapse
 
kunal2001 profile image
Hanuman2001

Thanks very much it really helped

Collapse
 
jackjones profile image
Jack Jones

This is now a feature natively built into Strapi V4.

Essentially you can create a second 'ID' field that takes the title and converts it into a slug automatically :)

Collapse
 
olyphotographer profile image
Peter Arnold

This was really helpful! Thanks

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay