I want to trigger a re-deploy of my Hugo blog which is hosted on Netlify.
In the past, I’ve successfully used ifttt with a webhook.
Unfortunately, they’ve stopped supporting the webhook feature on the free tier.
What’s the solution?
Netlify has a tutorial on how to use serverless functions for automatic deploys.
Here is the concise tutorial with a few steps added which weren’t clear to me.
How to schedule deploys on Netlify using serverless functions
You’ll need Node.js on your machine.
Create a new
npm
project in your current directory (Hugo folder) by runningnpm init -y
.Install the dependencies by running the following command in your terminal:
npm install @netlify/functions
npm install node-fetch
- Add the required configuration in
netlify.toml
:
[functions]
node_bundler = "esbuild"
- Get your build hook URL.
The name doesn’t matter much. I’ve called mine “netlify serverless function”.
- Set the URL as environment variable (replace with yours, below is a placeholder example):
npx netlify-cli env:set BUILD_HOOK_URI https://api.netlify.com/build_hooks/<xxxxxxxx>
- Create a file
/netlify/functions/scheduled-deploy.mjs
. It’s important that you choose the correct path (inside the/netlify/functions
directory).
(You can choose a different location, but in that case you’ll need to configure it in netlify.toml
. I didn’t want to bother with that.)
import fetch from 'node-fetch'
export default async () => {
try {
const BUILD_HOOK = Netlify.env.get('BUILD_HOOK_URI')
const response = await fetch(BUILD_HOOK, {
method: 'POST',
})
return new Response('Build triggered')
} catch (error) {
console.error('Error triggering build hook:', error)
return new Response('Error triggering build hook', {
status: error.response?.status ? error.response.status : 500,
statusText: error.response?.message ?? "Uh oh, this didn't work"
})
}
}
// Schedules the handler function to run every day at 19h UTC
export const config = {
schedule: '0 19 * * *',
}
Check crontab.guru for a different schedule.
If you want to know more about scheduled functions, you can check the docs.
- Test locally
npx netlify-cli dev
The command will start a new local server. Open your webbrowser on http://localhost:8888/.netlify/functions/serverless-deploy
.
This will trigger the function and you should see that you’ve started a new deploy successfully in your Netlify dashboard.
- Source control and commit
I use git and GitLab/GitHub for my blog, so I’ve commited my changes and pushed them to my repository. The remote repo is connected to Netlify. Netlify should pick up the changes automatically.