Report this

What is the reason for this report?

How To Install and Use the Yarn Package Manager for Node.js

Updated on October 30, 2025
How To Install and Use the Yarn Package Manager for Node.js

Introduction

Yarn is a package manager for Node.js that focuses on speed, security, and consistency. It was originally created to address some issues with the popular NPM package manager. Though the two package managers have since converged in terms of performance and features, Yarn remains popular, especially in the world of React development.

If you need a quick overview of Yarn’s features and usage, check out our concise introduction: Quick Intro to Yarn.

Some of the unique features of Yarn are:

  • A per-project caching mechanism, that can greatly speed up subsequent installs and builds
  • Consistent, deterministic installs that guarantee the structure of installed libraries are always the same
  • Checksum testing of all packages to verify their integrity
  • “Workspaces”, which facilitate using Yarn in a monorepo (multiple projects developed in a single source code repository)

In this tutorial, you will install Yarn globally, add Yarn to a specific project, learn essential Yarn commands, troubleshoot common issues, and understand when Yarn offers advantages over npm.

Deploy your frontend applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.

Key Takeaways

  • Project-Specific Versions: Yarn uses a two-tier installation model—global CLI tool plus project-specific versions—ensuring consistent behavior across team and CI/CD environments
  • Zero-Install Potential: With Plug’n’Play (PnP) mode, Yarn can eliminate node_modules directories entirely, dramatically reducing installation times and disk usage
  • Deterministic Installs: The yarn.lock file guarantees identical dependency trees across different machines and environments, preventing “works on my machine” issues
  • Offline-First Architecture: Yarn’s aggressive caching means packages installed once can be used offline, making development more reliable in low-connectivity scenarios

Installing & Using Yarn Package Manager for Node.js

  1. Install Yarn globally
  2. Install Yarn in your project
  3. Use Yarn
  4. Understanding Yarn vs npm
  5. Troubleshooting Common Issues

Prerequisites

Before installing and using the Yarn package manager, you will need to have Node.js installed. To see if you already have Node.js installed, type the following command into your local command line terminal:

  1. node -v

If you see a version number, such as v24.11.0 printed, you have Node.js installed. If you get a command not found error (or similar phrasing), please install Node.js before continuing.

To install Node.js, follow our tutorial for Ubuntu, Debian, CentOS, or macOS.

Once you have Node.js installed, proceed to Step 1 to install the Yarn package manager.

Step 1 — Installing Yarn Globally

Install the global Yarn CLI once so you can bootstrap a project-pinned Yarn version reliably on every machine.

Yarn has a unique way of installing and running itself in your JavaScript projects. First, you install the yarn command globally, then you use the global yarn command to install a specific local version of Yarn into your project directory. This is necessary to ensure that everybody working on a project (and all of the project’s automated testing and deployment tooling) is running the same version of yarn, to avoid inconsistent behaviors and results.

The Yarn maintainers recommend installing Yarn globally by using the NPM package manager, which is included by default with all Node.js installations. Use the -g flag with npm install to do this:

  1. sudo npm install -g yarn

After the package installs, have the yarn command print its own version number. This will let you verify it was installed properly:

  1. yarn --version
Output
1.22.22

Now that you have the yarn command installed globally, you can use it to install Yarn into a specific JavaScript project.

Step 2 — Installing Yarn in Your Project

Pin a local Yarn (“Berry”) version in your repo so teammates and CI run the exact same tooling.

You can skip this step if you are using Yarn to work with an existing Yarn-based project. The project should already be set up with a local version of Yarn and all the configuration files necessary to use it.

If you are setting up a new project of your own, you’ll need to configure a project-specific version of Yarn now.

First, navigate to your project directory:

  1. cd ~/my-project

If you don’t have a project directory, you can make a new one with mkdir and then move into it:

  1. mkdir my-project
  2. cd my-project

Now use the yarn set command to set the version to berry:

  1. yarn set version berry

This will download the current, actively developed version of Yarn – berry – save it to a .yarn/releases/ directory in your project, and set up a .yarnrc.yml configuration file as well:

Output
Resolving berry to a url... Downloading https://github.com/yarnpkg/berry/raw/master/packages/berry-cli/bin/berry.js... Saving it into /home/sammy/my-project/.yarn/releases/yarn-berry.cjs... Updating /home/sammy/my-project/.yarnrc.yml... Done!

Now try the yarn --version command again:

  1. yarn --version
Output
4.5.0

You’ll see the version is 3.0.0 or higher. This is the latest release of Yarn.

Note: If you cd out of your project directory and run yarn --version again, you’ll once again get the global Yarn’s version number, 1.22.22 in this case. Every time you run yarn, you use the command’s globally installed version. The global yarn command first checks to see if it’s in a Yarn project directory with a .yarnrc.yml file, and if it is, it hands the command off to the project-specific version of Yarn configured in the project’s yarnPath setting.

Your project is now set up with a project-specific version of Yarn. Next, we’ll look at a few commonly used yarn commands to get started with.

Using Yarn

These essential commands handle the majority of everyday tasks: installing dependencies, adding, removing, or upgrading packages, and running scripts.

For more about adding and removing packages using both npm and Yarn, see: Adding and Removing Packages Using npm and Yarn

Yarn has many subcommands, but you only need a few to get started. Let’s look at the first subcommands you’ll want to use.

Getting Help

When starting with any new tool, it’s useful to learn how to access its online help. In Yarn the --help flag can be added to any command to get more information:

  1. yarn --help

<$>[tip] You can also use -h instead of --help for a shorter version, e.g. yarn add -h. <$>

This will print out overall help for the yarn command. To get more specific information about a subcommand, add --help after the subcommand:

  1. yarn install --help

This would print out details on how to use the yarn install command.

Starting a New Yarn Project

If you’re starting a project from scratch, use the init subcommand to create the Yarn-specific files you’ll need:

  1. yarn init

This will add a package.json configuration file and a yarn.lock file to your directory. The package.json contains the configuration and your list of module dependencies. The yarn.lock file locks those dependencies to specific versions, making sure that the dependency tree is always consistent.

Installing all of a Project’s Dependencies

To download and install all the dependencies in an existing Yarn-based project, use the install subcommand:

  1. yarn install

This will download and install the modules you need to get started.

Adding a New Dependency to a Project

Use the add subcommand to add new dependencies to a project:

  1. yarn add package-name

This will download the module, install it, and update your package.json and yarn.lock files.

Sanity Check: Run and Verify

Install Express and create a tiny server:

  1. yarn add express
index.js
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("Yarn is working!"));
app.listen(3000, () => console.log("Server running on http://localhost:3000"));

Run it:

  1. yarn node index.js

Verify it responds:

  1. curl http://localhost:3000
Expected output
Yarn is working!

Updating Your .gitignore File for Yarn

Yarn stores files in a .yarn folder inside your project directory. Some of these files should be checked into version control and others should be ignored. The basic .gitignore configuration for Yarn follows:

.gitignore
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
.pnp.*

This ignores the entire .yarn directory and then adds in some exceptions for important folders, including the releases directory which contains your project-specific version of Yarn.

For more details on how to configure Git and Yarn, please refer to the official Yarn documentation on .gitignore.

Additional Essential Yarn Commands

Beyond the basic install and add commands, Yarn provides several other useful commands for managing dependencies:

Removing a dependency:

  1. yarn remove package-name

Updating dependencies:

  1. yarn upgrade [package-name]

Listing installed packages:

  1. yarn list --depth=0

Checking for outdated packages:

  1. yarn outdated

Running scripts defined in package.json:

  1. yarn run script-name

Cleaning the cache:

  1. yarn cache clean

Understanding .yarnrc.yml Configuration

.yarnrc.yml controls how Yarn links modules (PnP vs node_modules), caches packages, and integrates with editors/CI.

The .yarnrc.yml file is Yarn’s configuration file. Here’s an example of common configurations:

.yarnrc.yml
nodeLinker: pnp
pnpMode: strict

compressionLevel: mixed
enableGlobalCache: true
enableTelemetry: false

Key settings explained:

  • nodeLinker: This setting tells Yarn how to manage Node.js module resolution. It can be set to pnp (Plug’n’Play, which eliminates the node_modules folder), pnpm (similar to the pnpm manager’s symlinked structure), or node-modules (traditional install). Choose based on your workflow or compatibility needs. The choice affects dependency layout and performance.

  • compressionLevel: This controls how Yarn compresses packages in its cache to save disk space and bandwidth. 0 disables compression entirely (faster, but uses more space), 1 fully compresses all packages, and mixed applies compression only where it makes the biggest impact. Recommendation: Use mixed (the default) for most projects as it provides a good balance. Use 0 only if you have abundant disk space and prioritize installation speed. Use 1 if disk space is constrained.

  • enableGlobalCache: When set to true, Yarn stores a shared package cache globally (usually in the user’s home directory) so that different projects can reuse the same dependency packages instead of maintaining separate per-project caches. This speeds up installs and saves disk space, especially when working with multiple projects using many of the same modules.

  • enableTelemetry: This option enables or disables anonymous usage telemetry collection by Yarn. When false, Yarn won’t send any usage statistics or environment information. Turning this off can help with compliance or privacy concerns in corporate or sensitive environments, but Yarn uses this data to prioritize bug fixes and improve user experience overall.

Understanding Yarn vs npm

Choose Yarn for faster, deterministic installs and first-class workspaces; choose npm for simpler, single-package projects or when your org standardizes on it.

Both Yarn and npm are package managers for Node.js, and they share many similarities. However, there are key differences that may influence your choice:

Feature Yarn npm
Installation Speed Faster initial and repeat installs due to parallelization and aggressive caching Slower, especially for large projects, though recent versions have improved
Deterministic Installs yarn.lock ensures identical installs across all environments package-lock.json provides consistency, but historically less strict
Workspaces/Monorepos First-class support, easy linking, mature integration Basic support, fewer advanced features
Plug’n’Play Support Supports PnP to remove node_modules, improving performance and saving disk space No PnP support; always uses node_modules
Disk Space Efficiency Lower (up to 50%) disk usage with PnP; global cache shared across projects Comparable with Yarn in classic mode; higher with many projects
CI/CD Reliability --immutable flag fails builds on lockfile drift, enforcing reproducibility Lockfile warnings but does not enforce by default
Offline Installation Strong offline support; aggressive local caching Basic offline capabilities
Configuration File YAML-based .yarnrc.yml - flexible and project-scoped .npmrc - traditional key-value format
Custom Registry Support Advanced settings (scopes, CA, authentication) in config Supported via .npmrc
Telemetry Disabled by default (enableTelemetry: false in config) Enabled by default, must be opted out
Community & Ecosystem Popular in React and monorepo setups; growing support Default for Node.js; vast documentation and resources
Backward Compatibility May require adaptation (e.g., yarn.lock not read by npm) Standard baseline for most JavaScript projects

Tip: In general, Yarn is recommended for teams that want speed, reproducibility, and monorepo-friendly workflows. npm remains a solid, straightforward choice for most Node.js applications, solo projects, or environments that standardize around npm.

Performance Characteristics

Installation Speed: Yarn’s parallel installation process and aggressive caching typically result in faster initial installs, especially for projects with many dependencies. Benchmarks often show Yarn completing installs in 60-70% of the time npm requires for large dependency trees.

Disk Space: When using Plug’n’Play (PnP) mode, Yarn can consume 40-50% less disk space by eliminating the node_modules directory. Traditional Yarn with node_modules typically uses similar space to npm.

Lock File Handling

Both tools generate lock files (yarn.lock and package-lock.json), but Yarn’s yarn.lock is generally considered more deterministic. The lock file format is more compact and explicitly tracks dependency resolution decisions, which can help debug version conflicts.

Concrete Scenarios

Scenario 1 — Monorepo with ~6 packages (shared ESLint/TS config)

  • Problem: Cross‑package linking and consistent tooling versions are brittle.
  • Yarn win: Workspaces auto‑link local packages; one lockfile; predictable hoisting.

Scenario 2 — CI/CD with strict reproducibility

  • Problem: “Works on my machine” due to lockfile drift / partial installs.
  • Yarn win: Use yarn install --immutable to fail builds if the lockfile doesn’t match, guaranteeing identical artifacts.

Scenario 3 — Corporate proxy / custom CA

  • Problem: SSL MITM or private registries cause install failures.
  • Yarn win: Configure trust/cert once in .yarnrc.yml (e.g., caFile, npmScopes) and keep CI in sync with the repo config.

Workspace Support

Yarn’s workspace feature is more mature and integrated than npm’s equivalent. Monorepos benefit from:

  • Automatic workspace linking without explicit configuration
  • Better dependency hoisting controls
  • Seamless integration with tools like Lerna and Nx
  • Editor SDKs: yarn dlx @yarnpkg/sdks vscode enables TypeScript/ESLint to understand PnP without node_modules.

When to Choose Yarn

Choose Yarn when:

  • You need deterministic builds across different environments (CI/CD, team members, production)
  • You’re working with large monorepos or multiple projects
  • Disk space is at a premium and you want to explore PnP mode
  • Your team values consistent, auditable dependency installations
  • You’re building React applications (where Yarn has strong community support)

When to Use npm

Stick with npm when:

  • Your project is simple with few dependencies (npm’s simplicity is an advantage)
  • Your team is already comfortable with npm
  • You’re using tools that better integrate with npm’s ecosystem
  • The difference in installation speed doesn’t impact your workflow

Migration Note: It’s possible to switch between Yarn and npm in the same project, but not recommended. The lock files (yarn.lock and package-lock.json) serve different purposes and shouldn’t coexist. If migrating, delete one lock file and regenerate it with the tool you’re switching to.

Troubleshooting Common Issues

Yarn Installation Fails with Permissions Error

If you encounter permission errors during global installation:

  1. sudo npm install -g yarn

On some systems, you might need to configure npm to use a different directory for global packages. Check npm’s configuration:

  1. npm config get prefix

If it points to a system directory, you may want to reconfigure npm to use a user-owned directory. To do this, create a directory for global packages and configure npm:

  1. mkdir ~/.npm-global
  2. npm config set prefix '~/.npm-global'

Then add this directory to your PATH by adding this line to your ~/.bashrc, ~/.zshrc, or equivalent shell configuration file:

  1. export PATH=~/.npm-global/bin:$PATH

Reload your shell configuration with source ~/.bashrc (or equivalent), then try installing Yarn again without sudo.

Version Discrepancies Between Global and Project Yarn

This is expected behavior. The global Yarn CLI (version 1.x) is just a launcher for the project-specific version. When you’re inside a project with .yarnrc.yml, the global yarn delegates to the project’s version. This ensures everyone on the team uses the same Yarn version.

To verify which version is actually being used:

  1. yarn --version

Inside a Yarn project, this shows the project’s version. Outside a Yarn project, it shows the global version.

Packages Not Found After Installation

If you’re using Yarn PnP mode (where node_modules doesn’t exist), some tools may not understand how to resolve modules. Solutions:

  1. Use compatible tools: Yarn maintains a tool compatibility list

  2. Enable the SDK: Some editors require explicit SDK setup:

    1. yarn dlx @yarnpkg/sdks vscode
  3. Switch to node_modules mode:
    If PnP causes compatibility problems, you can tell Yarn to use the traditional node_modules folder by adding this to your .yarnrc.yml file:

nodeLinker: node-modules

yarn.lock Conflicts in Team Work

The yarn.lock file should be committed to version control. When multiple team members add dependencies, you’ll encounter merge conflicts. Resolution strategy:

  1. Choose one branch as the source of truth
  2. Run yarn install to regenerate the lock file
  3. Commit the regenerated lock file

To prevent future conflicts, adopt a workflow where dependency changes go through a single person or a bot.

If Yarn starts behaving unexpectedly or packages seem outdated, clear the cache:

  1. yarn cache clean

You can also check where Yarn stores cached packages:

  1. yarn cache dir

The .pnp Files and Node.js Resolution

When using PnP mode, Yarn creates .pnp.js and .pnp.cjs files. These map module names to their exact locations on disk, eliminating the need for Node.js to traverse directories. If you see import errors with PnP, ensure your Node.js version is recent enough to support PnP resolution hooks. Yarn Berry requires Node.js 14.18.0 or higher, though Node.js 16.x or 18.x LTS are recommended for best compatibility and performance.

Frequently Asked Questions

How do I install Yarn globally on my system?

The recommended way to install Yarn globally is using npm:

  1. sudo npm install -g yarn

After installation, verify with yarn --version. This installs the global Yarn CLI, which is version 1.x and serves as a launcher for project-specific Yarn versions.

What’s the difference between npm and Yarn?

Yarn and npm are both package managers for Node.js with several key differences:

Performance: Yarn’s parallel installation and caching typically result in faster installs (often 60-70% faster for large projects). Yarn’s PnP mode can reduce disk usage by up to 50% by eliminating node_modules.

Determinism: Yarn’s yarn.lock format is more deterministic, ensuring identical dependency trees across environments. This reduces “works on my machine” issues significantly.

Monorepo Support: Yarn’s workspace feature is more mature, with automatic linking and better hoisting controls compared to npm’s equivalent.

Workflow: Yarn commands are generally more intuitive (yarn add vs npm install --save), and the output is more concise and readable.

How do I update Yarn to the latest version?

For the global Yarn CLI:

  1. npm install -g yarn@latest

For project-specific Yarn versions, navigate to your project directory and run:

  1. yarn set version latest

Or to set a specific version (e.g., berry for Yarn 4.x):

  1. yarn set version berry

Can I use Yarn with existing npm projects?

Yes, you can switch to Yarn in an existing npm project. Navigate to your project directory and run:

  1. yarn install

This reads your package.json and generates a yarn.lock file. You should delete package-lock.json and add yarn.lock to version control. Be aware that the dependency resolution might differ slightly between npm and Yarn, which is why the lock file should be regenerated.

Note: Don’t use both npm and Yarn in the same project. Choose one package manager and stick with it to avoid inconsistencies in your dependency tree.

What are the benefits of using Yarn for Node.js development?

  • Deterministic builds: The yarn.lock file guarantees that everyone on your team and in production gets the exact same dependency versions, eliminating environment-specific bugs.

  • Faster installations: Yarn’s parallel installation and caching mechanism significantly reduce installation times, especially for projects with many dependencies.

  • Offline support: Yarn can work completely offline after the first install, thanks to its aggressive caching strategy.

  • Better monorepo support: Yarn workspaces provide seamless management of multiple packages in a single repository, with automatic linking and optimized hoisting.

  • Security: Yarn performs checksum verification on all packages, ensuring package integrity and security.

  • PnP mode: Optional Plug’n’Play mode eliminates node_modules entirely, dramatically reducing disk usage and improving performance in constrained environments.

How do I remove a package in Yarn?

Use the remove command:

  1. yarn remove package-name

This removes the package from package.json, deletes it from yarn.lock, and uninstalls it from your project.

What’s the difference between Yarn 1.x and Yarn Berry (2.x/3.x/4.x)?

Yarn 1.x (also called Classic) is the original Yarn and is still widely used. Yarn Berry (versions 2.x, 3.x, and 4.x) is the modern iteration with significant improvements:

  • PnP by default: Berry uses Plug’n’Play mode by default, eliminating node_modules
  • Zero-installs: Projects can be committed with dependencies included
  • Better performance: Improved caching and installation algorithms
  • Improved CLI: More intuitive commands and better error messages
  • Plugin system: Extensible through a plugin architecture

Most new projects should use Yarn Berry. The global CLI serves as a launcher for both versions.

Yarn Classic (1.x) vs Yarn Berry (2.x/3.x/4.x): Comprehensive Comparison

Choosing between Yarn Classic and Yarn Berry is essential for optimal Node.js project management. Here is an expert-driven feature breakdown to help you select the right version for your workflow, optimized for both developer productivity and CI/CD reliability.

Feature Area Yarn Classic (1.x) Yarn Berry (2.x/3.x/4.x) Key Considerations
Default Module Linking Uses traditional node_modules directory for package resolution Plug’n’Play (PnP) is the default; eliminates node_modules for reduced disk usage and faster resolution Use PnP when you want maximum performance and disk efficiency; revert to node_modules for legacy tool compatibility
Lockfile & Reproducibility yarn.lock ensures deterministic installs yarn.lock plus advanced --immutable installs for strict, fail-safe reproducible builds Use yarn install --immutable in CI/CD to guarantee lockfile sync and build consistency
Installation Performance Parallelized installs with dependency caching Next-generation algorithms and support for “Zero‑Install” (pre-committed dependencies for instant setup) Large monorepos and frequent CI runners see dramatic speed gains
Workspaces (Monorepo Support) Supported since v1; basic linking & hoisting Enhanced, first-class workspaces: smarter hoisting, constraints, and cross-package linking Choose Berry for streamlined monorepo workflows and consistent tooling management
Editor & Tooling Integration Auto-works via node_modules, widely compatible Requires SDKs for editors with PnP: for VS Code, run yarn dlx @yarnpkg/sdks vscode Ensure proper TypeScript/ESLint integration by enabling PnP SDKs
Plugin & Extensibility Limited to built-in features Fully modular, extensible with a powerful plugin API ecosystem Extend Yarn Berry easily without forking—ideal for custom or enterprise requirements
Migration Complexity Low—no major config changes for upgrading May require .yarnrc.yml updates, PnP compatibility adjustments, and some tool validation Review project and toolchain readiness before migrating to Yarn Berry, especially in complex setups

Expert Tip:
If a required tool does not yet support Plug’n’Play, you can easily revert to classic node_modules mode for compatibility. Simply adjust your .yarnrc.yml configuration:

# .yarnrc.yml
nodeLinker: node-modules

This flexibility enables you to take advantage of Yarn Berry’s latest innovations while maintaining compatibility with legacy development tools.

By understanding these distinctions, teams can confidently select the right version of Yarn for secure, efficient, and reproducible Node.js development.

How do I check which packages are outdated?

Run:

  1. yarn outdated

This lists packages with available updates, showing the current version, wanted version (based on your version range), and latest version.

Can I use Yarn with other package managers?

While technically possible, it’s not recommended to use multiple package managers in the same project simultaneously. The lock files (yarn.lock, package-lock.json, pnpm-lock.yaml) serve different purposes and could conflict.

If you must switch between package managers, ensure you:

  1. Delete all lock files and dependency directories
  2. Use the new package manager to generate a fresh lock file
  3. Update your team on the switch
  4. Update CI/CD pipelines to use the new package manager

Conclusion

In this tutorial, you installed Yarn globally and configured a project-specific version, learned essential Yarn commands including installation, adding and removing dependencies, and explored Yarn’s unique features. You also gained insight into when Yarn might be preferable to npm, particularly for projects requiring deterministic builds, monorepo support, or improved performance with large dependency trees.

The two-tier installation model ensures consistent behavior across development environments, making Yarn an excellent choice for teams and production deployments. Whether you’re managing dependencies for a simple application or a complex monorepo, Yarn’s advanced features like Plug’n’Play mode and workspace support provide flexibility and performance benefits.

For more information on using Yarn, explore the official Yarn CLI documentation and Yarn’s migration guide.

For more general Node.js and JavaScript help, visit our Node.js and JavaScript tag pages, where you’ll find relevant tutorials, tech talks, and community Q&A.

Further Learning

References

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Brian Boucheron
Brian Boucheron
Author
See author profile

Senior Technical Writer at DigitalOcean

Vinayak Baranwal
Vinayak Baranwal
Editor
Technical Writer II
See author profile

Building future-ready infrastructure with Linux, Cloud, and DevOps. Full Stack Developer & System Administrator @ DigitalOcean | GitHub Contributor | Passionate about Docker, PostgreSQL, and Open Source | Exploring NLP & AI-TensorFlow | Nailed over 50+ deployments across production environments.

Still looking for an answer?

Was this helpful?


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

use “yarn add” instead of “yarn install”

Can add a section about Yarn adding and managing global packages? I’m stuck and searching for resources.

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.