If you’ve spent time looking at open-source repos onGitHub, you’ve probably noticed that most of them use badges in their README files.Take the official React repository,for instance.There are GitHub badges all over theREADMEfile thatcommunicate important dynamic info,like the latest released version and whether the current build is passing.
Badges like these provide a nice way to highlight key information about a repository. You can even use your own custom assets as badges, like Next.js does in its repo.
But the most useful thing about GitHub badges by far is that they update by themselves. Instead of hardcoding values into your README, badges in GitHub can automatically pick up changes from a remote server.
Let’s discuss how to add dynamic GitHub badges to the README file of your own project. We’ll start by using an online generator called badgen.net to create some basic badges. Then we’ll make our badges dynamic by hooking them up to our own serverless function via Napkin. Finally, we’ll take things one step further by using our own custom SVG files.
First off: How do badges work?
Before we start building some badges in GitHub, let’s quickly go over how they are implemented. It’s actually very simple: badges are just images. README files are written in Markdown, and Markdown supports images like so:
!\[alt text\](path or URL to image)
The fact that we can include a URL to an image means that a Markdown page will request the image data from a server when the page is rendered. So, if we control the server that has the image, we can change what image is sent back using whatever logic we want!
Thankfully, we have a couple options to deploy our own server logic without the whole “setting up the server” part. For basic use cases, we can create our GitHub badge images with badgen.net using its predefined templates. And again, Napkin will let us quickly code a serverless function in our browser and then deploy it as an endpoint that our GitHub badges can talk to.
Making badges with Badgen
Let’s start off with the simplest badge solution: a static badge via badgen.net. The Badgen API uses URL patterns to create templated badges on the fly. The URL pattern is as follows:
https://badgen.net/badge/:subject/:status/:color?icon=github
There’s a full list of the options you have for colors, icons, and more on badgen.net. For this example, let’s use these values:
- :subject : Hello
- :status: : World
- :color: : red
- :icon: : twitter
Our final URL winds up looking like this:
https://badgen.net/badge/hello/world/red?icon=twitterView the image
Adding a GitHub badge to the README file
Now we need to embed this badge in the README file of our GitHub repo. We can do that in Markdown using the syntax we looked at earlier:
!\[my badge\](https://badgen.net/badge/hello/world/red?icon=twitter)
Badgen provides a ton of different options, so I encourage you to check out their site and play around! For instance, one of the templates lets you show the number of times a given GitHub repo has been starred. Here’s a star GitHub badge for the Next.js repo as an example:
https://badgen.net/github/stars/vercel/next.jsView the image
Pretty cool! But what if you want your badge to show some information that Badgen doesn’t natively support? Luckily, Badgen has a URL template for using your own HTTPS endpoints to get data:
https://badgen.net/https/url/to/your/endpoint
For example, let’s say we want our badge to show the current price of Bitcoin in USD. All we need is a custom endpoint that returns this data as JSON like this:
{ "color": "blue", "status": "$39,333.7", "subject": "Bitcoin Price USD" }
Assuming our endpoint is available at https://some-endpoint.example.com/bitcoin, we can pass its data to Badgen using the following URL scheme:
https://badgen.net/https/some-endpoint.example.com/bitcoin
Even cooler now! But we still have to actually create the endpoint that provides the data for the GitHub badge. ? Which brings us to…
Badgen Napkin
There’s plenty of ways to get your own HTTPS endpoint. You could spin up a server with DigitalOcean or AWS EC2, or you could use a serverless option like Google Cloud Functions or AWS Lambda; however, those can all still become a bit complex and tedious for our simple use case. That’s why I’m suggesting Napkin’s in-browser function editor to code and deploy an endpoint without any installs or configuration.
Head over to Napkin’s Bitcoin badge example to see an example endpoint. You can see the code to retrieve the current Bitcoin price and return it as JSON in the editor. You can run the code yourself from the editor or directly use the endpoint.
To use the endpoint with Badgen, work with the same URL scheme from above, only this time with the Napkin endpoint:
https://badgen.net/https/napkin-examples.npkn.net/bitcoin-badgeView the image
More ways to customize GitHub badges
Next, let’s fork this function so we can add in our own custom code to it. Click the “Fork” button in the top-right to do so. You’ll be prompted to make an account with Napkin if you’re not already signed in.
Once we’ve successfully forked the function, we can add whatever code we want, using any npm modules we want. Let’s add the Moment.js npm package and update the endpoint response to show the time that the price of Bitcoin was last updated directly in our GitHub badge:
import fetch from 'node-fetch' import moment from 'moment' const bitcoinPrice = async () => { const res = await fetch("<https:>") const json = await res.json() const lastPrice = json.USD.last "" const [ints, decimals] = lastPrice.split(".") return ints.slice(0, -3) "," ints.slice(-3) "." decimals } export default async (req, res) => { const btc = await bitcoinPrice() res.json({ icon: 'bitcoin', subject: `Bitcoin Price USD (${moment().format('h:mma')})`, color: 'blue', status: `\\$${btc}` }) }</https:>
You might notice that the badge takes some time to refresh the next time you load up the README file over at GitHub. That’s is because GitHub uses a proxy mechanism to serve badge images.
GitHub serves the badge images this way to prevent abuse, like high request volume or JavaScript code injection. We can’t control GitHub’s proxy, but fortunately, it doesn’t cache too aggressively (or else that would kind of defeat the purpose of badges). In my experience, the TTL is around 5-10 minutes.
OK, final boss time.
Custom SVG badges with Napkin
For our final trick, let’s use Napkin to send back a completely new SVG, so we can use custom images like we saw on the Next.js repo.
A common use case for GitHub badges is showing the current status for a website. Let’s do that. Here are the two states our badge will support:
Badgen doesn’t support custom SVGs, so instead, we’ll have our badge talk directly to our Napkin endpoint. Let’s create a new Napkin function for this called site-status-badge.
The code in this function makes a request to example.com. If the request status is 200, it returns the green badge as an SVG file; otherwise, it returns the red badge. You can check out the function, but I’ll also include the code here for reference:
import fetch from 'node-fetch' const site_url = "<https:>" // full SVGs at <https:> const customUpBadge = '' const customDownBadge = '' const isSiteUp = async () => { const res = await fetch(site_url) return res.ok } export default async (req, res) => { const forceFail = req.path?.endsWith('/400') const healthy = await isSiteUp() res.set('content-type', 'image/svg xml') if (healthy && !forceFail) { res.send(Buffer.from(customUpBadge).toString('base64')) } else { res.send(Buffer.from(customDownBadge).toString('base64')) } }</https:></https:>
Odds are pretty low that the example.com site will ever go down, so I added the forceFail case to simulate that scenario. Now we can add a /400 after the Napkin endpoint URL to try it:
!\[status up\](https://napkin-examples.npkn.net/site-status-badge/) !\[status down\](https://napkin-examples.npkn.net/site-status-badge/400)View Status Up Badge View Status Down Badge
Very nice ?
And there we have it! Your GitHub badge training is complete. But the journey is far from over. There’s a million different things where badges like this are super helpful. Have fun experimenting and go make that README sparkle! ✨
The above is the detailed content of Adding Custom GitHub Badges to Your Repo. For more information, please follow other related articles on the PHP Chinese website!

What it looks like to troubleshoot one of those impossible issues that turns out to be something totally else you never thought of.

@keyframesandCSSTransitionsdifferincomplexity:@keyframesallowsfordetailedanimationsequences,whileCSSTransitionshandlesimplestatechanges.UseCSSTransitionsforhovereffectslikebuttoncolorchanges,and@keyframesforintricateanimationslikerotatingspinners.

I know, I know: there are a ton of content management system options available, and while I've tested several, none have really been the one, y'know? Weird pricing models, difficult customization, some even end up becoming a whole &

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
