How to Use Private Git Repositories with NPM in package.json
Configure automatic authentication to private git repositories for npm and any other use of git on your local machine.
There are times when we need to install a package directly from a git repo. If you want to do this with a private git repo, it may look something like this in your package.json.
1
2
3
"devDependencies": {
"pro-thunderball-stat-monitor": "git+https://7cc40a9eea50c193fd7e0d2e39ce9@github.com/salbarley/pro-thunderbal-stat-monitor",
}
That package.json is probably going to end up in a repo of its own. But you don’t want to publish your Personal Access Token (PAT) in a repo. So lets configure your local machine to use a PAT whenever you pull a repo from GitHub or any other git implementation.
Generate a Personal Authentication Token (PAT)
Get yourself a Personal Authentication Token with read-only access. It will be added to a config on your local machine.
This section is specific to GitHub. If you are using a different implementation of git, find out how to get a PAT and continue on to the next section.
- On GitHub, go to your Settings page and navigate to Developer Settings.
- Select Personal access tokens.
- Select Fine-grained tokens.
- Use the Generate new token button.
- Give the token a name and description.
- Optional. If you want to access repos in an organization, change Resource owner to that organization.
- Set the Expiration to suit your needs.
- Under Repository access select All repositories.
- Select the Add permissions dropdown and check Contents.
- After confirming all settings, use the Generate token button.
- Follow any additional prompts. Important: Copy and paste your PAT to a file and save it on your local machine. It is only displayed one time.
You may have to wait for an admin to approve giving your PAT access to the organization.
Configure git to use the PAT
Configure your local machine to use the PAT with the following command. Replace <YOUR_TOKEN> with your token. Replace SomeOrg with your organization. You could also replace SomeOrg with your username so your token is only used when accessing your own private repos.
1
git config --global url."https://<YOUR_TOKEN>@github.com/SomeOrg".insteadOf "https://github.com/SomeOrg"
Now when you run npm install in the project your PAT will automatically be injected whenever there is a repo at https://github.com/SomeOrg. This will also work when using git from the command line or any other time git tries to pull a repo from https://github.com/SomeOrg.
