Audits & updates

npm audit

Maintaining the health of a Node.js project involves monitoring for security vulnerabilities and keeping your dependencies organized. npm audit is the primary tool for this task.

1. What is npm audit?


When you install a package, you aren't just installing that one piece of code; you are installing its "dependency tree" (the packages that the package relies on). npm audit checks this entire tree against the GitHub Advisory Database to find known security vulnerabilities.

  • How to run: Type npm audit in your terminal.

  • The Report: It provides a list of vulnerabilities categorized by severity: Low, Moderate, High, or Critical.

  • The Fix: If fixes are available, it will suggest running npm audit fix.



2. Fixing Vulnerabilities


There are two levels of fixing:

  • npm audit fix: Automatically updates compatible packages to a version that contains a security patch. It only performs "non-breaking" updates (Patch or Minor versions).

  • npm audit fix --force: This will install the latest versions even if they are "Major" updates. Caution: This can break your code because major updates often change the API or functionality of a library.


3. Dependency Management Commands


Effective management goes beyond just installing. You need to know how to inspect and clean your environment.

Checking for Outdated Packages

Run npm outdated. This shows you:

  • Current: What version you have installed.

  • Wanted: The highest version allowed by your package.json semver (e.g., ^1.2.0).

  • Latest: The actual latest version available on npm.


Removing Packages

To uninstall a package and remove it from package.json:


npm uninstall <package-name>


Listing Dependencies

To see your dependency tree without opening node_modules:


npm list --depth=0


4. The npx Tool


npx (Node Package Execute) comes with npm and is used to run packages without permanently installing them.

  • Use Case: If you want to use a tool like create-react-app or sequelize-cli once, you don't need to bloat your project or global space.

  • Command: npx <package-name>

  • How it works: It checks if the package exists locally. If not, it downloads it to a temporary cache, runs it, and deletes it afterward.


5. Best Practices for Management


  • Audit on Every Install: Modern versions of npm run a "quick audit" every time you install a new package. Don't ignore the warnings.

  • Prune Regularly: Use npm prune to remove packages in your node_modules that are no longer listed in your package.json.

  • Check Licenses: For professional projects, ensure the third-party packages you use have licenses (like MIT or Apache) that allow for commercial use.