How to Install Npm Packages

How to Install Npm Packages Node Package Manager (npm) is the default package manager for Node.js and one of the largest software registries in the world. It enables developers to easily share, reuse, and manage code libraries—known as packages—that power everything from simple scripts to enterprise-grade web applications. Whether you're building a React frontend, a Express.js API, or a CLI tool,

Oct 30, 2025 - 12:59
Oct 30, 2025 - 12:59
 0

How to Install Npm Packages

Node Package Manager (npm) is the default package manager for Node.js and one of the largest software registries in the world. It enables developers to easily share, reuse, and manage code libraries—known as packages—that power everything from simple scripts to enterprise-grade web applications. Whether you're building a React frontend, a Express.js API, or a CLI tool, installing npm packages is a foundational skill that unlocks the full potential of modern JavaScript development.

Installing npm packages correctly ensures your project remains maintainable, secure, and scalable. Missteps—like installing packages globally when they should be local, or neglecting version control—can lead to dependency conflicts, security vulnerabilities, and inconsistent behavior across environments. This guide provides a comprehensive, step-by-step walkthrough of how to install npm packages effectively, covering everything from basic commands to advanced best practices and real-world examples.

Step-by-Step Guide

Prerequisites: Setting Up Node.js and npm

Before you can install any npm packages, you must have Node.js installed on your system. npm comes bundled with Node.js, so installing one installs the other. To verify whether you already have Node.js and npm installed, open your terminal or command prompt and run:

node --version

npm --version

If both commands return version numbers (e.g., v20.12.0 and v10.5.0), you’re ready to proceed. If not, download and install the latest LTS (Long-Term Support) version of Node.js from nodejs.org. The installer will automatically configure npm for you.

Understanding npm Package Types

npm packages come in two primary categories: local and global. Understanding the difference is critical to proper package management.

  • Local packages are installed within a specific project directory and are listed in the project’s package.json file. These are dependencies required for the application to run or develop. Most packages you install should be local.
  • Global packages are installed system-wide and are typically command-line tools (like nodemon, eslint, or create-react-app) that you use across multiple projects.

Installing a package globally with npm install -g package-name places it in a system directory and makes it accessible from any terminal session. However, global installations should be used sparingly to avoid conflicts and maintain project portability.

Initializing a New Project

Before installing any packages, it’s best practice to initialize a new Node.js project. This creates a package.json file, which acts as the manifest for your project’s dependencies, scripts, metadata, and configuration.

Navigate to your project directory in the terminal and run:

npm init

This command launches an interactive prompt asking for details like project name, version, description, entry point, and more. You can press Enter to accept defaults, or provide custom values. Alternatively, use the -y flag to skip prompts and generate a default package.json:

npm init -y

The resulting package.json file will look something like this:

{

"name": "my-project",

"version": "1.0.0",

"description": "",

"main": "index.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"keywords": [],

"author": "",

"license": "ISC"

}

This file is essential for reproducible builds and team collaboration. Always commit it to version control (e.g., Git).

Installing a Package Locally

To install a package as a dependency for your project, use the npm install command followed by the package name. For example, to install the popular HTTP client axios:

npm install axios

This command does several things:

  • Downloads the latest version of axios from the npm registry.
  • Creates or updates a node_modules folder in your project directory containing the package and its dependencies.
  • Adds axios to the dependencies section of your package.json file.

After installation, you can import and use the package in your code:

const axios = require('axios');

// or

import axios from 'axios';

Installing Specific Versions

By default, npm install package-name installs the latest stable version. However, you may need to install a specific version for compatibility or stability reasons.

To install a specific version:

npm install axios@1.6.7

You can also use version modifiers:

  • ^1.6.7 – Install the latest patch version compatible with 1.6.7 (e.g., 1.6.8, but not 1.7.0)
  • ~1.6.7 – Install the latest patch version within 1.6.x (e.g., 1.6.8, but not 1.7.0)
  • 1.6.7 – Install exactly version 1.6.7
  • latest – Install the most recent release (same as omitting version)

Using version modifiers helps maintain stability. The caret (^) is the default in modern npm, allowing minor updates that are unlikely to break your code.

Installing as a Development Dependency

Not all packages are required for your application to run in production. Tools like testing frameworks, bundlers, or linters are only needed during development. These should be installed as devDependencies.

To install a package as a devDependency, use the --save-dev or -D flag:

npm install jest --save-dev

or

npm install jest -D

This adds the package to the devDependencies section of package.json instead of dependencies. When someone else clones your project and runs npm install, they’ll install both dependencies and devDependencies by default.

If you want to install only production dependencies (e.g., when deploying to a server), use:

npm install --production

This skips all devDependencies, reducing installation time and attack surface.

Installing Multiple Packages at Once

You can install multiple packages in a single command by listing them space-separated:

npm install express mongoose dotenv cors

For devDependencies:

npm install jest eslint prettier --save-dev

This reduces repetitive typing and ensures consistent versioning across your team.

Installing from a Package File

If you have a package.json file from another project or a teammate, you can install all listed dependencies at once by running:

npm install

Without any arguments, npm reads the package.json file and installs all packages listed under dependencies and devDependencies. This is the standard workflow for onboarding new developers or deploying applications.

npm also reads package-lock.json (or npm-shrinkwrap.json) to install exact versions of packages and their sub-dependencies, ensuring reproducible builds across environments.

Installing Globally

Global installations are reserved for tools you use across multiple projects. Common examples include:

  • nodemon – Automatically restarts Node.js apps during development
  • eslint – Code quality and style enforcement
  • typescript – If you use TypeScript globally
  • create-react-app – Legacy project scaffolding tool

To install globally:

npm install -g nodemon

After installation, you can run the tool from anywhere in your terminal:

nodemon server.js

⚠️ Caution: Global installations can cause version conflicts if multiple projects require different versions of the same tool. Whenever possible, use local installations with npm scripts (e.g., npm run dev that calls nodemon locally).

Uninstalling Packages

To remove a package from your project, use:

npm uninstall package-name

This removes the package from node_modules and deletes its entry from package.json.

To remove a devDependency:

npm uninstall package-name --save-dev

To uninstall a globally installed package:

npm uninstall -g package-name

Always verify the package is no longer referenced in your code before uninstalling.

Best Practices

Always Use package.json and package-lock.json

Never rely on manual installations without updating package.json. This file is the single source of truth for your project’s dependencies. Similarly, package-lock.json locks dependency versions to ensure every developer and deployment environment uses identical package trees.

Commit both files to version control. Never ignore them. This prevents “it works on my machine” issues and enables reliable CI/CD pipelines.

Prefer Local Over Global Installations

Global packages may seem convenient, but they introduce hidden dependencies and version drift. Instead, install tools like eslint, prettier, or nodemon locally and define scripts in package.json:

{

"scripts": {

"start": "node index.js",

"dev": "nodemon index.js",

"lint": "eslint . --ext .js,.jsx",

"format": "prettier --write ."

}

}

Run them via npm run dev or npm run lint. This ensures everyone uses the same version and makes your project self-contained.

Keep Dependencies Updated

Outdated packages can introduce security vulnerabilities and performance issues. Use the following commands to stay current:

  • npm outdated – Shows which packages have newer versions available
  • npm update – Updates packages to the latest version allowed by your version range (e.g., ^1.2.3 → 1.3.1)
  • npm audit – Scans for known security vulnerabilities

For major version updates (which may include breaking changes), use tools like npx npm-check-updates:

npx npm-check-updates -u

npm install

This upgrades all dependencies to their latest major versions and updates package.json accordingly. Always test thoroughly after major updates.

Use Semantic Versioning

Understand and respect semantic versioning (SemVer): MAJOR.MINOR.PATCH.

  • MAJOR – Breaking changes
  • MINOR – Backward-compatible features
  • PATCH – Backward-compatible bug fixes

Use ^ for minor and patch updates (recommended for most dependencies). Use ~ if you want only patch updates. Avoid * or no version specifier—this leads to unpredictable behavior.

Minimize Dependencies

Every package you install increases your project’s complexity, bundle size, and attack surface. Before adding a new dependency, ask:

  • Can I achieve this with native JavaScript or a smaller library?
  • Is this package actively maintained?
  • Does it have a large community and good documentation?
  • What are its own dependencies? (Use npm ls to view the dependency tree)

For example, instead of installing a full utility library like Lodash, import only what you need:

import { debounce } from 'lodash-es';

Or better yet, write a simple debounce function yourself if it’s only used once.

Secure Your Dependencies

Run npm audit regularly to identify known vulnerabilities. npm will suggest fixes:

npm audit fix

This automatically applies non-breaking fixes. For breaking changes, use:

npm audit fix --force

⚠️ Use --force cautiously—it may introduce instability. Always review changes in package-lock.json before committing.

Consider integrating automated security scanning into your CI pipeline using tools like Snyk or GitHub Dependabot.

Use .npmrc for Custom Configurations

Project-specific npm settings (like private registries, registry URLs, or authentication tokens) can be stored in a .npmrc file in your project root. This ensures consistency across team members.

Example .npmrc:

registry=https://registry.npmjs.org/

save-prod=true

audit=true

Never commit API keys or tokens to .npmrc. Use environment variables or secrets management instead.

Tools and Resources

npm Registry and Website

The official npm registry is hosted at registry.npmjs.org. The public-facing website, npmjs.com, allows you to search for packages, view documentation, check download stats, and review package metadata.

Use the website to evaluate packages before installing:

  • Check the number of weekly downloads
  • Review the last publish date
  • Look at the number of open issues and recent commits
  • Read the license (avoid non-commercial or ambiguous licenses)

npm Audit and Security Tools

npm includes built-in security auditing via npm audit. For enhanced security, consider:

  • Snyk – Scans for vulnerabilities and provides automated fixes
  • Dependabot – GitHub’s automated dependency updater
  • Greenkeeper – Legacy tool for automatic version updates

Integrate Snyk or Dependabot into your GitHub repository to receive alerts and pull requests when vulnerabilities are found.

Package Discovery Tools

When searching for packages, use:

  • npms.io – Rates packages by quality, popularity, and maintenance
  • bundlephobia.com – Shows bundle size impact of packages (critical for frontend projects)
  • libraries.io – Cross-platform package dependency tracker

These tools help you avoid bloated, unmaintained, or poorly documented packages.

Package Managers Alternatives

While npm is the default, other package managers offer improved speed, security, or features:

  • Yarn – Developed by Facebook, offers faster installs and deterministic dependency resolution. Uses yarn add and yarn install.
  • pnpm – Uses hard links and a content-addressable store to save disk space and improve performance. Uses pnpm add.

Both are fully compatible with npm’s registry and package.json. Choose based on team preference and performance needs. You can switch between them without changing your codebase.

Node Version Management

Use a Node version manager like nvm (Node Version Manager) to switch between Node.js versions across projects:

  • Install nvm: curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
  • List available versions: nvm list-remote
  • Install a version: nvm install 20
  • Use a version: nvm use 20
  • Set default: nvm alias default 20

This ensures your project runs consistently regardless of the system’s default Node.js version.

Documentation and Learning Resources

For deeper learning:

Real Examples

Example 1: Setting Up a Basic Express Server

Let’s build a simple Express.js server and install required packages step by step.

  1. Create a project folder: mkdir express-app && cd express-app
  2. Initialize: npm init -y
  3. Install Express: npm install express
  4. Create index.js:
const express = require('express');

const app = express();

const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {

res.send('Hello, World!');

});

app.listen(PORT, () => {

console.log(Server running on http://localhost:${PORT});

});

  1. Add a start script to package.json:
{

"scripts": {

"start": "node index.js"

}

}

  1. Run: npm start

You now have a fully functional Express server with proper dependency management.

Example 2: React Frontend with Development Tools

Let’s create a React app using Vite (modern alternative to Create React App).

  1. Create project: npm create vite@latest my-react-app -- --template react
  2. Navigate: cd my-react-app
  3. Install dependencies: npm install
  4. Install dev tools: npm install --save-dev eslint prettier eslint-plugin-react
  5. Add scripts:
{

"scripts": {

"dev": "vite",

"build": "vite build",

"preview": "vite preview",

"lint": "eslint . --ext .js,.jsx,.ts,.tsx",

"format": "prettier --write ."

}

}

  1. Run development server: npm run dev

This setup includes bundling, linting, and formatting—all managed locally with npm scripts, ensuring portability and consistency.

Example 3: CLI Tool with Global Installation

Suppose you’re building a custom CLI tool called my-cli. You want to install it globally for easy access.

  1. In package.json, add:
{

"name": "my-cli",

"version": "1.0.0",

"bin": {

"my-cli": "./bin/index.js"

},

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

}

}

  1. Create bin/index.js with a shebang:

!/usr/bin/env node

console.log('Hello from my CLI tool!');

  1. Make it executable: chmod +x bin/index.js
  2. Install globally: npm install -g . (from the project root)
  3. Use it anywhere: my-cli

This is how tools like create-react-app or next are distributed.

FAQs

What is the difference between npm install and npm ci?

npm install reads package.json and installs dependencies, updating package-lock.json if needed. npm ci (clean install) strictly uses package-lock.json to install exact versions and deletes node_modules first. Use npm ci in CI/CD pipelines for faster, more reliable builds.

Why is my node_modules folder so large?

Node.js packages often have deep dependency trees. Each package may depend on others, creating a hierarchy. Use npm ls to visualize the tree. To reduce size, use pnpm (which shares packages globally) or remove unused dependencies with npm prune.

Can I install npm packages without internet?

Yes. Use npm pack to create a .tgz file of a package, then install it locally with npm install ./package.tgz. For offline environments, use tools like npx with cached packages or set up a private registry like Verdaccio.

How do I know if a package is safe to install?

Check the package’s:

  • Download count and recent activity
  • Author and maintainer reputation
  • License type (MIT, Apache, BSD are safe)
  • Security advisories via npm audit or Snyk
  • GitHub repository issues and pull requests

Avoid packages with no GitHub repo, no documentation, or suspicious code.

What happens if I delete node_modules?

You can safely delete the node_modules folder. It’s generated from package.json and package-lock.json. Simply run npm install to restore it. Never commit node_modules to version control—add it to .gitignore.

How do I install a package from GitHub?

You can install directly from a GitHub repository:

npm install github:username/repo-name
npm install github:username/repo-name

branch-name

npm install github:username/repo-name

commit-hash

This is useful for testing unreleased features or private repositories.

Why does npm install take so long?

Slow installs are often due to:

  • Large dependency trees
  • Slow network or registry issues
  • Antivirus scanning node_modules

Use pnpm for faster installs, or configure npm to use a faster registry like https://registry.npmmirror.com (mirror in China).

Conclusion

Installing npm packages is not just a technical task—it’s a critical practice that shapes the reliability, security, and maintainability of your JavaScript applications. From initializing a project with npm init to locking versions with package-lock.json, every step in the process contributes to a robust development workflow.

By following best practices—such as preferring local installations, using semantic versioning, auditing for vulnerabilities, and minimizing dependencies—you ensure your projects remain scalable, secure, and collaborative. Tools like npm audit, npx, and version managers like nvm further empower you to manage complexity with confidence.

Remember: npm is not just a package installer—it’s the backbone of the modern JavaScript ecosystem. Mastering how to install npm packages properly means mastering the foundation of modern web development. Whether you’re building a simple script or a complex microservice, the principles outlined in this guide will serve you well across every project you undertake.

Start small. Verify each installation. Keep your dependencies lean. And always, always commit your package.json and package-lock.json. Your future self—and your team—will thank you.