By Brian Boucheron and Vinayak Baranwal
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:
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.
node_modules directories entirely, dramatically reducing installation times and disk usageyarn.lock file guarantees identical dependency trees across different machines and environments, preventing “works on my machine” issuesBefore 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.
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.
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
Output1.22.22
Now that you have the yarn command installed globally, you can use it to install Yarn into a specific JavaScript 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:
OutputResolving 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
Output4.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.
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.
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.
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.
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.
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.
Install Express and create a tiny server:
- yarn add express
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
Expected outputYarn is working!
.gitignore File for YarnYarn 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:
.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.
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
.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:
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.
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.
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.
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.
yarn install --immutable to fail builds if the lockfile doesn’t match, guaranteeing identical artifacts..yarnrc.yml (e.g., caFile, npmScopes) and keep CI in sync with the repo config.Yarn’s workspace feature is more mature and integrated than npm’s equivalent. Monorepos benefit from:
yarn dlx @yarnpkg/sdks vscode enables TypeScript/ESLint to understand PnP without node_modules.Choose Yarn when:
Stick with npm when:
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.
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.
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.
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_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
The yarn.lock file should be committed to version control. When multiple team members add dependencies, you’ll encounter merge conflicts. Resolution strategy:
yarn install to regenerate the lock fileTo 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:
- yarn cache clean
You can also check where Yarn stores cached packages:
- yarn cache dir
.pnp Files and Node.js ResolutionWhen 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.
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.
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.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.
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:
node_modulesMost new projects should use Yarn Berry. The global CLI serves as a launcher for both versions.
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:
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.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Senior Technical Writer at DigitalOcean
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.
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!
Can add a section about Yarn adding and managing global packages? I’m stuck and searching for resources.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.