Strapi is one of the most popular headless content management systems (CMS) written using Javascript. As a reminder, in the case of headless CMS, the data presentation layer is not part of the content management system.
As in other solutions of this type, the creators of the CMS called Strapi try to provide universal solutions to satisfy the widest possible group of users. Something that is universal will most likely not meet all users’ requirements. The logic of the application can be adapted to our requirements using, among others, lifecycle hooks. This topic is what I would like to focus on in this article.
These hooks are functions that are called automatically when a specific operation occurs. They allow us to implement additional logic before and after adding, editing, deleting, getting or counting data. Thanks to them, we can modify and extend the default logic implemented in the content management system. It is worth noting that lifecycle hooks can be customized declaratively or programmatically. I recommend that you read the details available in the CMS documentation, which you can read here.
I will try to present the advantages of this solution based on a specific example. I encountered a situation where data generated using a defined content type should affect other data derived using the same content type. Namely, the moderator has the ability to add articles and define which of them will be the leading article. By design, only one article can be marked in this way.
The problem described above was solved with little effort using lifecycle hooks. Initially, I added a method that allows you to mark lead articles that are not currently edited as standard.
Then I extended the logic that should be performed when adding a new article or editing an existing one.
Lifecycle hooks can also be used to extend standard data validation. For example, the form allows you to enter dates, and we want to limit their range to a date in the past. We have no way to achieve such an effect using built-in tools. The solution may be to validate this data from the lifecycle hook level before saving it and return an error message to the moderator. An exception can be returned as follows:
Lifecycle hooks are just one of the functionalities that Strapi provides us with so that we can adjust the behavior of the content management system to our needs. I hope that by describing the above 2 examples, I have shown how, in a convenient way, we can extend the logic of our application.
Krzysztof Kura