Skip to content

    Frontend System Design

    Monorepos and Shared Libraries

    How a front-end monorepo shares code: workspaces, the package graph, affected builds and caching, tag rules for boundaries, and when sharing costs too much.

    By Published 13 min read

    • frontend-system-design
    • monorepo
    • workspaces
    • shared-libraries
    Share

    Standard lessonintermediateTypeScript labFrontend System Design

    Before this: Module Boundaries and Public APIs

    What you'll learn: By the end of this lesson you will be able to say what a monorepo is and what it is not, describe how workspaces turn folders into linked packages, read a package dependency graph, explain how tools decide which packages a change affects and what they cache, choose between source-shared and compiled shared libraries, keep versions and boundaries under control, and judge when a shared library is worth its cost.

    A neighbourhood has a tool shed. Everyone on the street can borrow the ladder, so nobody buys a fourth ladder. But the shed only works with rules: a list of what is inside and a way to see who borrowed the drill. Without them, things get lost and everyone buys their own saw again.

    A monorepo is a shed for code. Several applications and libraries live in one repository so they can share code and change together. The running example is a storefront: a customer app, an admin app, three feature packages, four shared packages and one tooling package (the lab's workspace, ten in all). Module Boundaries and Public APIs set the rules inside one app; this lesson moves the same ideas up one level, to packages.

    The core idea

    1. A monorepo is one repository with many packages, not one big build. Each package keeps its own package.json, its own dependencies and its own public API. The repository is the unit of storage; the package is the unit of design.
    2. The package graph is the shared fact. Package managers link local packages into each other, and build tools read the graph to decide the order of work, what a change affects and what can be reused from cache.
    3. Sharing has a price. A shared package has many readers, so a change to it has many consequences. Share what is stable and understood by everyone; leave the rest inside the app that needs it.

    Three illustrations run through the lesson: a minimal one (two packages and one link), a realistic one (the lab's ten-package storefront) and a failure (two bad edits to the same workspace).

    What a monorepo is, and what it is not

    Turborepo's documentation says it is built on top of workspaces, "a feature of package managers in the JavaScript ecosystem that allows you to group multiple packages in one repository". npm lists paths in the workspaces property of package.json and, after npm install at the root, symlinks a folder such as packages/a into node_modules so it can be used by name. pnpm uses a file at the workspace root, pnpm-workspace.yaml, whose packages field "lists the directories of the workspace's projects".

    Illustration 1 (minimal): two packages and one link.

    # pnpm-workspace.yaml
    packages:
      - "apps/*"
      - "packages/*"
    {
      "name": "@shop/storefront",
      "dependencies": { "@shop/ui": "workspace:*" }
    }

    The workspace: protocol is the explicit link. pnpm's documentation says that when it is used, "pnpm will refuse to resolve to anything other than a local workspace package". On publish, workspace:* becomes the target's real version (the page's example turns it into 1.5.0). Without the protocol, pnpm links a workspace package only if linkWorkspacePackages is on, and its default is false, so a plain range such as ^1.2.0 can quietly resolve to the registry copy instead of your local code.

    Turborepo's repository guide recommends apps/ for applications and services and packages/ for everything else, and says to "avoid accessing files across package boundaries as much as possible": a ../ from one package into another is a link the package manager cannot see.

    A monorepo is therefore not automatically one deployable or one team. Whether the apps ship together is a separate decision (see Independent Deployment and Shared Dependencies).

    Figure 1. The storefront workspace as a layout

    Apps depend on feature and shared packages; shared packages depend on nothing above themstorefront to features (workspace:*); admin to features (workspace:*); features to shared (workspace:*)APPS/PACKAGES/storefront: appstorefrontappadmin: appadminappfeatures: cart, catalog, authfeaturescart, catalog,authshared: ui, tokens, apisharedui, tokens, apiworkspace:*workspace:*workspace:*

    How to read this: arrows point from user to used. Nothing depends on an app, and shared packages depend on no feature. The lab's exact edges are in the demo output below; this drawing groups packages to show the direction.

    The package graph

    From the manifests the tools build a graph: a node per package, an edge from A to B when A lists B as a dependency. Nx says it works out most dependencies "from source code, installed dependencies, and TypeScript configuration"; the lab reads only declared dependencies, so it is a smaller model. The graph gives three answers:

    • Order. pnpm's recursive commands run "in topological order: dependencies run before their dependents", and in Turborepo dependsOn: ["^build"] makes a package's build wait for the task in its direct dependencies. Packages with no path between them can run in parallel (the lab calls these waves).
    • Reach. In pnpm's filter syntax ...pkg selects a package and its dependents, and pkg... a package and its dependencies.
    • Cycles. With a cycle there is no order in which each package comes after its dependencies. The lab refuses to produce one, and a person cannot reason about the pair separately either (see the cycles section of the module-boundaries lesson).

    What gets rebuilt: affected selection and caching

    The question on every pull request is: what do I rebuild and retest? Everything is the safe answer and the slow one. Tools narrow it two ways.

    Affected selection starts from the changed files. pnpm's --filter "[<since>]" "selects all the packages changed since the specified commit/branch". Turborepo's --affected is by default "equivalent to --filter=...[main...HEAD]" and "operates at the package level: if any file in a package changed, all of its tasks are selected". Nx "selects each build and test task whose inputs include a changed file", and says Nx 23 and earlier use project-based affected, where "a change to a project runs every task of that project and of every project that depends on it". So there are two granularities: packages and their dependents, or tasks and their declared inputs.

    Caching skips repeated work. Turborepo hashes a task's inputs into a "fingerprint"; if the global hash or the task hash changes, "the task will miss cache", otherwise it restores the declared outputs and replays the logs. Without outputs, "Turborepo will not cache any files", and Remote Caching shares a cache "among your entire team and CI".

    Figure 2. From a diff to a run

    flowchart LR accTitle: How a monorepo tool turns a diff into a run accDescr: A git diff lists changed files. Each file is mapped to its owning package, or flagged as a global file. The tool adds the dependents of the changed packages, orders the affected packages by the dependency graph, and runs each task or restores it from cache when its inputs hash is unchanged. A["git diff
    changed files"] --> B{"Global file?
    lockfile, shared config"} B -->|"yes"| E["everything is affected"] B -->|"no"| C["owner package
    of each file"] C --> D["add dependents
    (transitive)"] D --> F["order by graph
    dependencies first"] E --> F F --> G{"inputs hash
    seen before?"} G -->|"yes"| H["restore from cache"] G -->|"no"| I["run the task"]

    How to read this: the first steps are cheap path and graph work. Only the last diamond decides whether real work runs. A global file skips the narrowing and sends everything to the order step.

    On the global-file branch, Nx documents that "by default, a change to your package manager's lock file affects every task", and offers projectsAffectedByDependencyUpdates: "auto" to limit that to projects whose resolved dependencies changed.

    Shared libraries: what to share and how to ship it

    A shared library is a package that two or more others depend on: a design-system package, design tokens, an API client, analytics, lint config. Two decisions matter.

    What to share. Share things that change for the same reason in every consumer and mean the same everywhere: tokens, primitives, the typed API client. Be wary of sharing business rules between features: two features that look alike often change independently.

    How to ship it. Turborepo lists three strategies for packages inside a workspace:

    Strategy What it means Cost
    Just-in-time The consuming app's bundler compiles the package's source Least configuration; consumers must transpile TypeScript; Turborepo "cannot cache a build" for it
    Compiled Built with tsc or a bundler; consumers import the output A build step and a cache entry
    Publishable Prepared for the npm registry "The most strict requirements"; needed only for outside consumers

    Just-in-time works by pointing the exports field at TypeScript files, which suits small internal packages but means every consumer's toolchain must understand the source.

    Versions. A workspace usually wants one version of each third-party dependency. pnpm's catalogs define a range once in pnpm-workspace.yaml and packages write catalog: instead; duplicates "can conflict at runtime and cause bugs", and an upgrade becomes one edit.

    TypeScript. Project references (see Tools and further reading) treat each package as its own project: referenced projects set composite, and tsc --build builds out-of-date projects "in the correct order".

    Boundaries between packages

    Packages give a monorepo the walls that Module Boundaries and Public APIs asked for: a package's exports field is its public API, and the manifest is the declaration of who may use whom. Nx adds tags: annotate projects with tags, then write depConstraints in the lint rule, where sourceTag names the importer and onlyDependOnLibsWithTags lists what it may use. Nx's page says "Projects without any tags cannot depend on any other projects" (unless the rule allows *), so an untagged package is a gap. The lab models a simplified version of the rule.

    Figure 3. Allowed directions between tags

    App packages may depend on features; features on shared packages; shared packages only on shared and toolingscope:app to scope:feature (allowed); scope:feature to scope:shared (allowed); scope:feature to scope:tooling (allowed); scope:shared to shared imports feature (rule fails)scope:app: may use all belowscope:appmay use all belowscope:feature: may use shared, toolingscope:featuremay use shared,toolingscope:shared: may use shared, toolingscope:sharedmay use shared,toolingscope:tooling: lint and build configscope:toolinglint and buildconfigshared imports feature: forbidden edgeshared importsfeatureforbidden edgeallowedallowedallowedrule fails

    How to read this: the edges labelled allowed are the lab's constraints. The failing edge is what the tag rule turns into an error; section 10 of the demo reports one of this kind.

    Trade-offs

    Choice Gains Costs
    One repository Atomic changes across packages; one place for tooling Repository-wide tooling to maintain; a lockfile change affects everything
    Shared library One implementation; consistent behaviour Many readers per change; pressure to add options
    Source-shared vs compiled package Source: no build step. Compiled: clear output, works for plain Node Source: consumers must compile it. Compiled: a build step to keep fresh
    Package-level affected Simple, predictable May run tasks a change cannot affect
    Task-input affected Runs only tasks whose inputs changed Inputs must be declared correctly

    Build it: a workspace graph with affected selection

    Setup. The lab is examples/frontend/labs/workspace-graph. It is a model of what workspace tools know, not pnpm, Nx or Turborepo: it reads package.json-shaped data (name, folder, dependencies, tags) and nothing else, runs no tasks and caches nothing. Its "affected" rule is the package-level one: the packages that own changed files plus everything that depends on them. Its tag rule simplifies Nx's.

    Illustration 2 (realistic): the ten-package storefront.

    cd examples/frontend/labs/workspace-graph
    ../../node_modules/.bin/vitest run    # 32 tests
    ../../node_modules/.bin/tsc -p tsconfig.json
    node src/demo.ts

    Steps.

    1. Read src/workspaces.ts: ten manifests with tags, linked by workspace:*, the GLOBAL_FILES (lockfile, workspace file, shared tsconfig, turbo.json) and the tag constraints.
    2. Read src/graph.ts: buildGraph (dependency and dependent maps, plus a warning for a workspace name with an ordinary range), findCycles (Tarjan's strongly connected components), buildWaves, ownerOf (longest folder that is a path prefix, on a / boundary), affectedBy and checkBoundaries.
    3. Run the demo and read the graph and waves, the change scenarios (3 to 8), then sections 9 and 10.

    Expected output, captured from a real run (Node 26.12.1, 2026-11-08):

    === 1. The graph: who depends on whom
    @shop/admin
      depends on:    @shop/auth, @shop/catalog, @shop/ui
      depended on by: (none)
    @shop/analytics
      depends on:    (none)
      depended on by: @shop/cart, @shop/storefront
    @shop/api-client
      depends on:    @shop/eslint-config
      depended on by: @shop/auth, @shop/cart, @shop/catalog
    @shop/auth
      depends on:    @shop/api-client
      depended on by: @shop/admin
    @shop/cart
      depends on:    @shop/analytics, @shop/api-client, @shop/ui
      depended on by: @shop/storefront
    @shop/catalog
      depends on:    @shop/api-client, @shop/ui
      depended on by: @shop/admin, @shop/storefront
    @shop/eslint-config
      depends on:    (none)
      depended on by: @shop/api-client, @shop/ui
    @shop/storefront
      depends on:    @shop/analytics, @shop/cart, @shop/catalog, @shop/ui
      depended on by: (none)
    @shop/tokens
      depends on:    (none)
      depended on by: @shop/ui
    @shop/ui
      depends on:    @shop/eslint-config, @shop/tokens
      depended on by: @shop/admin, @shop/cart, @shop/catalog, @shop/storefront
    
    === 2. Build order: waves, dependencies first
    wave 1: @shop/analytics, @shop/eslint-config, @shop/tokens
    wave 2: @shop/api-client, @shop/ui
    wave 3: @shop/auth, @shop/cart, @shop/catalog
    wave 4: @shop/admin, @shop/storefront
    
    === 3. Change: a design token changes
    files:    packages/tokens/src/colors.ts
    changed:  @shop/tokens
    affected: @shop/admin, @shop/cart, @shop/catalog, @shop/storefront, @shop/tokens, @shop/ui [6 of 10]
      run wave 1: @shop/tokens
      run wave 2: @shop/ui
      run wave 3: @shop/cart, @shop/catalog
      run wave 4: @shop/admin, @shop/storefront
      reusable from an earlier run: @shop/analytics, @shop/api-client, @shop/auth, @shop/eslint-config
    
    === 4. Change: the analytics package changes
    files:    packages/analytics/src/track.ts
    changed:  @shop/analytics
    affected: @shop/analytics, @shop/cart, @shop/storefront [3 of 10]
    
    === 5. Change: only the admin app changes
    files:    apps/admin/src/App.tsx
    changed:  @shop/admin
    affected: @shop/admin [1 of 10]
      run wave 1: @shop/admin
      reusable from an earlier run: @shop/api-client, @shop/auth, @shop/catalog, @shop/eslint-config, @shop/tokens, @shop/ui
    
    === 6. Change: the shared ESLint config changes
    files:    tooling/eslint-config/index.js
    changed:  @shop/eslint-config
    affected: @shop/admin, @shop/api-client, @shop/auth, @shop/cart, @shop/catalog, @shop/eslint-config, @shop/storefront, @shop/ui [8 of 10]
    
    === 7. Change: the lockfile changes
    files:    pnpm-lock.yaml
    changed:  (none)
    affected: everything (a global file changed) [10 of 10]
    
    === 8. Change: a README and a folder no package owns
    files:    README.md, packages/ui-extras/readme.md
    changed:  (none)
    affected: (none) [0 of 10]
    unowned:  README.md, packages/ui-extras/readme.md
    
    === 9. Boundary rules on the healthy workspace
    violations: (none)
    untagged:   (none)
    
    === 10. The same workspace after two bad edits
    cycles: @shop/catalog <-> @shop/ui
    violation: @shop/ui (scope:shared) must not depend on @shop/catalog [scope:feature]
    warning: @shop/auth depends on "@shop/api-client" with "^1.2.0", which is not a workspace: spec, so it is not linked
    build order: Cannot order packages: cycle @shop/catalog <-> @shop/ui

    What the output shows.

    • Reach follows the graph, not the folder. A token change (scenario 3) touches one package but affects 6 of 10, because ui depends on tokens and four packages depend on ui. The other four are listed as reusable from an earlier run: a real tool would restore their results from cache, which this model does not have.
    • Small packages can have wide reach. A lint-config change (scenario 6) affects 8 of 10. Under a task-input rule such as Nx's, the answer would depend on whether lint config is a declared input of each task; the package-level rule cannot tell.
    • Global and unowned files. The lockfile (scenario 7) affects all 10. A file no package owns (scenario 8) affects none and is listed as unowned, a prompt to ask who should own packages/ui-extras.

    Illustration 3 (failure): two bad edits. Section 10 makes two small edits to the healthy workspace: @shop/ui starts using @shop/catalog, and @shop/auth lists @shop/api-client as ^1.2.0 instead of workspace:*. The cycle catalog <-> ui has no valid build order (the lab throws and says so), the tag rule reports the shared-to-feature edge, and the warning says the registry range is not linked, which models pnpm's documented default.

    Break it. In src/graph.ts, in ownerOf, change path.startsWith(`${dir}/`) to path.startsWith(dir). A file in packages/ui-extras now counts as a file of packages/ui, so a change nobody owns makes @shop/ui and its dependents rebuild. One test fails and scenario 8 changes. Revert it and re-run the tests. Stretch. Add task inputs to the manifests and select by whether a changed file matches one, then write a test where that rule and the package-level rule disagree.

    In practice: two apps stop copying components

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A storefront and an admin app live in two repositories (illustrative). Both carry their own copy of buttons, form fields and an API client, and the copies have drifted: a bug fixed in one is still present in the other, and a token change takes two pull requests.

    Starting architecture

    Figure 4. Starting point: two repositories, two copies

    Starting architecture: each app carries its own copy of the UI and API clientstorefront repo to two CI pipelines (every push); admin repo to two CI pipelines (every push); two CI pipelines to deploystorefront repo: own ui copystorefrontrepoown ui copyadmin repo: own ui copyadmin repoown ui copytwo CI pipelines: run everythingtwo CIpipelinesrun everythingdeploy: per appdeployper appevery pushevery push

    How to read this: nothing links the two copies, so the drift is invisible to tooling.

    Options considered

    Option Attraction Risk
    Two repositories, a UI package on a registry Strong versioning Every fix needs a release and an upgrade in each app
    One workspace One pull request changes the library and its users Needs affected selection, caching and tag rules to stay fast
    Copy by hand Zero setup The drift continues

    The decision

    Field Decision record
    Context Two apps duplicate UI and API code, and fixes do not travel.
    Decision One pnpm workspace with apps/ and packages/; extract ui, tokens and api-client; link with workspace:*; one catalog for React and TypeScript; tags on every package with a lint rule; CI runs affected tasks with caching.
    Consequences, good A token change is one pull request; the graph shows who is affected.
    Consequences, bad A change to ui can affect both apps; global files rebuild everything; shared packages need an owner.
    Revisit when Shared packages grow options that only one app uses.

    Rollout and verification

    1. Move one app in, then the second, and verify the build before extracting anything.
    2. Extract tokens first, the smallest package with the clearest meaning, link it with workspace:* and confirm the graph has no cycle.
    3. Tag every package before turning the lint rule on: an untagged package has no rule.
    4. Declare outputs for each cached task and check that a second run is served from cache.

    The 2 a.m. failure

    The main branch fails to build at 2 a.m. The pull request that caused it passed. A developer had imported ../../packages/ui/src/Button from an app file by relative path and never declared @shop/ui as a dependency. A tool that reads only declared dependencies (like the lab's model) cannot see that edge, so a later ui change left the app out of the affected set (illustrative).

    First three checks: (1) compare the failing app's imports with its package.json; (2) search for ../ paths that cross a package folder; (3) read the affected list for the change that broke it. Mitigation: declare the dependency and import by package name. Follow-up: a lint rule against relative imports that leave a package.

    Architect's notes

    • Make the package graph printable. If nobody can print it, nobody can say what a change affects.
    • Treat global files as expensive; keep the list short.
    • Share the stable, not the similar. Extract after a second real consumer exists.
    • Give every shared package an owner and a small public API.

    Common mistakes

    • Believing a monorepo means one build. What builds and deploys together is still a decision.
    • Using a plain version range for a local package, so the registry copy may be installed instead of the workspace one.
    • Importing across packages by relative path. The graph cannot see it.
    • A shared or utils package that collects everything.
    • Caching a task without declaring its outputs.
    • Leaving packages untagged, which leaves them outside every rule.

    Key takeaways

    • A monorepo stores many packages in one repository; each package keeps its own manifest and public API.
    • Workspaces link local packages; the workspace: protocol makes the link explicit.
    • The package graph gives build order, reach (dependents) and cycle detection.
    • Affected selection may be package-level or task-input-level; caching needs declared inputs and outputs.
    • A shared library has many readers; share the stable and ship it as source, compiled or published as the consumers need.
    • Tags and manifests are the boundaries between packages; relative paths across packages bypass them.

    Practice exercises

    Exercise 1 (Starter, 30 min): Draw the dependency graph of a repository you know. Find the package with the most dependents and predict what a change to it affects.

    Exercise 2 (Intermediate, 2 hours): In the lab, add @shop/search, tagged scope:feature, depending on @shop/ui. Predict the waves and the affected list for a token change, run the demo and explain any difference.

    Exercise 3 (Advanced, half day): Implement the stretch: input globs per package and selection by input match. Write a test where it and the package-level rule disagree, and say which you would trust for a lint-config change.

    In this course:

    Official documentation

    Tools and further reading

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments