Build and Deploy Hooks
Learn how to hook onto key lifecycle events of the "webiny deploy" commands.
Build-related hooks outlined in this guide are available since Webiny v5.20.0, while deploy-related ones are available already since Webiny v5.0.0.
- how to run custom code before and after build and deploy steps
Introduction
Internally, thewebiny deploy
command consists of two steps:- build - within this step, your application code gets compiled and is made ready for deployment
- deploy - within this step, the compiled code, along with the defined cloud infrastructure resources gets deployed
In some cases, it might be necessary to run some code before or after build or deployment. For example, you may want to add some additional logging or validation.
This is why thewebiny deploy
command enables hooking onto a couple of its key lifecycle events:- pre-build
- post-build
- pre-deploy
- post-deploy
The following diagram shows in which order these lifecycle events are triggered:
We can hook onto any of these events via a dedicated plugin type, which we cover in the following section.
Creating a Hook
The following code demonstrates all of the plugin types we can use in order to hook onto the command’s key lifecycle events. We are defining them within the cli.plugins
section of the object exported from the root webiny.project.ts
file.
// Some of the code is removed for brevity.
export default {
name: "your-project",
cli: {
plugins: [
// ... all other plugins go here
{
type: "hook-before-build",
name: "my-custom-hook-before-build",
async hook(args, context) {
// Gets executed before the build (application code compilation) step.
}
},
{
type: "hook-after-build",
name: "my-custom-hook-after-build",
async hook(args, context) {
// Gets executed after the build (application code compilation) step.
}
},
{
type: "hook-before-deploy",
name: "my-custom-hook-before-deploy",
async hook(args, context) {
// Gets executed before the deployment of the compiled code
// and other necessary cloud infrastructure resources.
}
},
{
type: "hook-after-deploy",
name: "my-custom-hook-after-deploy",
async hook(args, context) {
// Gets executed after the deployment of the compiled code
// and other necessary cloud infrastructure resources.
}
}
]
}
};
FAQ
Can I Define My Plugin in a Separate File and Simply Import It in the webiny.project.ts
File?
Yes, you can and that’s probably the best way to do it because the webiny.project.ts
file will be easier to read.