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 install, share, and manage reusable code libraries—known as packages—that power modern web applications. Whether you're building a simple script, a full-stack application, or a complex React or Vue frontend, chanc

Nov 6, 2025 - 11:08
Nov 6, 2025 - 11:08
 1

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 install, share, and manage reusable code librariesknown as packagesthat power modern web applications. Whether you're building a simple script, a full-stack application, or a complex React or Vue frontend, chances are youll rely on npm to bring in essential tools like Express, Lodash, Webpack, or Babel.

Installing npm packages correctly is fundamental to efficient development. It ensures your project has the right dependencies, avoids version conflicts, and remains maintainable over time. Poor package management can lead to broken builds, security vulnerabilities, and inconsistent behavior across environments. This guide walks you through everything you need to know to install npm packages confidentlyfrom basic commands to advanced best practicesso you can streamline your workflow and build more reliable applications.

Step-by-Step Guide

Prerequisites: Installing Node.js and npm

Before you can install npm packages, you must have Node.js installed on your system. npm comes bundled with Node.js, so installing one installs the other. Visit the official Node.js website (https://nodejs.org) and download the Long-Term Support (LTS) version, which is recommended for most users due to its stability and extended support cycle.

After installation, open your terminal (Command Prompt on Windows, Terminal on macOS/Linux) and verify the installation by running:

node --version

npm --version

You should see output similar to:

v20.12.2

10.5.0

If these commands return version numbers, youre ready to proceed. If not, ensure Node.js was installed correctly, restart your terminal, or reinstall from the official site.

Initializing a New Project

Before installing any packages, its best practice to initialize a new Node.js project. This creates a package.json filethe manifest that tracks your projects metadata and dependencies.

Navigate to your project directory using the terminal:

cd /path/to/your/project

Then run:

npm init

This command launches an interactive prompt asking for project details like name, version, description, entry point, and more. You can press Enter to accept default values or customize them. Alternatively, use the shortcut:

npm init -y

The -y flag skips the prompts and generates a default package.json file instantly. Heres what a minimal package.json looks like:

{

"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 critical. It tells npm which packages your project depends on and how to run scripts like build, start, or test.

Installing a Package Locally

The most common way to install a package is locallymeaning its added to your projects node_modules folder and listed in your package.json under dependencies.

To install a package like express, run:

npm install express

npm downloads the package and its dependencies, stores them in a node_modules folder inside your project, and adds an entry to your package.json:

"dependencies": {

"express": "^4.18.2"

}

The caret (^) before the version number indicates semantic versioning: npm will install the latest patch version (e.g., 4.18.3) but not a breaking major version (e.g., 5.0.0).

Installing a Package as a Development Dependency

Some packages are only needed during developmentlike testing frameworks (Jest), bundlers (Webpack), or linters (ESLint). These should be installed as devDependencies to keep your production environment lean.

To install a dev dependency, 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 your package.json:

"devDependencies": {

"jest": "^29.7.0"

}

When you deploy your app to production, tools like npm ci or cloud platforms automatically ignore devDependencies unless explicitly told to include them.

Installing a Specific Version

Sometimes you need to install a specific version of a packagefor compatibility, stability, or legacy reasons.

To install version 1.2.3 of a package:

npm install lodash@1.2.3

You can also use version ranges:

  • @1.2.3 exact version
  • @^1.2.3 compatible with 1.2.3 (patch and minor updates)
  • @~1.2.3 compatible with 1.2.x (patch updates only)
  • @latest latest version available

For example:

npm install react@^18.2.0

This ensures you get any 18.x version but not 19.x, avoiding breaking changes.

Installing Global Packages

Some packages are designed to be used as command-line tools across your systemnot tied to a specific project. Examples include nodemon, typescript, create-react-app, or eslint.

To install globally, use the -g flag:

npm install -g nodemon

Global packages are installed in a system-wide directory (not in your project folder). You can find this location by running:

npm config get prefix

After installing globally, you can run the tool from any terminal window:

nodemon index.js

?? Caution: Global installations can cause version conflicts if multiple projects require different versions of the same tool. Use them sparingly and prefer local installations when possible.

Installing from a Package File

If youre working in a team or deploying to production, youll often install all dependencies from a package-lock.json file (generated automatically when you install packages). This file locks exact versions of all dependencies and their sub-dependencies, ensuring consistency across environments.

To install from the lockfile:

npm ci

npm ci is faster and more reliable than npm install in CI/CD environments because it:

  • Deletes the existing node_modules folder
  • Installs packages strictly according to package-lock.json
  • Throws an error if package.json and package-lock.json are out of sync

Use npm ci in automated build pipelines and npm install during local development when you want to update dependencies.

Installing from a Git Repository

You can install packages directly from GitHub, GitLab, or other Git hosts using the repository URL:

npm install git+https://github.com/user/repo.git

Or install from a specific branch or tag:

npm install git+https://github.com/user/repo.git

v1.2.3

npm install git+https://github.com/user/repo.git

develop

This is useful for testing unreleased features, using private forks, or contributing to open-source projects.

Installing from a Local Path

If youre developing a private npm package and want to test it locally before publishing, you can install it directly from a filesystem path:

npm install ../my-local-package

This creates a symbolic link in node_modules, allowing you to make changes to the local package and see them reflected immediately in your main projectno need to republish or reinstall.

Verifying Installed Packages

After installation, you can list all installed packages with:

npm list

To see only top-level dependencies:

npm list --depth=0

To check for outdated packages:

npm outdated

This shows packages with newer versions available in the registry, along with current, wanted, and latest versions.

To update a package to its latest compatible version:

npm update express

To update all packages, run:

npm update

Always test your application after updating dependencies, as minor or patch updates can occasionally introduce breaking changes.

Best Practices

Always Use package.json and package-lock.json

Your package.json defines what packages your project needs, and package-lock.json ensures everyone uses the exact same versions. Never commit only package.json and ignore package-lock.json. Both files should be included in version control (e.g., Git). This guarantees reproducible builds across development, staging, and production environments.

Never Commit node_modules to Version Control

The node_modules folder can be hundreds of megabytes or even gigabytes in size. It contains thousands of files and is automatically regenerated from package-lock.json. Adding it to Git bloats your repository, slows down clones, and creates merge conflicts. Always add node_modules/ to your .gitignore file:

node_modules/

Use Semantic Versioning (SemVer)

Understand how npm interprets version ranges:

  • ^1.2.3 allows updates to 1.2.4, 1.3.0, but not 2.0.0
  • ~1.2.3 allows only patch updates: 1.2.4, 1.2.5, but not 1.3.0
  • 1.2.3 exact version only
  • * any version (not recommended)

Use ^ for most dependencies. Use ~ for packages where even minor updates might break compatibility (e.g., low-level utilities). Avoid * unless youre building a tool that must always use the latest version.

Minimize Dependencies

Every package you install increases your projects attack surface, bundle size, and maintenance burden. Before installing a new package, ask:

  • Can I achieve this with vanilla JavaScript or a built-in module?
  • Is this package actively maintained?
  • Does it have a small footprint and good test coverage?
  • Are there lighter alternatives?

For example, instead of installing a full utility library like Lodash for one function (_.debounce), consider using a single-function package like lodash.debounce or implement it yourself.

Regularly Audit for Security Vulnerabilities

npm includes a built-in security audit tool. Run it periodically:

npm audit

This scans your dependencies for known vulnerabilities and suggests fixes. If vulnerabilities are found, run:

npm audit fix

This automatically applies non-breaking fixes. For more serious issues, you may need to manually update packages or consult the npm advisories page at https://npmjs.com/advisories.

Use .npmrc for Custom Configuration

Customize npm behavior with a local .npmrc file. Common uses include:

  • Setting a custom registry (e.g., for private packages)
  • Configuring authentication tokens
  • Enabling strict SSL or proxy settings

Example .npmrc:

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

save-prod=true

audit-level=high

Place this file in your project root to apply settings only to that project.

Use npm Scripts for Common Tasks

Define reusable scripts in your package.json to avoid typing long commands:

"scripts": {

"start": "node index.js",

"dev": "nodemon index.js",

"build": "webpack --mode production",

"test": "jest --coverage",

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

"prepare": "npm run build"

}

Run them with:

npm run dev

The prepare script runs automatically before publishing to npm, making it ideal for building distribution files.

Lockfile Management

Always commit your package-lock.json and avoid regenerating it manually. If you need to update a package, use:

npm install package-name@latest

Then commit the updated lockfile. Never delete package-lock.json unless youre intentionally resetting your dependency tree.

Keep npm Updated

Although npm comes with Node.js, its updated separately. Keep it current for performance improvements and security patches:

npm install -g npm@latest

However, avoid updating npm in production environments unless necessarystick with the version bundled with your Node.js LTS release.

Tools and Resources

npm Registry (registry.npmjs.org)

The official npm registry hosts over 2 million packages. You can browse packages at https://www.npmjs.com. Each package page includes documentation, version history, download stats, and dependency graphs. Always check the Maintainers and Last published date to gauge package health.

npms.io

https://npms.io is a search engine for npm packages that scores them based on popularity, quality, and maintenance. Its excellent for comparing alternatives. For example, searching for react state management shows packages like Redux, Zustand, and Jotai ranked by metrics.

BundlePhobia

https://bundlephobia.com analyzes the size of npm packages and their impact on your frontend bundle. Its invaluable for optimizing performance. For example, you might discover that a popular library adds 200KB to your bundleinformation that could prompt you to find a lighter alternative.

Dependabot / Renovate

These automated tools monitor your package.json and open pull requests to update dependencies. GitHubs Dependabot is built into repositories and can be configured to update dependencies daily, weekly, or only for security patches. Renovate is a more powerful open-source alternative that supports multiple package managers.

npm Fund

Run npm fund to see which of your dependencies are open-source projects seeking financial support. You can choose to donate directly to maintainers whose work you rely on.

Node.js Documentation

The official Node.js API documentation includes details on built-in modules like fs, path, and http. Familiarizing yourself with these reduces unnecessary npm dependencies.

Security Advisories

Subscribe to the Node.js Security Working Group on GitHub to stay informed about critical vulnerabilities. You can also use tools like snyk or retire.js for deeper scanning.

npm CLI Reference

For full command details, run:

npm help <command>

Or visit the official documentation: https://docs.npmjs.com.

Real Examples

Example 1: Setting Up a Basic Express Server

Lets create a simple HTTP server using Express.

  1. Create a project folder: mkdir my-express-app && cd my-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 = 3000;

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

res.send('Hello World!');

});

app.listen(port, () => {

console.log(Server running at http://localhost:${port});

});

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

"start": "node index.js"

}

  1. Run: npm start

Visit http://localhost:3000 to see your server in action.

Example 2: Building a React App with Vite

Instead of using the legacy Create React App, modern developers often use Vite for faster development.

  1. Create project: npm create vite@latest my-react-app -- --template react
  2. Navigate: cd my-react-app
  3. Install dependencies: npm install
  4. Start dev server: npm run dev

Notice how npm create is a modern alternative to global tools like create-react-app. It downloads and runs a template package without requiring global installation.

Example 3: Setting Up ESLint and Prettier

Improve code quality with linting and formatting.

  1. Install dev dependencies:
npm install --save-dev eslint prettier eslint-config-prettier eslint-plugin-prettier
  1. Create .eslintrc.json:
{

"extends": ["eslint:recommended", "prettier"],

"plugins": ["prettier"],

"rules": {

"prettier/prettier": "error"

}

}

  1. Create .prettierrc:
{

"semi": true,

"trailingComma": "es5",

"singleQuote": true,

"printWidth": 80,

"tabWidth": 2

}

  1. Add lint script:
"scripts": {

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

}

Now run npm run lint to check code style across your project.

Example 4: Using a Private Package from GitHub

Suppose your team has a private utility package hosted on GitHub at https://github.com/yourcompany/utils.

To install it:

npm install git+https://github.com/yourcompany/utils.git

If authentication is required, use SSH or a personal access token:

npm install git+ssh://git@github.com/yourcompany/utils.git

npm install git+https://<TOKEN>@github.com/yourcompany/utils.git

Ensure your package-lock.json is committed so teammates can install it without manual setup.

FAQs

What is the difference between npm install and npm ci?

npm install reads package.json and installs the latest compatible versions according to version ranges, updating package-lock.json if needed. npm ci ignores package.json version ranges and installs exact versions from package-lock.json, deleting node_modules first. Use npm ci in CI/CD pipelines for consistent, fast, and reliable builds.

Why is my npm install taking so long?

Slow installations are often caused by:

  • Large dependency trees with many nested packages
  • Network latency or proxy issues
  • Outdated npm version
  • Missing package-lock.json, forcing npm to resolve versions dynamically

Improve speed by using npm ci, enabling npms built-in cache (npm config set cache /path/to/cache), or switching to a faster registry like https://registry.npmmirror.com (in China) or https://registry.npm.taobao.org.

Can I install npm packages without internet?

Yes. If you have a previous node_modules folder or package-lock.json, you can copy the folder to an offline machine and run npm ci. Alternatively, use npm pack to create .tgz files of packages and install them locally: npm install ./package.tgz. Tools like npm-offline or verdaccio can also help set up local registries.

What happens if I delete node_modules?

Nothing catastrophic. You can safely delete the node_modules folder. Run npm install or npm ci to restore it from package-lock.json. This is often done to resolve corrupted installations.

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

Check:

  • Download count and recent activity on npmjs.com
  • Number of maintainers and responsiveness to issues
  • License type (prefer MIT, Apache, BSD)
  • Security audit results via npm audit
  • GitHub stars, forks, and recent commits

Avoid packages with no recent updates, poor documentation, or suspicious code.

Can I use yarn or pnpm instead of npm?

Yes. Yarn and pnpm are alternative package managers with different performance characteristics and installation strategies. Yarn offers faster installs and deterministic resolution. pnpm uses hard links to save disk space. However, npm has improved significantly since version 5 and is now the default for most projects. Stick with npm unless you have a specific need for another tool.

How do I publish my own npm package?

First, create a package.json with a unique name. Then:

  1. Log in: npm login
  2. Run npm publish from your project directory

Make sure your package name isnt already taken. Avoid using names that could be confused with popular packages.

Conclusion

Installing npm packages is a foundational skill for any JavaScript or Node.js developer. From understanding the difference between dependencies and devDependencies to using semantic versioning and auditing for security, mastering these concepts ensures your projects are reliable, maintainable, and scalable.

This guide has walked you through the full lifecycle of package installationfrom initializing a project and installing local and global packages, to managing version locks, auditing vulnerabilities, and leveraging real-world examples. You now know not only how to install packages, but how to do it responsibly and efficiently.

Remember: the goal isnt just to install packagesits to build systems that are secure, fast, and sustainable. Use the best practices outlined here to avoid common pitfalls, reduce technical debt, and collaborate effectively with other developers. As the JavaScript ecosystem evolves, staying disciplined with package management will keep your projects ahead of the curve.

Keep experimenting, stay curious, and always verify what youre adding to your codebase. Your future selfand your userswill thank you.