# A GitHub Activity Calendar on a Static Site, Rebuilt Every Night
The home page of this site has a GitHub-style activity calendar: one square per day for the last 12 months, darker on busier days. The site itself is static. Astro builds it into HTML files, and Cloudflare Pages serves them. The calendar’s data changes every day, and the HTML only changes when the site is rebuilt.
It took me three versions to settle how those two fit together. The third one fetches the data at build time and rebuilds the site every night from a cron job. This post covers how it renders, how it updates, what it costs, and what I gave up for it.
Version 1: fetched at build, never refreshed
The theme I started from already had a calendar component. It fetched contributions from github-contributions-api.jogruber.de, a free service that returns a year of GitHub contributions as JSON, right in the component’s frontmatter. I added a JSON file of GitLab counts I had exported once and merged it into the GitHub numbers.
The fetch ran during npm run build, and Pages only builds when I push. If I didn’t push for three weeks, the calendar stopped three weeks ago. The GitLab file never changed after I exported it. On a phone, the calendar showed its oldest months, and the newest ones, the interesting ones, were off-screen to the right.
Version 2: fetched in the browser
The API sends access-control-allow-origin: *, so moving the fetch into a client script was easy. The data was fresh on every visit. The problems were on the page:
- The block was empty until the response arrived, then popped in and pushed everything below it down. I hid it until the data came and added a reveal animation, which is extra code to fix a problem I had just created.
- Every visitor made a request to a third-party API, and the page shipped JavaScript to build the SVG.
- A search engine or link preview that doesn’t run scripts saw no calendar.
Astro’s built-in way to defer a component, server:defer, needs a server adapter, and I wanted the site to stay plain static files.
Version 3: a content loader and a nightly rebuild
The calendar doesn’t need to-the-minute data. Today’s square can wait until tomorrow. So the fetch went back into the build, this time through Astro’s Content Layer, and a cron job rebuilds the site every night.
The loader
A collection’s loader runs at build time and writes entries into Astro’s data store. Mine fetches the last 12 months and stores them as one entry:
// Last 12 months of GitHub contributions, fetched at build time.const activityCollection = defineCollection({ loader: githubActivityLoader({ username: 'AntonBurduzha' }),});load: async ({ store, logger, parseData }) => { for (let attempt = 1; attempt <= ATTEMPTS; attempt++) { try { const response = await fetchLastYear(username); const data = await parseData({ id: username, data: { total: response.total.lastYear ?? 0, contributions: response.contributions, }, }); store.clear(); store.set({ id: username, data }); return; } catch (error) { logger.warn( `Attempt ${attempt}/${ATTEMPTS} failed: ${(error as Error).message}`, ); if (attempt < ATTEMPTS) { await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS * attempt)); } } } logger.warn( store.has(username) ? 'Keeping previously loaded activity.' : 'No activity data: the calendar will be hidden.', );},parseData validates the data against a Zod schema, so a changed API format counts as a failed attempt instead of drawing a broken calendar. If all three attempts fail (2 and then 4 seconds apart), the store keeps the previous entry if it has one, and the build goes on either way. A broken third-party API never breaks a deploy.
Rendering
The component reads the collection and renders the SVG on the server:
---const [activity] = await getCollection('activity');const calendar = activity ? renderCalendar(activity.data.contributions) : undefined;---If there’s no entry, nothing renders. There’s no empty state or spinner, and the layout below doesn’t move.
renderCalendar in src/activity.ts is a plain TypeScript function that returns an SVG string and a date range. It doesn’t import anything from Astro, so it would work the same in a browser script. It does four things:
- Fills the gaps. Every day between the first and last date gets an entry, with zero for the missing ones.
- Groups days into weeks. The list is left-padded so every column starts on a Sunday. The first column can have empty slots at the top, like on GitHub.
- Computes the levels itself. The API sends a level from 0 to 4 for each day, but the function recomputes them from the quartiles of my non-zero days. That was required in version 1, when GitLab counts were added and the API’s levels no longer matched the totals. I kept it so the shade of a square always follows the count in its tooltip.
- Takes its colors from the theme. Level 0 is the theme’s background, level 4 is its accent, and the steps between are
color-mix(in oklab, …)of the two CSS variables. The calendar follows the light and dark themes without a palette of its own, and it would follow any other theme too.
Month labels go over the first column of each month. A month at either edge with fewer than three columns loses its label, since the text wouldn’t fit. Instead of a year on every label, the header shows the range, Nov 2025 – Dec 2026.
The page has two small scripts. One scrolls the calendar to the right edge, so phones open on the newest weeks. The other is the tooltip: a single delegated mouseover listener on the calendar instead of 367 listeners, one per square. It only starts on screens at least 1024 px wide, where there’s a mouse to hover with.
The nightly rebuild
Cloudflare Pages has deploy hooks: a secret URL that starts a build of a branch when you POST to it. A Worker with a cron trigger calls it every night:
export default { async scheduled(_controller, env) { if (!env.DEPLOY_HOOK_URL) throw new Error('DEPLOY_HOOK_URL secret is not set'); const response = await fetch(env.DEPLOY_HOOK_URL, { method: 'POST' }); if (!response.ok) { throw new Error(`Deploy hook failed: ${response.status} ${await response.text()}`); } },};{ "name": "aburduzha-daily-rebuild", "main": "src/index.js", "triggers": { "crons": ["15 0 * * *"] }, "observability": { "enabled": true },}The hook URL is a Worker secret, not something in the repo, because anyone with it can start builds. A failed call throws, so it shows up as a failed run in the Worker’s logs.
I also looked at GitHub Actions with a schedule trigger. It needs no extra service, but scheduled runs can start late, and GitHub turns schedules off in a public repository with no activity for 60 days. A personal site can easily go two months without a commit.
What it costs
Nothing. The Pages free plan allows 500 builds a month, one at a time. The nightly rebuild uses about 31 of them, so there’s plenty left for pushes. A Worker that runs once a day is well inside the Workers free plan, and a build takes a minute or two.
What I got
- The calendar is in the HTML. No empty block, no layout shift, no animation to hide either of them.
- The only JavaScript for it is the tooltip and the scroll. No script fetches or draws anything.
- Visitors don’t depend on a third-party API, and an API outage costs at most one night’s update.
- Search engines and link previews see the same page people do.
What I gave up
- Freshness. The data is up to a day old. For a year of activity that doesn’t matter. For a live status page it would.
- HTML size. 367
<rect>s with inline attributes come to about 77 KB of the home page’s 103 KB of HTML. It compresses well, to about 4 KB gzipped, because the squares are nearly identical, but it’s still the biggest thing on the page. - Builds that change nothing. The site rebuilds every night even when the data is the same as yesterday. At this size it costs nothing, but a site with thousands of pages and a 15-minute build would feel it.
- A failed night can hide the calendar. Astro keeps its data store in
node_modules/.astro. Locally that survives between builds, so a failed fetch keeps yesterday’s data. On Pages I don’t count on that cache being there, so if the API is down at 00:15 UTC, the calendar can be missing until the next night. - An unofficial data source. The contributions API is a free service run by one person, not GitHub’s own API. GitHub’s GraphQL API has the same data, but it needs a token in the build environment, and I didn’t want a secret in the Pages build for one widget.
- One more thing to deploy. The Worker lives in this repo but deploys separately with
wrangler, and the deploy hook is set up by hand in the dashboard. Both are written down in the deploy guide, because I won’t remember them in a year.
When I’d do it differently
| Approach | When it fits |
|---|---|
| Build time + scheduled rebuild | Data that can be a day old, a static host, a fast build |
| Fetch in the browser | Data that must be current to the minute, or different for each visitor |
Server rendering with a CDN cache (s-maxage) | Many pages use the data, or the build is too slow to run every day |
| Rebuild on a webhook from the source | The source can tell you when it changes, like a CMS |
For a calendar of a year’s activity, the first row fit. The whole setup is a loader, a render function and a dozen lines of Worker.