How to Publish NPM Package in Year 2025

背景
本文解决 npm error 403 403 Forbidden - PUT registry.npmjs.org/swaggered - Two-factor authentication or granular access token with bypass 2fa enabled is required to publish packages.
看到 www.npmjs.com/ 上这个公告很久了,
!CAUTION\] **Security Update**: Classic tokens have been revoked. Granular tokens are now limited to 90 days and require 2FA by default. Update your CI/CD workflows to avoid disruption. Learn more.
但是一直还能在本地发包,故没有在意,今天突然发现发布包报错:
> npm run pub:patch
ts
npm error code E403
npm error 403 403 Forbidden - PUT https://registry.npmjs.org/swaggered - Two-factor authentication or granular access token with bypass 2fa enabled is required to publish packages.
npm error 403 In most cases, you or one of your dependencies are requesting
npm error 403 a package version that is forbidden by your security policy, or
npm error 403 on a server you do not have access to.
看看重点:
npm error 403 403 Forbidden - PUT registry.npmjs.org/swaggered - Two-factor authentication or granular access token with bypass 2fa enabled is required to publish packages.
如何解决?我们是自己人不能说每次自己发布都需要 Two-factor authentication,故我们选择生成一个 access token with bypass 2fa enabled,即生成一个可以绕过 2FA 的 Access Token。
第一步:生成【绕过 2FA】的 Access Token
使用 npm token create 会报错
npm error 400 Bad Request - POST registry.npmjs.org/-/npm/v1/to... - Token name is required
我们需要通过网站生成。 进入 npmjs.com/settings/~/...
不会的可以看看 docs.npmjs.com/creating-an...
注意勾选"Bypass two-factor authentication"!
然后得到一个 access token,复制。
这是本地可以通过 ❯ npm token list 查看刚刚新增的环境变量:
Token npm_E...c... with id d***0 created 2025-12-11
第二步:设置【绕过 2FA】的 Access Token
设置 .npmrc
项目根目录 .npmrc
sh
# for publish
//registry.npmjs.org/:_authToken=${NPM_TOKEN}
registry=https://registry.npmjs.org
# for npm install
# registry=https://registry.npmmirror.com
//registry.npmjs.org/:_authToken=${NPM_TOKEN} 是新增的。等会会用到我们刚刚复制的环境变量。
设置环境变量【NPM_TOKEN】
我试过设置到 .env 不生效(好处是能按照项目设置不同的 NPM_TOKEN)。故需要设置到 bash profile:
~/.zshrc:
sh
export NPM_TOKEN=npm_Exxxxxxxxxxxxxxxxxxxc # 大家使用自己刚刚复制的
新增环境变量了需要重启终端,直到看到 echo $NPM_TOKEN 有值。
!CAUTION\] 注意 💥:`NPM_TOKEN` 不要提交到任何代码仓库!
OK 现在执行 npm run pub:patch,可以正常发布了 🎉!
diff
npm notice name: swaggered
npm notice version: 2.6.13
npm notice filename: swaggered-2.6.13.tgz
npm notice package size: 23.7 kB
npm notice unpacked size: 78.5 kB
npm notice shasum: d5a70d3e88888888885e348c8baf8e
npm notice integrity: sha512-8888888[...]8888888==
npm notice total files: 21
npm notice
npm notice Publishing to https://registry.npmjs.org with tag latest and default access
+ swaggered@2.6.13
FAQ
如果还不行 ❯ npm login 即清空之前的 session 重新登录,还是不行 ❯ npm install -g npm@latest。
参考
原文:2025-12-11 之后前端 npm 如何发包 How to Publish NPM Package in Year 2025