Table of Contents
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.
[info]
Deploy your frontend applications from GitHub using an app platform. Let the cloud provider 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_modulesdirectories entirely, dramatically reducing installation times and disk usage
- Deterministic Installs: The
yarn.lockfile 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
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:
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.
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:
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:
yarn --version
[secondary_label 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:
cd <^>~/my-project<^>
If you don't have a project directory, you can make a new one with mkdir and then move into it:
mkdir <^>my-project<^>
cd <^>my-project<^>
Now use the yarn set command to set the version to berry:
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:
[secondary_label 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:
yarn --version
[secondary_label 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:
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:
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:
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:
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:
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:
yarn add express
[label 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:
yarn node index.js
Verify it responds:
curl http://localhost:3000
[secondary_label 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:
[label .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:
yarn remove <^>package-name<^>
Updating dependencies:
yarn upgrade [package-name]
Listing installed packages:
yarn list --depth=0
Checking for outdated packages:
yarn outdated
Running scripts defined in package.json:
yarn run <^>script-name<^>
Cleaning the cache:
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:
[label .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 topnp(Plug'n'Play, which eliminates thenode_modulesfolder),pnpm(similar to the pnpm manager’s symlinked structure), ornode-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.0disables compression entirely (faster, but uses more space),1fully compresses all packages, andmixedapplies compression only where it makes the biggest impact. Recommendation: Usemixed(the default) for most projects as it provides a good balance. Use0only if you have abundant disk space and prioritize installation speed. Use1if disk space is constrained.
enableGlobalCache: When set totrue, 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. Whenfalse, 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 --immutableto 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 vscodeenables TypeScript/ESLint to understand PnP withoutnode_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:
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:
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:
mkdir ~/.npm-global
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:
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:
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:
- Use compatible tools: Yarn maintains a tool compatibility list
- Enable the SDK: Some editors require explicit SDK setup:
yarn dlx @yarnpkg/sdks vscode
- Switch to
node_modulesmode:
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:
- Choose one branch as the source of truth
- Run
yarn installto regenerate the lock file
- Commit the regenerated lock file
To prevent future conflicts, adopt a workflow where dependency changes go through a single person or a bot.
Cache-Related Issues
If Yarn starts behaving unexpectedly or packages seem outdated, clear the cache:
yarn cache clean
You can also check where Yarn stores cached packages:
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
The recommended way to install Yarn globally is using npm:
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.
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.
For the global Yarn CLI:
npm install -g yarn@latest
For project-specific Yarn versions, navigate to your project directory and run:
yarn set version latest
Or to set a specific version (e.g., berry for Yarn 4.x):
yarn set version berry
Yes, you can switch to Yarn in an existing npm project. Navigate to your project directory and run:
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.
[warning]
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.
- Deterministic builds: The
yarn.lockfile 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_modulesentirely, dramatically reducing disk usage and improving performance in constrained environments.
Use the remove command:
yarn remove <^>package-name<^>
This removes the package from package.json, deletes it from yarn.lock, and uninstalls it from your project.
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.
Run:
yarn outdated
This lists packages with available updates, showing the current version, wanted version (based on your version range), and latest version.
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:
- Delete all lock files and dependency directories
- Use the new package manager to generate a fresh lock file
- Update your team on the switch
- 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
- Yarn Official Documentation: Comprehensive guides on using Yarn for modern web development
- Yarn CLI Reference: Complete command reference for all Yarn subcommands
- Plug'n'Play (PnP) Guide: Understanding and using Yarn's PnP mode
- Yarn Workspaces: Managing monorepos and multiple packages with Yarn
- Migration Guide: Switching from npm or upgrading between Yarn versions
- Yarn Installation Alternatives: Additional installation methods for different platforms
References
- Yarn GitHub Repository: Source code and issue tracking
- Node.js Documentation: Learn more about Node.js and npm
- package.json Reference: Understanding package.json structure and fields
- Semantic Versioning: How package versions work in Node.js
- the cloud provider's Node.js Resources: Additional Node.js tutorials and guides