Menu
- Why Eleventy?
- Get Started
- Community
- Working with Templates
- Using Data
- Configuration
- Template Languages
- Plugins
- API Services
- Release History
- Advanced
1.93s
70.65s
Quick Tip #007—Fetch GitHub Stargazers Count (and More) at Build Time
Older iterations of this website used a third party JavaScript widget to show the number of GitHub Stars the project currently had. You can see it in action on the versioned docs for 0.7.1 (scroll to the bottom).
This was in fact the only <script>
tag on the entire 11ty.dev web site and it was from a third party. Naturally, it needed to be annihilated.
Let’s change up our architecture to ruthlessly eliminate this client-side JavaScript.
Get the Stargazers Count from the GitHub API Jump to heading
Read more at the GitHub API documentation.
This is a bit different from our client-side implementation because this data is only updated as often as your build runs. This is implemented using a global JavaScript data file at _data/github.js
.
- Install new dependencies:
npm install node-fetch@cjs --save-dev
- Read more about
node-fetch
const fetch = require("node-fetch");
module.exports = async function() {
console.log( "Fetching new github stargazers count…" );
// GitHub API: https://developer.github.com/v3/repos/#get
return fetch("https://api.github.com/repos/11ty/eleventy")
.then(res => res.json()) // node-fetch option to transform to json
.then(json => {
// prune the data to return only what we want
return {
stargazers: json.stargazers_count
};
});
};
Now in your templates you can output the stargazers count with:
{{ github.stargazers }} GitHub Stars
which outputs
1515 GitHub Stars
Bonus: I created a humanReadableNum
filter) using the human-readable-numbers
package to format the number.
More Examples Jump to heading
You can look in the footer of this page to see examples of this in use on this very web site. I used it for:
- NPM Download Count
- GitHub Stargazers Count
- Twitter Followers Count (careful here, this one is super brittle but Twitter’s API is historically anti-developer so 😇)
These all use the recommended caching mechanism described in the next section.
Recommended: Cache the Data to the File System Jump to heading
Update Counts Daily Jump to heading
If you want to update these counts automatically every day, read Quick Tip #008—Trigger a Netlify Build Every Day with IFTTT.
All Quick Tips
#001
—Inline Minified CSS#002
—Inline Minified JavaScript#003
—Add Edit on GitHub Links to All Pages#004
—Zero Maintenance Tag Pages for your Blog#005
—Super Simple CSS Concatenation#006
—Adding a 404 Not Found Page to your Static Site#007
—Fetch GitHub Stargazers Count (and More) at Build Time#008
—Trigger a Netlify Build Every Day with IFTTT#009
—Cache Data Requests#010
—Transform Global Data using an `eleventyComputed.js` Global Data File#011
—Draft Posts using Computed Data- View all of the Eleventy Quick Tips.