Getting Started

To configure your npm registry and authenticate with GitHub Packages, you'll need a personal access token, NPM_TOKEN, which allows your project to securely download private packages stored on GitHub. In this setup, we’re fetching the token from Bitwarden, so make sure you’re logged in to the Bitwarden CLI by running bw login before proceeding.

Run the following commands to fetch the token, set it up in the current shell session, save it to your environment files, and ensure your npm configuration is ready for authenticated installs:

bash
# Fetch the NPM token from Bitwarden and store it in a variable
NPM_TOKEN=$(bw get item a110d781-ca58-474e-b78f-b21f00a8373e | jq -r '.login.password')

# Export NPM_TOKEN in the current shell session
export NPM_TOKEN

# Append NPM_TOKEN to .env.local if it’s not already present
grep -q '^NPM_TOKEN=' .env.local || echo "NPM_TOKEN=${NPM_TOKEN}" >> .env.local

# Ensure the registry and auth token lines are added to .npmrc
grep -q '^@anakin-gbit:registry=https://npm.pkg.github.com' .npmrc || echo "@anakin-gbit:registry=https://npm.pkg.github.com" >> .npmrc
grep -q '^//npm.pkg.github.com/:_authToken=\${NPM_TOKEN}' .npmrc || echo "//npm.pkg.github.com/:_authToken=\${NPM_TOKEN}" >> .npmrc

Here’s a breakdown of each step:

Exporting NPM_TOKEN in the current session:
Exporting NPM_TOKEN temporarily sets it as an environment variable for the active terminal session. This is necessary because npm commands run in this session need access to the token for private package downloads.
Adding the token to .npmrc:
The .npmrc file contains npm configuration details. By adding the registry and token lines here, you tell npm to source packages with the @anakin-gbit scope from GitHub Packages instead of the default npm registry. The token is used to authenticate your request, ensuring that you have access to private packages from the GitHub repository.
This configuration is necessary because GitHub Packages requires authentication to access private packages. Once set up, npm will automatically authenticate and fetch these packages when you run commands like npm install.
Adding the token to Vercel's environment variables:
For builds and deployments on platforms like Vercel, settingNPM_TOKEN as an environment variable ensures your code has access to the token during build-time, enabling authenticated package installation in production environments.
Adding the token to local environment variables:
Adding NPM_TOKEN to .env.local isn’t strictly necessary for npm to function locally since npm reads the token directly from .npmrc in each session. However, storing it in .env.local maintains consistency with deployment platforms, such as Vercel, where environment variables are needed during build and deployment. This approach helps ensure that all required variables are documented and accessible consistently across different environments.