So far we've only consumed packages other people wrote. But the exact same registry is open to you too — if you write something reusable, you can publish it and let anyone in the world npm install it.
Step 1: Start the project
mkdir string-tidy
cd string-tidy
npm init
This time, skip the -y flag and actually answer the prompts — the name you pick has to be unique across the entire npm registry, so it's worth checking availability before you get attached to one:
npm search string-tidy
If nothing relevant comes back, the name is likely free.
Step 2: Write the package
Keep the first version simple. Create index.js:
function trimExtraSpaces(text) {
return text.trim().replace(/\s+/g, ' ');
}
function toTitleCase(text) {
return text
.toLowerCase()
.split(' ')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
module.exports = { trimExtraSpaces, toTitleCase };
This package cleans up messy strings — collapsing repeated whitespace and converting text to title case. Small, focused utilities like this are exactly the kind of thing that makes a good first package.
Step 3: Point package.json at the right entry file
Make sure package.json has:
"main": "index.js"
This tells npm (and anyone who installs your package) which file loads when someone writes require('string-tidy').
Step 4: Add a README
A README.md isn't optional in practice — it's the first (often only) thing people read before deciding whether to trust your package. Cover what it does, how to install it, and a quick usage example.
Step 5: Log in to npm
You'll need a free account on the npm registry. Once you have one:
npm login
This prompts for your username, password, and email, and stores an auth token locally.
Step 6: Publish
npm publish
If the name is available and everything's in order, your package is now live on the public registry — anyone, anywhere, can run npm install string-tidy and start using it.
Versioning — the rule that trips people up
npm refuses to publish the same version number twice. Every time you make changes and want to publish again, you must bump the version first:
npm version patch # 1.0.0 -> 1.0.1, small fixes
npm version minor # 1.0.0 -> 1.1.0, new backward-compatible features
npm version major # 1.0.0 -> 2.0.0, breaking changes
npm publish
These commands follow semantic versioning (semver): patch for bug fixes, minor for new features that don't break existing code, major for changes that do.
Depending on other packages inside your own
If your package needs another package to function, install it normally:
npm install lodash
It lands under dependencies in your package.json, and npm automatically installs it for anyone who installs your package too.
Taking a package down
npm unpublish string-tidy --force
npm only allows unpublishing within 72 hours of release, specifically to prevent people from yanking widely-depended-upon packages later and breaking other projects. After that window, you'd need to contact npm support directly.