Strapi Webhook Integration
Strapi is great headless cms to develop any kinds of apps, it provides seamless integration with most of the front end stack like Angular, React, Next JS, Gastby, Vue JS etc. Strapi can provide us a powerful headless backend by which we can easily create a database driven backend easily, and only we need to focus on the front end to develop the apps.
Introduction:
In front end we can build Server Side Rendering or Static Site Generator Application. But there is catch in Static Site Generator app like which built on by using Gastby or Next JS SSG. The problem is as it is static site generator application, so for each and every build time we will get the fresh content. So suppose if you create a Gastby App and if you changed any data in strapi and if you want to see the change result in the UI then directly in the Gastby website you cannot see the changes. It is because it will provide you the fresh content or latest changes at build time. So in order to see the latest changes you need to build the Gastby Application whenever any new content is updated to Strapi. This functionlaity we can achieve using Webhook, Webhhok will trigger based on some event. So In here Strapi provide webhook features under Settings > Webhook tab. So In this webhook we can integrate any webhook which do not have any payload. But If you are using Github Action then you must have one mandatory payload required and that is {“ref”:”branch-name”}. So Strapi by default will not support this feature that you can payload from the strapi admin panel. So to create Github Action Webhook in Strapi we need to use our own custom global middlewear from strapi and by using middlewear we can create a very reusable robust dynamic github action webhook.
Create a new API name webhookhandler in Strapi:
So First navigate to src>api directory and then create a folder name called webhookhandler like this src>api>webhookhandler. So under this folder we will two folders namelt controllers and routes. So In the routes folder we will define our webhook handler route which will point to the webhookhandler controller file function and controller to do the webhook api call and in the strapi webhook panel we need define the route url. So we will discussed the implementation in more detail in below. So right now lets focus on building the route of webhookhandler.
Create a Route of webhookhandler:
So now navigate to this folder src>api>webhookhandler>routes, and under this folder create a file name called webhookhandler.ts as we are using typescript in our strapi project and file structure look like this given below. src>api>webhookhandler>routes>webhookhandler.ts. We have created our router ts file for webhook now lets define the route of webhookhandler by following this code.
export default {
routes:[
{
method: "POST",
path: "/webhookhandler",
handler: "webhookhandler.webhookAction",
config: {
policies: [],
middleweares: []
}
}
]
}
So If you see the above code then we have define the method is POST, as webhook always expect POST call and then we defined the api route by using path key name, so it means the url path or Rest API parth will be http://localhost:1337/api/webhookhandler. After that we have define our handler name and that is webhookhandler.webhookAction, So the first one before dot is the controller file name and that is webhookhandler.ts under controller folder of webhook and then corresponding function which call trigger a function name webhookAction in webhook controller when we do a post call to this rest api. http://localhost:1337/api/webhookhandler.
Create a Controller of webhookhandler:
As we discussed that when we do the post call of webhookhandler api it will trigger webhookhandler controller, So lets now create a controller name webhookhandler.ts file under the controller folder and file structure look like this src>api>webhookhandler>controllers>webhookhandler.ts. Once we have created the controller file now it is our time to call the actual github action webhook api from the webhookhandler controller file from the webhookAction function. lets create a dynamic webhook handler for github action by writing this follwing code.
import fetch from 'node-fetch';
export default {
webhookAction:async (ctx, next) => {
if (ctx.request.body.event === 'trigger-test') {
try {
let response = await fetch(ctx.request.header.url, {
method: ctx.request.method ,
headers: {
'Content-Type': ctx.request.header['content-type'],
'Accept': ctx.request.header.accept,
'Authorization': ctx.request.header.token
},
body: ctx.request.header.payload
});
if ([200, 201, 204].includes(response.status)) {
return ctx.send('success', response.status);
} else {
return ctx.throw(response.status);
}
} catch(err) {
return ctx.throw(err.status, 'failed');
}
} else {
return ctx.throw(403);
}
}
}
So in the above code you have written a full fledged webhook which is not static rather it is dynamic and it those parameters will be managed from the webhook section itself. So lets now understand the code, First we have ctx object that is nothing but context object where we will get request and response object. So by default the webhook event name is trigger-test, so that that is why we have checked that is it a webhook event or not. Now if it is webhook event then we will call one post api which will trigger the github action webhook. So now lets talk about of each dynamic parameter.
Github Action Webhook Rest API will like this given below.
{url: ctx.request.header.url= https://api.github.com/repos/organization/reponame/actions/workflows/github-action-production.yaml/dispatches,
method: ctx.request.method = POST,
headers: {
'Content-Type': ctx.request.header['content-type'] = application/json,
'Accept': ctx.request.header.accept = application/vnd.github+json,
'Authorization': ctx.request.header.token = Bearer your_github_action_token
},
body: ctx.request.header.payload = {"ref":"master"} (eg. master is prod branch)
}
So above will be your webhook values that you need configure in the strapi webhook admin panel and that is call now if you change any content it will automatically trigger a build using your custom github action webhook.
So In the image you can see that we have configures all of the paramaters in the webhook admin panel and we can access it by using ctx.request object. Now if you trigger the webhook manually you will get forbidden error 403, So the question is why and answer is given below.
Give Permission to webhookhandler Route:
So Now navigate to Settings/USERS & PERMISSIONS PLUGIN/Roles/Public/webhookhandler and now enable the webhookActio route from the webhookhandler route folder.
So Once you will enable it you and then if you trigger the webhook manually or changed any content in strapi then you can trigger the github action webhook.
Conclusion:
Github Action Webhook is one of important factor for Static Site Generator application, we need to leverage the webhook for ssg application and Github Action provides a very strong webhook that we can customize in various ways. Strpai is one of the important headless where we need the Github Action Wehbook and be default strapi do not support any mechanism to post webhook payload from the admin panel. But we have created a rigid solution by which you can create full fledged dynamic github action webhook and even you can customize in your own way.