Custom webhook to trigger build on DigitalOcean App Platform using Strapi

garbanv

Alexei Garban

Posted on May 21, 2021

Custom webhook to trigger build on DigitalOcean App Platform using Strapi

A couple of days ago i needed to create a webhook to trigger a GatsbyJs build after update, create or delete something in our backend using Strapi.

Strapi has a built in option to do that very easy if your frontend app is on Netlify, but our app is on Digitalocean so we need to create our own webhook.

Reading digitalocean's documentation i found that the url that we need to make the request is this one:

https://api.digitalocean.com/v2/apps/YOUR_APP_ID/deployments

First we need to go to our api endpoint models (in this case i'm using Strapi) and i want to rebuild after creating , deleting or updating a post, so i will go to /api/posts/models/posts.js

We are going to use Strapi lifecycles hooks, afterCreate,afterUpdate,afterDestroy.

We also need to create a Token / Key in digitalocean (your digitalocean account/->api->Tokens/Keys)

I put the token in a .env file as POSTS_BUILD_TOKEN

then install axios npm i axios

Our /api/posts/models/posts.js should look like this:

'use strict';
const axios = require('axios')

const token = process.env.POSTS_BUILD_TOKEN

module.exports =  {

    lifecycles: {

    async afterCreate()  {

        axios({
            method: 'post',
            headers: {
                'Content-Type': 'json',
                'Authorization': `Bearer ${token}`
            },
            url: 'https://api.digitalocean.com/v2/apps/${token}/deployments',
           body:{
               "force_build":true
            }
          });
      },


    }
};
Enter fullscreen mode Exit fullscreen mode

Then you can go to your Content Type and create, edit or delete and as soon as you click save, it will trigger the build.

💖 💪 🙅 🚩
garbanv
Alexei Garban

Posted on May 21, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related