Building a seasonal veg app with Eleventy. Part 5 - Scheduled functions with Netlify
Netlify has this feature in beta called Scheduled functions. When I came across it, it sounded like a nice solution to the issue I mentioned in Part 1 where I didn't want to introduce more Javascript to the client-side just to render this month's seasonal veg.
So to start, I created a currentMonth.js file which returned the data of just this month's content. When I saw it working, I changed it to Typescript, but then later when it broke I realised that retrieving data with TS doesn't seem to be supported in Elementy.
Then, I updated the home page with this month's list of seasonal fruit/veg. To avoid repetition, I made sure the markup of the list could be reused in the two templates (index and month pages) by creating a produce-list.njk file, then {% include %}
ing it the templates. Since produce-list.njk used variable month
(object) to render its data from, I updated variable month
to be currentMonth before the {% include %}
on the home page, like so:
{% set month = currentMonth %}
{% include "./produce-list/produce-list.njk" %}
Now that the home page was ready, I created my Netlify function where it triggers a build using their build hooks api:
import type { Config } from "@netlify/functions"
export default async () => {
const response = await fetch(`https://api.netlify.com/build_hooks/${process.env.BUILD_KEY}`, {
method: 'POST'
})
}
export const config: Config = {
schedule: "@monthly"
}
The key to my project's build is replaced with an environment variable stored in Netlify, so that random people don't trigger a build for me whenever they like :D
The scheduling of the function comes from the Config
object with the schedule
property containing a cron expression. Because the list of fruit/veg will only update monthly, I set it to monthly, meaning it will trigger every month on the first day of the month at midnight UTC.
and that was it! My home page now shows this month's seasonal produce, which is statically generated on build time at the beginning of every month.
And in between I had been updating the styling.