Display Hashnode Statistics As Shields.io Badges Using GitHub Actions

by Admin 70 views

Introduction

In the dynamic landscape of content creation and online presence, displaying your statistics can significantly enhance your credibility and engagement. For developers and writers using Hashnode as their blogging platform, showcasing their blog's statistics—such as total views, number of posts, and followers—can be a compelling way to attract readers and collaborators. However, manually updating these statistics can be time-consuming and prone to errors. This is where automation comes into play. GitHub Actions, a powerful automation tool, allows you to automate tasks directly within your GitHub repository. By integrating GitHub Actions with Shields.io, a service for generating concise, consistent, and legible badges in SVG and raster format, you can automatically display your Hashnode statistics as badges in your repository's README or website. This article delves into how you can leverage GitHub Actions to seamlessly display your Hashnode statistics as Shields.io badges, ensuring your audience always has access to your latest performance metrics.

The primary advantage of using GitHub Actions in this context is automation. Instead of manually updating your statistics, a workflow can be set up to run at scheduled intervals or triggered by specific events, such as a new post being published on your Hashnode blog. This ensures that the badges displayed are always up-to-date, providing an accurate representation of your blog's performance. Furthermore, integrating with Shields.io allows you to present these statistics in a visually appealing and consistent manner. Shields.io offers a wide range of customization options, allowing you to tailor the badges to match your brand's aesthetics. This not only enhances the visual appeal of your repository but also makes it easier for visitors to quickly grasp the key statistics of your blog.

This article will guide you through the process of setting up a GitHub Actions workflow to fetch your Hashnode statistics and generate Shields.io badges. We will cover everything from obtaining the necessary API keys to configuring the workflow file and deploying the badges. By the end of this guide, you will have a fully automated system that keeps your Hashnode statistics prominently displayed, enhancing your online presence and credibility. Whether you are a seasoned developer or new to the world of automation, this article will provide you with the knowledge and tools needed to effectively showcase your Hashnode statistics.

Prerequisites

Before diving into the implementation, it's crucial to have the necessary prerequisites in place. This ensures a smooth and efficient setup process. The prerequisites include a Hashnode blog, a GitHub repository, and a basic understanding of GitHub Actions. Let's explore each of these in detail:

  1. Hashnode Blog:

    • You must have an active Hashnode blog to retrieve statistics from. If you don't have one, you can easily create one on the Hashnode platform (https://hashnode.com/). A Hashnode blog serves as the source of the statistics that will be displayed as badges. Ensure that your blog is set up and contains some content, as this will provide a baseline for the statistics to be fetched and displayed. The more content you have, the more meaningful the displayed statistics will be.
  2. GitHub Repository:

    • A GitHub repository is required to host the GitHub Actions workflow and store the generated badge files. If you don't have one, create a new repository on GitHub. This repository will be the central hub for your automation process. It's recommended to have a README.md file in your repository, as this is where you will typically embed the generated badges. Make sure your repository is properly initialized and connected to your local environment if you plan to make changes locally.
  3. Basic Understanding of GitHub Actions:

    • Familiarity with GitHub Actions is essential. GitHub Actions is a continuous integration and continuous delivery (CI/CD) platform that allows you to automate your software development workflows directly in your GitHub repository. If you're new to GitHub Actions, it's recommended to go through the official documentation (https://docs.github.com/en/actions) to understand the core concepts, such as workflows, jobs, and steps. Understanding how to create and configure workflow files (.yml files) is crucial for setting up the automation process. Additionally, knowledge of GitHub Secrets, which are used to store sensitive information like API keys, is also important.

Having these prerequisites in place will set the stage for a seamless integration of GitHub Actions and Shields.io to display your Hashnode statistics. With your Hashnode blog active, your GitHub repository ready, and a basic understanding of GitHub Actions, you'll be well-equipped to follow the steps outlined in the following sections to automate the display of your blog statistics.

Obtaining a Hashnode API Key

To access your Hashnode statistics programmatically, you need to obtain an API key. Hashnode provides a GraphQL API that allows you to retrieve data about your blog, including the number of posts, views, and followers. To use this API, you need to authenticate your requests using an API key. Here's a step-by-step guide on how to obtain your Hashnode API key:

  1. Log in to your Hashnode Account:

    • Go to the Hashnode website (https://hashnode.com/) and log in to your account. Make sure you are logged in with the account associated with the blog for which you want to retrieve statistics.
  2. Navigate to your Blog Dashboard:

    • Once logged in, navigate to your blog's dashboard. You can usually find this by clicking on your profile picture or blog name in the top navigation bar and selecting "Dashboard" or a similar option. The dashboard is the central hub for managing your blog and accessing various settings.
  3. Access the API Settings:

    • In your blog dashboard, look for a section related to "Settings," "Integrations," or "API." The exact location may vary slightly depending on updates to the Hashnode platform, but it is typically found in the settings or preferences section of your dashboard.
  4. Generate a New API Key:

    • Within the API settings, you should find an option to generate a new API key. This might be labeled as "Generate API Key," "Create New Key," or something similar. Click on this option to initiate the key generation process.
  5. Copy and Securely Store the API Key:

    • Once the API key is generated, it will be displayed on the screen. Make sure to copy this key and store it securely. This key is sensitive information, and you should treat it like a password. Do not share it publicly or commit it to your repository directly. Instead, you will store it as a GitHub Secret, as described in the next section. Losing control of your API key could allow unauthorized access to your blog's data, so it's crucial to keep it safe.

With your Hashnode API key obtained, you are now ready to proceed with setting up your GitHub Actions workflow. The API key will be used in the workflow to authenticate your requests to the Hashnode GraphQL API, allowing you to retrieve your blog statistics. Remember to handle your API key with care and follow best practices for storing sensitive information.

Setting Up GitHub Secrets

After obtaining your Hashnode API key, the next crucial step is to securely store it in your GitHub repository as a secret. GitHub Secrets allow you to store sensitive information, such as API keys and passwords, securely within your repository. These secrets are then accessible to your GitHub Actions workflows without exposing them in your codebase. Here's how to set up GitHub Secrets for your Hashnode API key:

  1. Navigate to Your GitHub Repository:

    • Go to your GitHub repository where you plan to set up the GitHub Actions workflow. This is the repository you created or identified in the prerequisites section.
  2. Access the Repository Settings:

    • In your repository, click on the "Settings" tab. This tab is usually located towards the right side of the navigation bar, alongside options like "Code," "Issues," and "Pull requests."
  3. Go to the Secrets Section:

    • In the settings sidebar, find and click on the "Secrets" option. This will take you to the secrets management page for your repository. GitHub Secrets are organized under the "Security" section in the settings.
  4. Add a New Secret:

    • On the secrets page, click on the "New repository secret" button. This button will open a form where you can define the name and value of your secret.
  5. Define the Secret Name and Value:

    • In the "Name" field, enter a descriptive name for your secret. A common convention is to use a name that clearly indicates the purpose of the secret. For your Hashnode API key, you might use a name like HASHNODE_API_KEY.
    • In the "Value" field, paste the Hashnode API key you obtained in the previous section. Ensure you paste the correct key to avoid any issues with authentication in your workflow.
  6. Add the Secret:

    • After entering the name and value, click on the "Add secret" button. This will save the secret in your repository. The value of the secret will be encrypted and stored securely by GitHub.

Once you've added the secret, it will be available for use in your GitHub Actions workflows. To access the secret in your workflow file, you can use the following syntax:

${{ secrets.HASHNODE_API_KEY }}

Replace HASHNODE_API_KEY with the name you gave your secret. When the workflow runs, GitHub Actions will automatically replace this placeholder with the actual value of the secret, without exposing the value in the logs or the workflow file itself. This ensures that your sensitive information remains protected.

By setting up GitHub Secrets, you can securely manage your Hashnode API key and other sensitive credentials required by your workflows. This practice is crucial for maintaining the security of your repository and your Hashnode blog. With the API key securely stored, you are now ready to create the GitHub Actions workflow file that will fetch your Hashnode statistics and generate the Shields.io badges.

Creating the GitHub Actions Workflow File

With the Hashnode API key securely stored as a GitHub Secret, the next step is to create the GitHub Actions workflow file. This file defines the automated process that will fetch your Hashnode statistics, generate Shields.io badges, and update your repository. The workflow file is a YAML file that resides in the .github/workflows directory of your repository. Here's a detailed guide on how to create and configure your workflow file:

  1. Create the Workflow File Directory:

    • If it doesn't already exist, create a directory named .github/workflows in the root of your repository. This directory is where GitHub Actions looks for workflow files.
  2. Create a New Workflow File:

    • Inside the .github/workflows directory, create a new YAML file. You can name it something descriptive, such as hashnode-stats.yml. The .yml extension is essential for GitHub Actions to recognize the file as a workflow definition.
  3. Define the Workflow Structure:

    • Open the newly created YAML file in a text editor or your preferred IDE. Start by defining the basic structure of the workflow. This includes the workflow name, the trigger events, and the jobs that the workflow will execute.
    name: Hashnode Stats Badges
    
    on:
      schedule:
        - cron: '0 * * * *' # Runs every hour
      workflow_dispatch:
    
    jobs:
      generate-badges:
        runs-on: ubuntu-latest
        steps:
          - name: Checkout code
            uses: actions/checkout@v3
    
          # Add steps here to fetch Hashnode stats and generate badges
    
    • name: This is the name of your workflow, which will be displayed in the GitHub Actions UI.
    • on: This section defines the events that trigger the workflow. In this example, the workflow is triggered by a schedule (cron job) and manually via workflow_dispatch.
      • schedule: This allows you to schedule the workflow to run at specific intervals. The cron expression '0 * * * *' means the workflow will run at the top of every hour.
      • workflow_dispatch: This allows you to manually trigger the workflow from the GitHub Actions UI.
    • jobs: This section defines the jobs that will be executed by the workflow. Each job runs in its own virtual environment.
      • generate-badges: This is the name of the job. You can choose any descriptive name.
      • runs-on: This specifies the type of virtual machine to use for the job. ubuntu-latest is a common choice.
      • steps: This is a list of steps that will be executed in the job.
        • name: This is the name of the step, which will be displayed in the workflow logs.
        • uses: This specifies an action to use. actions/checkout@v3 is a standard action that checks out your repository's code into the virtual environment.
  4. Add Steps to Fetch Hashnode Statistics and Generate Badges:

    • Now, you need to add the steps that will fetch your Hashnode statistics using the API key and generate the Shields.io badges. This typically involves using a scripting language like Node.js or Python to make API requests and generate the badge URLs. Here's an example using Node.js:
    name: Hashnode Stats Badges
    
    on:
      schedule:
        - cron: '0 * * * *'
      workflow_dispatch:
    
    jobs:
      generate-badges:
        runs-on: ubuntu-latest
        steps:
          - name: Checkout code
            uses: actions/checkout@v3
    
          - name: Set up Node.js
            uses: actions/setup-node@v3
            with:
              node-version: '16'
    
          - name: Install dependencies
            run: npm install axios
    
          - name: Fetch Hashnode stats and generate badges
            env:
              HASHNODE_API_KEY: ${{ secrets.HASHNODE_API_KEY }}
            run: |
              node <<EOF
              const axios = require('axios');
              const fs = require('fs');
              
              const apiKey = process.env.HASHNODE_API_KEY;
              const publicationId = 'YOUR_PUBLICATION_ID'; // Replace with your publication ID
              
              async function getHashnodeStats() {
                try {
                  const response = await axios({
                    url: 'https://api.hashnode.com',
                    method: 'POST',
                    headers: {
                      'Content-Type': 'application/json',
                      'Authorization': apiKey,
                    },
                    data: {
                      query: `
                        query {
                          publication(id: \"${publicationId}\") {
                            posts {
                              totalDocuments
                            }
                            followers {
                              totalDocuments
                            }
                          }
                        }
                      `,
                    },
                  });
              
                  const data = response.data.data.publication;
                  const totalPosts = data.posts.totalDocuments;
                  const totalFollowers = data.followers.totalDocuments;
              
                  const postsBadgeURL = `https://img.shields.io/badge/Posts-${totalPosts}-blue`;
                  const followersBadgeURL = `https://img.shields.io/badge/Followers-${totalFollowers}-green`;
              
                  fs.writeFileSync('posts-badge.svg', `<img src=\