Skip to content

Lesson 31 of 50JavaScript at work

Monorepos and Workspaces

Run many apps and packages in one repo with pnpm workspaces, Turborepo or Nx task graphs, shared TypeScript config, Changesets and CODEOWNERS.

20 min read0/4 questions

Your company has a customer web app, an admin dashboard, a docs site and a design system, each in its own repository. Changing a button means a pull request to the design system, a release, then three more pull requests to bump the version in each app, and a week later someone notices the admin app is still two versions behind. A monorepo puts all of that in one repository so one pull request can change the button and every app that uses it, tested together. The price is that a naive monorepo rebuilds and retests everything on every commit, so you need tools that understand which packages depend on which. This lesson covers how workspaces link packages, how task runners like Turborepo and Nx skip work, how TypeScript fits across packages, and the failures you will meet in your first month on a monorepo team.

Why companies choose a monorepo

A monorepo is one repository holding several projects that could, in principle, live apart. It is not the same as a monolith: the apps can still deploy separately. Google and Meta famously keep almost everything in one repo, but most teams you join will have something smaller, often 3 to 40 packages.

What you gain:

  • Atomic changes. Rename a function in a shared package and fix every caller in the same commit. CI tests the whole change at once, so there is never a moment when the library and its users disagree.
  • One version of the truth. Every app uses the current shared code, not whichever version it last remembered to install.
  • Shared tooling. One ESLint config, one TypeScript base config, one CI pipeline, one place to upgrade React.
  • Discoverability. You can search all the code your company owns, and see who calls what before you change it.

What you pay:

  • CI time. Without care, every commit builds and tests everything. This is the problem task runners solve.
  • Ownership. Hundreds of people commit to one repo. You need clear rules about who reviews which folders.
  • Coupling. Because changing shared code is easy, teams change it often, and one breaking change can block five teams at once.
  • Tooling weight. Workspaces, caches and graph tools are more to learn, and a broken cache is harder to debug than a broken script.

The alternative is a polyrepo: one repo per project, sharing code by publishing packages to a registry. That is still a fine choice when teams are truly independent, release on different schedules, or need different access controls.

Workspaces: many packages, one install

A workspace is a folder with its own package.json inside a larger repo. The package manager installs dependencies for all of them in one go and links internal packages to each other instead of downloading them. Every major package manager supports this: npm, Yarn, Bun and pnpm. pnpm is the most common choice for new monorepos, so the examples use it.

A typical pnpm monorepo
  • acme/
  • package.jsonroot: dev tools and scripts only, private: true
  • pnpm-workspace.yamlwhich folders are workspaces
  • pnpm-lock.yamlone lock file for everything
  • turbo.jsontask graph and caching
  • .changeset/pending release notes
  • .github/
  • CODEOWNERSwho reviews which folder
  • apps/
  • web/Next.js customer app
  • package.jsondepends on @acme/ui
  • admin/Vite dashboard
  • packages/
  • ui/shared React components
  • package.jsonname: @acme/ui
  • src/index.ts
  • utils/plain TypeScript helpers
  • tsconfig/shared tsconfig files
  • base.json
  • react-library.json

The split between apps/ and packages/ is a convention, not a rule: apps are things you deploy, packages are things apps import. Workspaces are declared at the root:

pnpm-workspace.yaml
packages:
  - "apps/*"
  - "packages/*"

With npm, Yarn or Bun the same list goes in the root package.json as "workspaces": ["apps/*", "packages/*"].

Depending on an internal package

An app depends on a sibling package like any other dependency, but with the workspace protocol:

apps/web/package.json
{
  "name": "web",
  "private": true,
  "dependencies": {
    "@acme/ui": "workspace:*",
    "@acme/utils": "workspace:*",
    "next": "^16.0.0"
  }
}

workspace:* means "always use the copy in this repo, never the registry". pnpm creates a symlink from apps/web/node_modules/@acme/ui to packages/ui, so edits to the button show up in the app straight away. If you ever publish a package, pnpm rewrites workspace:* to the real version number in the published package.json. pnpm, Yarn and Bun support this protocol. npm does not: with npm workspaces you write a normal version or "*" and npm links the local copy when the name matches.

Give internal packages a scope such as @acme/ so their names never collide with public npm packages, and mark anything you will not publish as "private": true so an accidental publish fails.

Running commands across packages

pnpm install                          # one install for every workspacepnpm --filter web dev                 # run "dev" in one packagepnpm --filter "@acme/ui..." build     # ui and everything it depends onpnpm --filter "...@acme/ui" test      # ui and everything that depends on itpnpm -r build                         # every package, in dependency orderpnpm add zod --filter @acme/utils     # add a dependency to one package

The three dots are worth memorising. Dots after the name follow dependencies downwards. Dots before the name follow dependents upwards, which is exactly the set you must retest after changing a shared package.

One version per dependency

Ten package.json files drift. Soon web has React 19.2 and admin has 19.0. pnpm catalogs fix this: you declare a version once in pnpm-workspace.yaml and each package writes "react": "catalog:". Other teams use a lint tool such as syncpack to flag mismatched versions in CI. Either way, the goal is that upgrading React is one line, reviewed once.

Quick check
You changed @acme/utils and want to run tests in every package that could break because of it. Which command does that?
Need a nudge? A hint rules out a wrong answer.

The task graph: build only what changed

Workspaces solve installing and linking. They do not make CI fast. That is the job of a task runner: Turborepo and Nx are the two you will meet most. Both work the same way underneath.

First they build a package graph from the dependencies in each package.json. Then they combine it with your task definitions into a task graph: "web#build needs ui#build, which needs utils#build". Tasks with no path between them run in parallel.

turbo.json
{
  "$schema": "https://turborepo.com/schema.json",
  "tasks": {
    "build": {
      "dependsOn": ["^build"],
      "outputs": ["dist/**", ".next/**", "!.next/cache/**"]
    },
    "test": { "dependsOn": ["^build"] },
    "lint": {},
    "dev": { "cache": false, "persistent": true }
  }
}

The caret in ^build means "the build task of my dependencies first". Without the caret, dependsOn: ["build"] would mean "my own build first", which is how you say tests need this package built. outputs tells the runner which files to save and restore.

Here is the graph logic in plain JavaScript. Change which package is in the affected calls and see how far a change spreads.

JavaScript
// Each package and the internal packages it depends onconst graph = { "@acme/tsconfig": [], "@acme/utils": ["@acme/tsconfig"], "@acme/ui": ["@acme/utils", "@acme/tsconfig"], "@acme/api-client": ["@acme/utils"], "web": ["@acme/ui", "@acme/api-client"], "admin": ["@acme/ui"], "docs": ["@acme/tsconfig"],}; // Build order: every dependency before the package that needs itfunction buildOrder(graph) { const order = []; const state = {}; // undefined = new, 1 = visiting, 2 = done function visit(name, path) { if (state[name] === 2) return; if (state[name] === 1) throw new Error("cycle: " + [...path, name].join(" -> ")); state[name] = 1; for (const dep of graph[name]) visit(dep, [...path, name]); state[name] = 2; order.push(name); } for (const name of Object.keys(graph)) visit(name, []); return order;} // Affected: the changed packages plus everything that depends on themfunction affected(graph, changed) { const result = new Set(changed); let grew = true; while (grew) { grew = false; for (const [name, deps] of Object.entries(graph)) { if (!result.has(name) && deps.some((d) => result.has(d))) { result.add(name); grew = true; } } } return buildOrder(graph).filter((name) => result.has(name));} console.log("build order:", buildOrder(graph).join(", "));console.log("change utils ->", affected(graph, ["@acme/utils"]).join(", "));console.log("change docs ->", affected(graph, ["docs"]).join(", ")); // Try adding "web" to the deps of "@acme/utils" to see a cycletry { buildOrder({ ...graph, "@acme/utils": ["@acme/tsconfig", "web"] });} catch (e) { console.log(e.message);}
Output
Press Run (⌘ Enter) to see what happens.

That is a topological sort, the same algorithm a real runner uses. Changing docs touches one package. Changing utils touches five. This is why low-level shared packages deserve the most careful review: their blast radius is the largest.

What a change to @acme/utils affects
tsconfigutilsdocsuiapi-clientadminweb

currentwaitingdone

Arrows point from a package to what it depends on. You edit utils.

1/4

Caching: never do the same work twice

The bigger win is the cache. Before running a task, the runner computes a hash of everything that could change its result: the package's source files, its package.json, the lock file entries it uses, relevant environment variables, the command itself, and the hashes of the tasks it depends on. If that hash has been seen before, the runner restores the saved outputs and the logs, and the task finishes in milliseconds.

JavaScript
// A toy version of how Turborepo and Nx decide "cache hit or rebuild"function hash(text) { let h = 0; for (const ch of text) h = (h * 31 + ch.charCodeAt(0)) >>> 0; return h.toString(16);} const files = { "@acme/utils": "export const slug = (s) => s.toLowerCase()", "@acme/ui": "export function Button() {}",};const deps = { "@acme/utils": [], "@acme/ui": ["@acme/utils"] };const cache = new Map(); function taskHash(pkg) { // own inputs + the hashes of everything it depends on const depHashes = deps[pkg].map(taskHash).join(","); return hash(pkg + files[pkg] + depHashes + "cmd:tsc");} function build(pkg) { const key = taskHash(pkg); if (cache.has(key)) return `${pkg}: cache hit (${key})`; cache.set(key, `dist for ${pkg}`); return `${pkg}: built (${key})`;} console.log(build("@acme/utils"), "|", build("@acme/ui"));console.log(build("@acme/utils"), "|", build("@acme/ui"));files["@acme/utils"] += " // tweak";console.log(build("@acme/utils"), "|", build("@acme/ui"));
Output
Press Run (⌘ Enter) to see what happens.

Notice that editing utils also changed the hash of ui, even though no file in ui changed. Including dependency hashes is what keeps the cache honest.

A local cache lives on your machine. A remote cache is shared storage that CI and every developer read from, so if CI already built main, your first build after git pull is mostly cache hits. Turborepo can use Vercel's remote cache or a self-hosted one; Nx has Nx Cloud or self-hosted options.

Two settings matter most, and getting them wrong causes the worst bugs:

  • Missing outputs. If outputs does not list a folder the build writes, a cache hit restores nothing and the next step fails with "file not found", but only on cache hits, so it looks random.
  • Missing inputs. If a build reads an environment variable the runner does not know about, the hash ignores it. Change API_URL, get a cache hit, and ship a build pointing at the old URL. Turborepo has an env key per task for exactly this.

Affected builds in CI

Caching makes repeated work cheap. Affected detection avoids starting it: compare against the base branch and run tasks only for changed packages and their dependents.

turbo run build test --affected        # Turborepo: changed vs the base branchturbo run build --filter="web..."      # web and its dependenciesnpx nx affected -t build test          # Nx: same ideanpx nx graph                           # open an interactive graph of the repo

Nx goes further than Turborepo in some areas: generators that scaffold packages to the team's standard, module boundary lint rules ("apps may import packages, packages may not import apps"), and splitting tasks across CI machines. Turborepo is smaller and closer to plain package.json scripts. Both are good. The concepts transfer, so learn the graph and the cache, not the brand.

Predict the outputJavaScript

What does this print?

const graph = {
utils: [],
ui: ["utils"],
web: ["ui"],
admin: ["ui"],
docs: [],
};
const changed = new Set(["ui"]);
let grew = true;
while (grew) {
grew = false;
for (const [name, deps] of Object.entries(graph)) {
  if (!changed.has(name) && deps.some((d) => changed.has(d))) {
    changed.add(name);
    grew = true;
  }
}
}
console.log([...changed].join(","));
Need a nudge? Hints walk you through it.

TypeScript across packages

Share the config

Put base settings in a package of their own and extend them:

packages/tsconfig/base.json
{
  "compilerOptions": {
    "strict": true,
    "target": "es2024",
    "module": "esnext",
    "moduleResolution": "bundler",
    "verbatimModuleSyntax": true,
    "isolatedModules": true,
    "skipLibCheck": true
  }
}
packages/ui/tsconfig.json
{
  "extends": "@acme/tsconfig/react-library.json",
  "compilerOptions": { "outDir": "dist" },
  "include": ["src"]
}

extends merges compilerOptions option by option. include, files and exclude are not merged: a child's list replaces the base list entirely, and relative paths in the base file resolve from the base file's folder, so "include": ["src"] in a shared package would point at the wrong place. That is why each package keeps its own include. references are never inherited at all. Since TypeScript 6.0, types defaults to an empty list, so a package that uses Node globals must list "types": ["node"] itself.

Just-in-time or compiled packages

There are two ways to ship an internal package to the apps that use it:

Just-in-timeCompiled
exports points at./src/index.ts (source)./dist/index.js plus .d.ts files
Who compiles itThe app's bundler (Next.js, Vite)The package's own build task
SetupMinimal, no build stepA build script and outputs to cache
Editor go-to-definitionLands in the sourceNeeds declaration maps to reach the source
Cacheable workNone for the package itselfIts build is cached and reused
Publishable to npmNoYes

Just-in-time packages are the quickest start and very common inside app-only monorepos. The cost is that every app recompiles the shared code, and type errors in a package only show when an app type-checks it. Some frameworks need to be told to compile a workspace package (Next.js has transpilePackages; check the docs for your version). Compiled packages are more setup, but their builds are cached, and they are required for anything you publish.

Project references

For compiled packages, project references let tsc understand the package graph. Each referenced package sets "composite": true, and the consumer lists what it depends on:

apps/web/tsconfig.json
{
  "extends": "@acme/tsconfig/base.json",
  "references": [{ "path": "../../packages/ui" }, { "path": "../../packages/utils" }]
}

Then tsc -b (build mode) checks packages in order, writes .tsbuildinfo files, and skips any package whose inputs have not changed. It is the TypeScript-only version of the task graph above. Many Turborepo setups skip references and let each package run its own tsc --noEmit; large Nx and Turborepo repos often use both. The TypeScript toolchain lesson covers composite, incremental builds and the faster native compiler in more detail.

Releasing and owning code

Versioning with Changesets

If your packages are only used inside the repo, they need no versions at all. If you publish some of them, Changesets is the standard tool. It turns "what changed and how big was it" into a file written at the time of the change, by the person who made it.

Put it in order4 steps

Put the Changesets release flow in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

CODEOWNERS

A CODEOWNERS file maps paths to the people or teams who must review changes there. Combined with branch protection that requires code owner approval, it is how a monorepo keeps team boundaries without separate repos.

.github/CODEOWNERS
# The last matching line wins
*                     @acme/platform
/apps/web/            @acme/web-team
/apps/admin/          @acme/internal-tools
/packages/ui/         @acme/design-system
/packages/tsconfig/   @acme/platform

How monorepos break

These are the failures you will actually debug.

Phantom dependencies. npm and Yarn's classic layout hoist packages into the root node_modules, so web can import "lodash" even though only admin depends on it. It works until admin drops lodash, then web breaks for no visible reason, or web is deployed alone and the package is missing. pnpm's strict layout only lets a package see what it declares, which turns phantom imports into immediate errors. The fix is always the same: declare what you import.

Duplicate React. A shared ui package lists react in dependencies, a slightly different version gets installed for it, and now the app has two copies of React. Hooks crash with "Invalid hook call", or context from one copy is invisible to components using the other. A library that must share one instance with its host (React, a router, a styling engine) belongs in peerDependencies, with a devDependency for local work. Then check with pnpm why react that only one version is installed.

Circular packages. utils imports from ui "just for one type", and ui already imports utils. Now there is no valid build order; the runner refuses to build, or builds in an order that uses stale output. Fix it by moving the shared piece into a lower package both can depend on.

Deploying one app. A Docker image for web should not contain every package's source. turbo prune web --docker writes out a trimmed copy of the repo with only web and its dependencies, plus a pruned lock file, so the image installs and builds just that slice.

Match the pairs0/5 matched

Match each symptom to its most likely cause.

Choose an item, then its match on the other side.
Key terms
monorepo
One repository holding several apps and packages that are built and versioned together.
workspace
A package inside a monorepo that the package manager installs and links alongside the others.
workspace protocol
workspace:* in a dependency: always link the local package, never download it from the registry.
task graph
Tasks per package plus their order, built from the package dependency graph; independent tasks run in parallel.
remote cache
Shared storage of task outputs keyed by an input hash, so CI and developers reuse each other's builds.
affected
The changed packages plus every package that depends on them, directly or indirectly.
phantom dependency
A package you import without declaring it, which only works because hoisting put it within reach.