Octokit From Auth

0.3.2 · active · verified Wed Apr 22

octokit-from-auth simplifies the instantiation of a GitHub Octokit client, abstracting away the complexities of authentication token resolution. It automatically attempts to retrieve a token from `process.env.GH_TOKEN` or by executing `gh auth token` via the `get-github-auth-token` package. The library offers two functions: `octokitFromAuth`, which rejects if no token is found, and `octokitFromAuthSafe`, which resolves to an unauthenticated Octokit instance if no token is available. The current stable version is 0.3.2. Releases are consistent, primarily for dependency updates and minor fixes, with new features introduced in minor versions. It ships with TypeScript types and requires Node.js >=18.3.0. This package differentiates itself by offering a robust, opinionated, and flexible approach to Octokit instantiation and authentication, minimizing boilerplate for interacting with the GitHub API.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating both authenticated and unauthenticated Octokit instances using `octokitFromAuth` and `octokitFromAuthSafe`, handling potential authentication failures gracefully.

import { octokitFromAuth, octokitFromAuthSafe } from 'octokit-from-auth';

async function run() {
  // Attempt to create an authenticated Octokit instance.
  // It will use process.env.GH_TOKEN or `gh auth token` if available.
  // This function will throw an error if no auth token is found.
  try {
    const authenticatedOctokit = await octokitFromAuth();
    const { data: user } = await authenticatedOctokit.request('GET /user');
    console.log(`Authenticated as ${user.login}.`);
  } catch (error) {
    console.warn(`Could not create authenticated Octokit: ${error.message}`);
    console.warn('Falling back to safe, unauthenticated Octokit...');

    // Create an Octokit instance that is unauthenticated if no token is found.
    const unauthenticatedOctokit = await octokitFromAuthSafe();
    const { data: publicUser } = await unauthenticatedOctokit.request('GET /users/{username}', {
      username: 'octokit',
    });
    console.log(`Accessed public user ${publicUser.login} without authentication.`);
  }
}

run();

view raw JSON →