Why Use Dependencies
The benefits to these packages and package managers are readily apparent — speed up development time by bringing in code that is tested, mature, and usually configurable for a variety of situations. Some of the drawbacks are probably also quite clear to you: you do not have control of the upkeep and security of the code.
Keeping track of all of your dependencies manually would be more than a full time job. Have you looked at the size of your node_modules folder in any medium-to-large projects lately? My guess is that all of your dependencies have their own dependencies and this folder has ballooned a little bit out of control. So what is the solution? Do we have to write every line of code we use ourselves? How do we keep track of potential issues in seemingly endless chain of code dependencies what we’ve entangled ourselves in?
Thankfully, npm (Node Package Manager — the tool that most of us use to pull in our dependencies) has developed a tool to check for known security flaws and correct them:
npm audit. Here’s how it works:
We’ll start with testing that we’re on the latest version of npm. Test your current version with
npm -v. The audit command requires npm version 6 and above, so if your version is not quite up to date, you can update with the command:
npm install -g npm@latest
Once you’re up to date, we can jump right in and run:
Test Repo and Demo
To test this out, I’ve created a small repo with one dependency that has vulnerabilities. (The package in question is lodash, but I’m not picking on them; this is an older version of their package, and the current version is free of known vulnerabilities.) If you would like to follow along, just clone this repo and follow these steps: First we’ll navigate to the directory and build our dependencies.
cd npm-audit-test npm install
This will install your node_modules packages and alert you to security vulnerabilities. In our case, we get this message:
found 2 high severity vulnerabilities run `npm audit fix` to fix them, or `npm audit` for details
First we’ll run
npm audit to see the details of the issues. This will show you a table with the each vulnerable package name, type of vulnernability, and the level of severity.
At the top of each table, NPM suggests a command that will resolve the security issue in question. You can either run each of these commands manually yourself, or run the command
npm audit fix to let npm run all of the suggested updates for you.