Become a design partnerApply now

← All posts

The Definitive Guide for Authenticating a GitHub App

Replay Team·
Story

Screen_Shot_2022-12-23_at_3.11.40_PM.png

Yesterday we published a post on how we debugged GitHub’s Auth flow in order to be able to programmatically manage PR Checks.

At a high level there were 7 steps:

  1. Create an App
  2. Create a private key
  3. Install the App
  4. Create a JWT with a reasonable expiration and app id
  5. Use the JWT and the installation id to create a token
  6. Use the token to create the Check Run
  7. profit

And there was some really crazy stuff in there. First signing a JWT is no joke and then fetching an access_token for the installation is not simple either. And this approach came straight from GitHub’s docs.

So, after meeting with Gregor who built a big chunk of the octokit SDK, I learned there’s a much simpler way to do it.

The simpler way boils down to four steps

  1. Create an @octokit/app App
  2. Fetch the installation id for the repo you want to talk to
  3. Create an octokit instance for the given installation
  4. profit
const { App } = require("@octokit/app");
const dotenv = require("dotenv");

dotenv.config({ path: "./.env.local" });

(async () => {
  const appId = 274973;
  const owner = "replayio";
  const repo = "devtools";

  const app = new App({ appId, privateKey: process.env.PEM });

  // First we need to get the installation id for the repo
  const { data: installation } = await app.octokit.request(
    `GET /repos/${owner}/${repo}/installation`
  );

  // Then we can get an octokit instance for the installation
  const octokit = await app.getInstallationOctokit(installation.id);

  // Then we go nuts
  const { data: issues } = await octokit.request(
    `GET /repos/${owner}/${repo}/issues`
  );

  console.log(issues);
})();

Loom Walk Through

video