Search code examples
strapi

How to integrate Strapi with a SSG using lifecycle callbacks?


I'm using Strapi together with a static site generator (Gatsby), and I'm trying to automate the "rebuild" process whenever you make any modifications in the CMS content.

I'm trying to use the lifecycle callbacks mentioned in the Strapi documentation to do this: https://strapi.io/documentation/3.x.x/guides/webhooks.html

The problem is that these callbacks are being called multiple times in different models. For example, the "afterUpdate" callback is getting called 5 times for the 5 models I have.

I only want to execute the build trigger function only once per change, is there a way to do that?


Solution

  • This seems to be the correct behavior of Strapi lifecycle callbacks: https://github.com/strapi/strapi/issues/1153

    Actually there is no issue here. In fact when you create an entry, we first create the entry and then update to handle relations. That's why many events are trigger on create entry.

    The documentation is misleading and I don't think lifecycle methods should be used to trigger the SSG builds.

    A better choice I found is to use the ContentManager.js controller, it's located in: plugins/content-manager/controllers/ContentManager.js

    The create, update and delete functions get called only once per request, so this is a better place to trigger a SSG build:

    delete: async ctx => {
        ctx.body = await strapi.plugins['content-manager'].services['contentmanager'].delete(ctx.params, ctx.request.query);
    
        // This is just a request to another service
        // that triggers the SSG build.
        await build.triggerSSGBuild();
    },