Vercel monorepo: properly cache Yarn installs

May 4, 2024

So you have a Vercel app that’s part of a monorepo. You may have noticed that by default it installs the whole monorepo dependencies, and you may have already addressed that!

But either way, you have another problem: Yarn downloads all your dependencies on every single build. That’s pretty time consuming. It doesn’t seem that dependencies are getting cached at all.

Vercel recommends setting a ENABLE_ROOT_PATH_BUILD_CACHE=1 environment variable to make build times faster in monorepos.

It sounds great, but in my experience it didn’t do anything, and I’m not the only one.

It seems that regardless of ENABLE_ROOT_PATH_BUILD_CACHE, Vercel doesn’t cache Yarn’s cache folder .yarn/cache, and Yarn 3 and greater will download everything again if this directory is not present, regardless of the state of node_modules.

So the key is to force Yarn’s cache folder to be inside a directory that Vercel actually caches.

I tried setting it inside the root node_modules by doing YARN_CACHE_FOLDER=../../node_modules/.yarn-cache yarn workspaces focus, which worked at first, but quickly encountered some issues when the cache was reused across different build states.

Luckily, thanks to this comment on a totally unrelated issue, I discovered I could put the cache in .next/cache instead, and I never had issues since then!

  "installCommand": " yarn workspaces focus"

Want to leave a comment?

Start a conversation on Twitter or send me an email! 💌
This post helped you? Buy me a coffee! 🍻