Chris Midgley
Chris Midgley

Reputation: 1651

How do I publish a package to npm using an API key?

NPM gives the ability to create access tokens with the right to publish packages to the NPM registry, assuming that you've set the package settings to "Require two-factor authentication or automation tokens" in "Publishing access" (and so implicitly it requires 2FA to be enabled, I assume).

How do I use this token to publish? I've checked the output of npm publish -- it asks for an OTP code, either as a prompt or a flag, and before I enabled 2FA it asked me for my password again. Using a fixed token would be easier than having to pull up my authenticator app. I could disable 2FA, but getting the token working is preferable.

Upvotes: 14

Views: 18018

Answers (2)

697
697

Reputation: 621

For verdaccio or similar you can use this:

> npm config set registry http://verdaccio/npm/

# then create and update local .npmrc file:
> npm config set _authToken=%YOUR_ACCES_TOKEN%

# and publish pointing to your registry
> npm publish --registry http://verdaccio/npm/

For proget:

[~]$ npm config set registry http://proget/npm/private-npm

[~]$ npm config set always-auth true
[~]$ npm config set _auth {ENCODEDAPIKEY}
[~]$ npm config set email {email address}

# then as usual
[~]$npm publish --registry {YOUR_REGISTRY}

Instructions are here proget and here verdaccio

Upvotes: 4

Nathan
Nathan

Reputation: 575

The npm registry has 3 different kinds of token: Read-only, Automation, and Publish.

It sounds like you created a Publish token. You need to create an Automation token instead, since this is the only one that bypasses 2FA.

Upvotes: 5

Related Questions