A Developer’s Tutorial to Using NPM Audit for Dependency Scanning

By Eyal Katz August 8, 2024

Many developers overlook the risks lurking in third-party packages. Every package you add could harbor vulnerabilities, potentially exposing sensitive user data and granting unauthorized access to your systems. It can lead to severe consequences, including data breaches, system compromises, reputation damage, and disruption of your services.

With 80% of projects using at least one vulnerable package – it’s a crucial issue. This guide on using npm audit will show you how to identify and fix these security risks before they become a problem. We’ll walk you through the steps to protect your application and keep sensitive data safe. 

What is an npm audit?

NPM audit is a powerful command-line utility included with Node Package Manager (npm) that scans your project’s dependencies for known security vulnerabilities. It contributes to effective data governance by ensuring the integrity and security of the software supply chain.

When you run the npm audit, it examines your package-lock.json file, cross-referencing your dependencies against a vast database of vulnerabilities maintained by the Node Security Working Group. This database, which includes thousands of documented vulnerabilities from sources like the National Vulnerability Database (NVD) and other security advisories, is continuously updated to reflect the latest threats. These threats can include excessive resource usage, leading to unexpected costs in cloud environments like AWS Lambda.

package-lock.json file

The tool then generates a detailed report categorizing vulnerabilities with low, moderate, high, or critical severity levels. This report identifies specific security issues and provides actionable steps to address them, such as updating or patching the affected packages. In short, an NPM audit acts like a security analyst, always looking to guarantee that your code remains protected and robust, similar to how tools like Git Secrets can help protect sensitive information within your code repositories.

Why Use npm audit?

Using npm audit is a no-brainer for keeping your Node.js applications secure and trustworthy. It allows you to proactively identify and address vulnerabilities within your dependencies, aiding in your overall cybersecurity risk assessment.

Vulnerabilities in third-party packages can expose sensitive user data. For instance, a known exploit in a dependency could allow attackers to gain unauthorized access to your database, leading to leaks of personal information, financial records, or other critical data. These vulnerabilities can lead to system failures and data breaches, making tracking and addressing them crucial to minimize the change failure rate.

They can also be a gateway for attackers to execute malicious code and gain control over your server environment, compromising the integrity of your entire system. Implementing a Zero Trust architecture can mitigate these risks by assuming that no user or device is inherently trustworthy, regardless of location or network.

Your organization’s reputation is on the line too. Once news of compromised systems or leaked data gets out, it spreads like wildfire, eroding user trust and potentially driving customers away.

Costs of a data breach

By incorporating npm audit into your development routine, you can stay ahead of new and existing dependency threats, helping to prevent attacks like those associated with the Black Basta ransomware. It seamlessly fits into your existing npm workflow, providing a user-friendly and essential tool for any developer committed to building and maintaining secure software.

How to Use npm Audit

Follow these three simple steps to perform an audit of your project’s dependencies:

  1. Open your terminal or command prompt.
  2. Use the cd command to jump to your project’s root directory. It is where your package.json and package-lock.json files live. For example, if your project is in a folder called “my-project,” you would enter:
<em>cd path/to/my-project</em>
  1. Once you’re in the root directory, run the command:
<em>npm audit</em>

This command will scan your project’s dependencies listed in the package-lock.json file against a database of known vulnerabilities. After a few moments, npm will generate an audit report.

Customizing the Audit

To get the most out of the npm audit, you can tweak its behavior using various flags:

–json – If you want a more machine-friendly output, use this flag to get the audit results in JSON format. It is helpful for further processing or integrating with other tools:

<em>npm audit --json</em>

–audit-level – Use this flag to set the minimum severity level of vulnerabilities to report. For example, to only show vulnerabilities that are moderate or higher, use:

<em>npm audit --audit-level=moderate</em>

–production – If your primary concern is the security of what affects your end-users, use this flag to audit only production dependencies and skip the development dependencies:

<em>npm audit --production</em>

Interpreting the Audit Report

The audit report provides a list of vulnerabilities. Each entry includes a severity level, a list of the affected packages, and recommended remediation steps.

npm audit report example

Low, moderate, high, or critical severity indicates how urgently you should address each issue. Low-severity issues are usually minor and informational, while someone could exploit moderate issues under certain conditions. High-severity vulnerabilities pose significant risks, and you should prioritize them. Critical issues can lead to severe security breaches and require immediate attention, making automation in DevOps essential for quick remediation.

The report lists each vulnerable dependency, specifying the affected versions and paths, and recommends actions such as updating to a secure version, conducting a manual review, or applying a patch if an update isn’t feasible.

Fixing Vulnerabilities with npm audit fix

The npm audit fix command automates resolving vulnerabilities by attempting to update all affected packages to secure versions. However, it does not always address all vulnerabilities.

You can forcefully install updates with npm audit fix –force, which might cause breaking changes. Manual intervention may be needed, especially if no compatible secure versions are available. 

npm audit fix

After running the npm audit fix command, thoroughly test your application to ensure that updates have not introduced any new issues or broken functionality.

Integrating npm audit into Your Workflow

By embedding npm audit into your workflow, you achieve early detection and remediation of security issues, reducing the risk of breaches and strengthening your project’s security posture by implementing effective information security controls. Practical strategies to integrate npm audit into your development workflow include:

  • Regular Automated Audits – Embed npm audit into your CI/CD pipeline. Use a script to run an npm audit on every build or before deployments. For instance, add it to your CI configuration file to catch vulnerabilities early and prevent insecure code from reaching production.
  • Setup Automated Alerts –  Leverage tools that integrate with npm audit to send you real-time notifications whenever it discovers new vulnerabilities. Stay updated and act quickly instead of discovering issues after deployment.
  • Fail Builds on Vulnerabilities—Tools like audit-ci can automate this process. They run an npm audit and break the build if they find any critical issues. It enforces a culture of security where you address vulnerabilities immediately.
audit-ci tool

Advanced npm audit Techniques

You can also take advantage of several advanced npm audit techniques. These methods go beyond basic vulnerability scanning and contribute to a more robust application environment.

Verify Package Integrity with Signatures:

Use npm audit signatures to check that your packages haven’t been tampered with. Verifying cryptographic signatures adds an extra layer of security.

Create Custom Audit Policies:

Customize your security checks by setting specific audit policies. For example, you can create a policy to ignore vulnerabilities that only affect optional dependencies, focusing on issues that impact critical paths.

npm config set audit-level=ignore-optional

Custom policies will be applied each time you run an npm audit.

Integrate with Other Security Tools:

Integrating npm audit with tools like GitHub Dependabot expands its functionality. These integrations offer continuous monitoring and automatic fixes for new vulnerabilities.

Lock Down Your Supply Chain with npm audit 

Keeping your Node.js project secure is more critical than ever, and dependency scanning with npm audit is a vital part of that process. By making npm audit a regular part of your development workflow, you can uncover and fix vulnerabilities in your project’s dependencies as they arise. 

For those looking to go beyond what npm audit offers, start with Spectral. With advanced features like real-time monitoring and custom policies, Spectral complements npm audit, providing a robust, all-encompassing security solution for your software supply chain.

Related articles

top 12 open source security solutions

Top 12 Open Source Code Security Tools

Open source software is everywhere. From your server to your fitness band. And it’s only becoming more common as over 90% of developers acknowledge using open

top 10 java vulnerabilities

Top 10 Most Common Java Vulnerabilities You Need to Prevent

It’s easy to think that our code is secure. Vulnerabilities or potential exploits are often the things we think about last. Most of the time, our

circle.ci vs jenkins

Circle.ci vs Jenkins: Battle of the CI/CDs

Continuous integration and delivery are necessary in any production level software development process. CI/CD are more than just buzzwords. Rather, it is a fully-fledged methodology of

Stop leaks at the source!