Create a slug system with Strapi V4
— Strapi — 1 min read
Follow this 2 steps guide to create a slug system with Strapi v4.
1. Slug field configuration
⚠️ First make sure the slug field is NOT required
Click at the Configure View button inside the Content-Type page:
- Add the follwing text to the slug's placeholder field:
Generated automatically based on the [FIELD_TO_SLUGFY]
. In our case title
- Disable the Editable field option clicking in
false
Save it and let's add the required code to generate the slugs.
2. Slug generation with Slugify
First install slugify
1npm install --save slugify
1yarn add slugify
After installing we need to update Strapi's lifecycles functions to create/update the slug.
Create a file following this format:
./src/api/[ENTITY_NAME]/content-types/[ENTITY_NAME]/lifecycles.js
and add the code bellow to create the slug.
./src/api/article/content-types/article/lifecycles.js
1const slugify = require("slugify");2
3module.exports = {4 beforeCreate({ params }) {5 const { data } = params;6
7 if (data.title) {8 data.slug = slugify(data.title, { lower: true });9 }10 },11 beforeUpdate({ params }) {12 const { data } = params;13
14 if (data.title) {15 data.slug = slugify(data.title, { lower: true });16 }17 },18};
Now we can fetch our content by slug
:
http://localhost:1337/api/articles?filters[slug]=my-slug