All Articles

Re-using a single Redis connection and avoiding race conditions on startup




When you try to use npm link to install a dependency you’re working on locally, the changes aren’t reflected in your project.

You also see intermittent issues starting your project (esp. in TypeScript), as well as subdependencies not resolving correctly.



There are two issues you can run into when npm link isn’t working which are worth noting;

  1. nvm related issues
  2. Peer Dependency related issues


nvm, or Node Version Manager, is a tool used to run different versions of node locally across microservices at the same time.

When running npm link, the specific version of node being used in the project will be used to create the link, which means only projects using the same version of node will be able to access the local version of the dependency. This can be all the more frustrating because npm link doesn’t throw an error when this happens.

Here’s the readout when using different versions of node (one using 8.9.4, the other using 12.13.1):

/Users/myName/dev/_github/myRepo/node_modules/myDependency -> /Users/myName/.nvm/versions/node/v12.13.1/lib/node_modules/myDependency

And here’s the readout with the same version of node (both using 8.9.4):

/Users/myName/dev/_github/myRepo/node_modules/myDependency -> /Users/myName/.nvm/versions/node/v8.9.4/lib/node_modules/myDependency -> /Users/myName/dev/_github/myDependency

Notice how the bottom line resolves to a folder where the dependency resides locally.

To fix this, use node -v in each project and check the running version of node. Use nvm install x.x.x & nvm use x.x.x to match them up.

Afterward, delete your node_modules, delete your package-lock.json, re-run npm i, and re-run npm link in your dependency folder and npm link myDependency in your project folder.

That should help.

Peer Dependencies

If your dependency has references to peerDependencies in it’s package.json you could stumble into issues with symlinks. These manifest themselves in the form of the peerDependency being unablee to be resolved at either compile time or at run time when needed.

The fix for this relatively simple. Add --preserve-symlinks into your start script e.g. node --preserve-symlinks build.

This will instruct your startup script to look in the correct place for it’s peer dependencies when running locally. Note that you’ll want to remove the flag once you’re done testing locally.

Problem (Hopefully) Solved

If you have any questions you’d like to ask me about this post, feel free to reach me on Twitter or Github.

If you found this post useful and would like to show you’re appreciation, join the Brave movement (and send me a tip if you like), or join the Crypto movement at Binance, and / or contribute to green investment at tickr :)