How can I provide credentials automatically for npm login command in a bash script?

I need help with automating npm authentication in my bash script. I’m creating a script that sets up a custom npm registry and everything works fine until I reach the login step.

Here’s what I’m doing:

# Configure custom registry
npm config set registry http://myserver:8080

# Login to registry
npm login --registry=http://myserver:8080/

The problem is that the npm login command prompts for username and password interactively. I need to pass these credentials automatically since this is running in an automated script. Is there a way to provide the username and password without manual input? I’ve tried a few approaches but haven’t found a working solution yet.

I use the .npmrc file method - it’s the cleanest way. Skip the interactive prompts and generate the auth token yourself, then add it straight to your config. Get your base64 credentials: echo -n 'username:password' | base64. Then write the auth token to .npmrc in your script: bash echo "//myserver:8080/:_authToken=your_token_here" >> ~/.npmrc npm config set registry http://myserver:8080 This skips the login command completely. I’ve run this in production CI/CD for 2+ years with zero problems. Just handle credentials securely - use environment variables or a secrets manager. The token stays valid until you revoke it, so you won’t need to regenerate it much.

You can pipe credentials directly into npm login using a here document or expect utility. Here document works for basic setups:

npm login --registry=http://myserver:8080/ << EOF
username
password
[email protected]
EOF

This method sometimes fails with different npm versions or terminal configs though. I’ve had better luck with the expect command. Install expect first, then create a small script that handles the interactive prompts. This works consistently across different environments and npm versions. Store your credentials in environment variables instead of hardcoding them for security. Expect gives you better timeout handling and error detection than piping input directly.