npm publish error


Recently I tried to publish an npm package, but I received the error:

npm ERR! publish Failed PUT 403
npm ERR! code E403
npm ERR! Package name too similar to existing packages

The name was available on npm package name checker so why did this fail?

After some research, I learned that new package moniker rules were added to prevent typosquatting on the npm registry.

This made sense from a security point of view so I reassessed my publish process.

Process

While working on a package, use a placeholder name that’s unique and greppable:

{
  "name": "placeholder"
}

When it’s ready to be published, create a test directory:

mkdir test && cd test

Initialize package.json in the test directory:

npm init -y

Remove all fields except for name and version:

{
  "name": "test",
  "version": "0.0.0"
}

Then follow the steps outlined below.

Steps

1. Change the name to what you want the package to be called (e.g., my-package):

sed -i '' 's/test/my-package/' package.json

Learn more about sed.

2. Try publishing the package:

npm publish
  • If it succeeds, you’re now the owner of the name and proceed to step 3.
  • If it fails, repeat steps 1-2 until it succeeds.

3. Return to your package:

cd .. && rm -rf test

4. Replace your package name with the published one:

git grep -l 'placeholder' | xargs sed -i '' -e 's/placeholder/my-package/g'

Learn more about git grep replace.

5. Commit the change:

git commit

6. Bump the package version:

npm version

7. Publish:

npm publish

Success!



Please support this site and join our Discord!