Why plan recurring builds
Using Hugo as a SSG (Static Site Generator), you can write an article and set the publish date in the future.
However, because of how SSG work, you would need a build to publish the article on the target date.
I could easily trigger the build manually from the Netlify dashboard, but wouldn’t it be better to have an automated process handle this. So how do you automate the build?
Thanks to Talves on this forum thread that pointed me to this guide (even if the solution is a bit obsolete), I manage to find the solution from that starting point.
Here are the steps:
In the Netlify Dashboard
-
Create a Build hook from
https://app.netlify.com/sites/<your-site-name>/configuration/deploys
- Select your site
- Then, go to
Deploys
blade in the primary menu. - Then, select
Deploy settings
- By default, you’re in the proper screen (
Build & deploy > continuous deployment
). There, scroll downBuild hooks
. - Click
Add build book
- Give a name to the hook like Daily publish and select the branch you want to target.
- Click Save and copy the URL.
-
Next, go to
Environment variables
that is a little bit down this secondary blade menu. -
Add a new environment variable that you’ll call
RECURRING_PUBLISH
and paste the copied URL as the value.
If you name the variable differently, please adjust the function script.
In your IDE with a clone of your repository
-
Install Netlify CLI as a development dependency on your repository:
1
npm i -D netlify-cli*
-
Install @netlify/functions package so that Netlify knows how to run your function, e.g., the scheduling part:
1
npm i @netlify/functions*
-
Add a npm script: to be able to run the CLI to create the function:
1
"netlify": "netlify"
-
Create a function using the CLI:
1
npm run netlify functions:create recurring_publish*
-
Add specify where you store the functions in
netlify.toml
file:1 2 3 4
[build] ignore = "exit 1" publish = "public" functions = "functions" #the function was create into the directory 'functions' at the root of your repository.
-
Use this function code (I’ve commented on it heavily) :
|
|
- Push everything for a new build.
Back on Netlify Dashboard
At the end of the build, check Logs > Functions blade under your app:
The recurring_publish function should appear and tell you it will run the next cron
time, in the example at 4:00 AM GMT time.
NB: you can’t use an environment variable to define the cron
value as Netlify will tell you:
|
|
This procedure works as of April 8, 2024.
Since I’m using it for my two blogs, if it breaks, I will update this article accordingly.
Thanks for reading this far and enjoy your scheduled Netlify builds.
Credit: top photo by Lukas Blazek on Unsplash.