Private bitbucket repository as npm dependency

In a way that it still works in your choice of Continuous Integration tools.

The Hard Way

By using BitBucket’s SSH deployment keys.

Tom Spencer has written a great post about this and I’ve used his method succesfully.

There’s nothing wrong his this approach, I just found it very complicated (for my specific use case) because it requires generating SSH keys, setting them up in BitBucket, and adding extra scripts in your dependant project that set up the SSH keys in the build environment before it can execute npm install.

The Easy Way

The easiest way I’ve found is by using a teamwide API key. This is basically a way to authenticate to your Team’s repositories with HTTP Basic Auth.

I’m using this method to automatically deploy a React web app to Netlify from my private BitBucket repositories.

Disclaimer: If you don’t trust all the members who have access to the dependant repository: Use the “Hard Way” above. Unlike the “Easy Way”, it doesn’t reveal teamwide access code in the package.json, instead it uses per repository Deployment Keys.*

Generating the API key

To generate an API key, go to BitBucket and navigate to: manage team > access management > API key.

If there’s already a key there, you can use that. If not, click Generate Key.

Adding the dependency to package json

Let’s imagine your team name is awesometeam and the key you found or generated in the previous step is now Djuv1uCnosHdom674BcHV.

Execute the following npm install command, replacing the placeholders with your team name, your team’s API key, and your repository name:

npm install git+https://awesometeam:Djuv1uCnosHdom674BcHV@bitbucket.org/awesometeam/oursharedcode.git --save-dev

Hint: If you want your package to depend on an exact version of the oursharedcode, you can add #commit or #tag to the end of the URL.

I hope that worked. Let me know how it went in the comments section below.

Bonus: Automatically building the dependency on install

If you don’t want to pre-build/transpile the npm dependency and push the built code to git, you can setup a process to build it automatically when another project installs it as a dependency.

I used postinstall-build for this:

npm install --save postinstall-build

After that, I added following scripts to the package.json in the dependency repository:

  "scripts": {
    "build-lib": "[YOUR BUILD STUFF HERE]",
    "postinstall": "postinstall-build lib 'npm run build-lib'"
  },

Voilà.

Anything else?

If you have questions or found any mistakes in this post, please leave a comment.