Overview
You may encounter an "Unable to authenticate" error when attempting to run `npm login`, even though you've successfully logged into your npm repo before with these credentials. For example:
$:> npm login
npm notice Log in on http://localhost:8081/repository/npm-hosted/
Username: admin
Password:
npm error code E401
npm error Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager"
npm error A complete log of this run can be found in: /.../.npm/_logs/2025-03-05T23_20_02_634Z-debug-0.log
The log mentioned above shows a 401 returned by the repo:
18 http fetch PUT 401 http://localhost:8081/repository/npm-hosted/-/user/org.couchdb.user:admin 6ms
19 verbose stack HttpErrorAuthUnknown: Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager"
19 verbose stack at /usr/local/lib/node_modules/npm/node_modules/npm-registry-fetch/lib/check-response.js:88:17
19 verbose stack at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
19 verbose stack at async putCouch (/usr/local/lib/node_modules/npm/node_modules/npm-profile/lib/index.js:133:18)
19 verbose stack at async loginCouch (/usr/local/lib/node_modules/npm/node_modules/npm-profile/lib/index.js:177:12)
19 verbose stack at async otplease (/usr/local/lib/node_modules/npm/lib/utils/auth.js:8:12)
19 verbose stack at async Object.login (/usr/local/lib/node_modules/npm/lib/utils/auth.js:91:11)
19 verbose stack at async Login.exec (/usr/local/lib/node_modules/npm/lib/commands/login.js:31:35)
19 verbose stack at async Npm.exec (/usr/local/lib/node_modules/npm/lib/npm.js:207:9)
19 verbose stack at async module.exports (/usr/local/lib/node_modules/npm/lib/cli/entry.js:74:5)
20 verbose statusCode 401
21 verbose pkgid org.couchdb.user:admin
22 error code E401
23 error Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager"
Workaround
The fix for this is fairly straightforward. Here are the steps:
1. Locate your .npmrc file. This would normally reside in your home directory.
2. Edit the file in a text editor and remove the preexisting token:
registry=http://localhost:8081/repository/npm-hosted/
email=admin@admin.io
always-auth=true
//localhost:8081/repository/npm-hosted/:_authToken=NpmToken.300e5536-1c81-35df-9563-fc1b56ead799
In the example above, it's the last line beginning with '//localhost:8081/...'
3. Save your changes, and run 'npm login' again to store a new token.