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
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
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 });
}
},
};
As you can see the slug is based on our title.
That's it!
So easy
Top comments (3)
Thanks very much it really helped
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 :)
This was really helpful! Thanks