npm EACCES: permission denied when installing packages globally
Fix npm "EACCES: permission denied, mkdir /usr/local/lib/node_modules" without sudo: change the npm folder, use nvm or fix ownership.
This error means npm tried to write to a folder that your user cannot change, usually the system folder for global packages. Running npm with sudo seems to work but it causes more permission problems later. Give npm a folder you own instead.
What to do, step by step
- Read the path in the error. If it is /usr/local/lib/node_modules or /usr/lib, npm is trying to install globally into a system folder.
- The cleanest fix is a Node version manager such as nvm. It installs Node in your home folder, so no sudo is needed.
- Or give npm its own global folder: create it, point npm at it, and add it to your PATH (commands below).
- If the path is inside ~/.npm or your project, an earlier sudo run left root-owned files. Take them back with the chown command below.
- Run the install again without sudo.
Commands you can copy
mkdir -p ~/.npm-global
npm config set prefix ~/.npm-globalexport PATH=~/.npm-global/bin:$PATHsudo chown -R $(id -u):$(id -g) ~/.npmnpm config get prefixOther causes to check
- EACCES on node_modules in your project
- An earlier sudo npm install made root-owned files. Run sudo chown -R $(id -u):$(id -g) node_modules or delete the folder and install again without sudo.
- Docker bind mount, permission denied
- The container user and your user have different IDs. Run the container with your user ID, or fix the ownership of the mounted folder.
- Windows: EPERM or EACCES
- A program such as antivirus or an editor is holding the file. Close it, delete node_modules and try again, or run the terminal as administrator once.
- The command is not found after the install
- The new global folder is not in your PATH. Add ~/.npm-global/bin to PATH in your shell profile.
Questions about npm EACCES permission denied
- Why should I not use sudo with npm?
- Packages and scripts would run as root and can create root-owned files in your home folder. That breaks later installs and is a security risk.
- What is nvm?
- Node Version Manager. It installs several Node versions in your home folder and lets you switch between them, with no sudo.
- Where does npm keep its cache?
- In ~/.npm on Linux and macOS. If it is owned by root, the chown command here fixes it.
Config generators for this
- package.json fileCreate a package.json with the right name, version, module type, scripts and Node version.
- tsconfig.json fileCreate a tsconfig.json for a Node or browser TypeScript project, with strict mode, target and output folder.