← Articles 2300

How to Commit Files to GitHub Using API in Node.js

By Vinay Saurabh • Published on

A minimal Node.js function to push or update files in a GitHub repository using GitHub REST API. Cloud-ready and dependency-light.

How to Commit Files to GitHub Using API in Node.js

Introduction to GitHub API for File Management

Learn how to programmatically commit files to a GitHub repo using the GitHub REST API and Node.js.


The GitHub API provides a powerful way to interact with repositories without using Git commands. In this guide, we’ll walk through how to commit new or updated files to a GitHub repo at a specific path using a cloud-ready Node.js function.


Why Use GitHub API for Commits?

Perfect for automation, CI/CD pipelines, content syncing, or publishing systems.



Required Inputs and Setup

Before making API calls, you’ll need to gather a few details.



Node.js Cloud Function to Create or Update GitHub File

A lightweight and efficient way to commit content using just one HTTP call.


const fetch = require("node-fetch");
const { Buffer } = require("buffer");

async function createOrUpdateGitHubFile(repo, branch, filePath, content, headers, message) {
    const apiURL = `https://api.github.com/repos/${repo}/contents/${filePath}`;

    // Check if file exists to get SHA
    const res = await fetch(apiURL, { headers });
    const fileExists = res.status === 200;
    const sha = fileExists ? (await res.json()).sha : undefined;

    const payload = {
        message,
        content: Buffer.from(content).toString("base64"),
        branch,
        ...(sha && { sha })
    };

    const response = await fetch(apiURL, {
        method: "PUT",
        headers: {
            ...headers,
            "Content-Type": "application/json"
        },
        body: JSON.stringify(payload)
    });

    if (!response.ok) {
        const err = await response.text();
        throw new Error(`GitHub API error: ${err}`);
    }
}

How It Works

The function checks for file existence and commits accordingly.


  1. Build the GitHub API URL using repo and file path
  2. Make a GET request to check if the file already exists
  3. If it exists, extract the sha for updating
  4. Prepare the PUT payload with base64 content and commit message
  5. Send the PUT request to create/update the file

Real-world Use Case: Publishing Articles via Git

This method is perfect for auto-publishing blog posts or documentation.


For example, in a Firebase Cloud Function, you could receive an article's title, content, and slug, and use this code to push it as a markdown file into your GitHub-powered blog repo (like Jekyll, Hugo, or Docusaurus).


Common Errors and Debugging Tips

What to do when things go wrong.



Final Thoughts

A minimal, powerful way to program Git commits.


With just a few lines of code and the GitHub REST API, you can create fully automated file commits from any cloud environment.
It's fast, clean, and CI/CD friendly—no Git binary required.