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:
# 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}" >> .npmrcHere’s a breakdown of each step:
NPM_TOKEN in the current session: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..npmrc:.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.npm install.NPM_TOKEN as an environment variable ensures your code has access to the token during build-time, enabling authenticated package installation in production environments.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.