How to Use GitHub Packages for a Private npm Registry

Spencer
Spencer
How to Use GitHub Packages for a Private npm Registry

Photo by Karolina Grabowska from Pexels.

I'm working on a TypeScript framework, and I wanted to publish the framework as a package that I could consume somewhere else ... but it's not ready for the world to see yet.

You can do this from a GitHub organization or from a free personal account.

So, here's how I used GitHub packages to create a private registry for my npm module.

Authenticate with GitHub

Every JS developer is familiar with the npm cli; not every JS knows that you can swap out the registry with a CLI flag or via .npmrc config.

First, we need to tell the npm CLI what authentication token to use.

You can follow GitHub's documentation, but here are the steps:

  1. Create a Personal Access Token in your developer settings.

Here are the permissions your token will need: Github Permissions

  1. Put it in your ~/.npmrc file
touch ~/.npmrc
echo "//npm.pkg.github.com/:_authToken=TOKEN_YOU_CREATED" >> ~/.npmrc
  1. Check your permissions
npm whoami --registry https://npm.pkg.github.com # echos out your GitHub username

Publish Your Package

You can follow Github's documentation, or the steps below.

  1. Tell the npm cli where to publish

Create a .npmrc with the following line next to your packages package.json:

// .npmrc
registry=https://npm.pkg.github.com/YOUR_GITHUB_USERNAME
  1. Align the name of the published package

Update the name of your package in package.json to reflect your username or organization name:

// package.json
{
  "name": "@YOUR_GH_USERNAME/PACKAGE_NAME",
  "version": "1.0.0"
}
  1. Update the registry field in package.json:
// package.json
{
  "name": "@YOUR_GH_USERNAME/PACKAGE_NAME",
  "version": "1.0.0",
  "repository": "git://github.com/YOUR_GH_USERNAME/PACKAGE_NAME.git"
}
  1. Publish!

Run npm publish and, if you've done it correctly, it will publish to your registry!

You can find your packages here: https://github.com/YOUR_GH_USERNAME?tab=packages

Install Your Package as a Dependency

Since you're already authenticated to the GitHub registry, you're ready to install your newly published package.

In the project that you want to install the package, add an .npmrc file next to your package.json:

@YOUR_GH_USERNAME:registry=https://npm.pkg.github.com/YOUR_GH_USERNAME

This tells npm to use the GitHub registry to install any packages published with @YOUR_GH_USERNAME. Otherwise, it'll use the npm registry like normal.

Then, you should be able to install the package from the cli:

npm i @YOUR_GH_USERNAME/PACKAGE_NAME

At this point, you should see the package show up your dependencies block of your package.json.

Success!