Monorepos and Shared Codebases: Turborepo, Nx and Boundaries

When a monorepo helps and when it hurts, how Turborepo and Nx differ, how to draw package boundaries, handle versioning and keep CI fast as the repository grows.

DIDatainter TeamJUN 26, 20269 MIN READTECHNOLOGY

A monorepo is a single repository containing multiple projects: a web app, a mobile app, an API, shared libraries, infrastructure code. The idea is old (large companies have run enormous monorepos for decades), but modern JavaScript and TypeScript tooling has made it accessible to teams of five. The pitch is attractive: share code without publishing packages, change an API and its consumers in one commit, and keep tooling consistent.

The reality is more nuanced. A monorepo does not remove complexity; it moves it from coordination between repositories into build tooling, ownership rules and CI design. This article covers when the trade is worth making, how to organize the code, and how to keep builds fast.

What you gain and what you pay

Benefits

  • Atomic changes. Renaming a function in a shared library and updating all callers happens in one pull request. In a multi-repo setup the same change requires a published version, several PRs and a period of version skew.
  • Code sharing without ceremony. Types, validation schemas, UI components and utilities are imported directly. No registry, no tokens, no waiting for a release.
  • Single source of truth for tooling. One ESLint config, one TypeScript baseline, one dependency policy.
  • Visibility. Engineers can search and read every project, which helps onboarding and cross-team reviews.
  • Simplified dependency management. A single lockfile avoids version drift of the same library across repos.

Costs

  • CI complexity. Without care, every change triggers every build and test.
  • Tooling investment. Someone must own the workspace configuration, caching and developer experience.
  • Coupling temptation. Easy imports make it easy to create a tangled dependency graph.
  • Access control and ownership. Everyone sees everything; if you need to restrict access to parts of the code, a monorepo is harder.
  • Repository size. Git performance degrades with very large histories and many files, although this is rarely an issue for teams under a few hundred engineers.

A monorepo makes the most sense when projects share meaningful code and are released together or by the same people: a Next.js frontend, a Node API, and a React Native app sharing TypeScript types and validation. It makes less sense when teams are independent, release on separate cadences, use different languages and share nothing but a company logo.

Workspaces: the foundation

Modern package managers (pnpm, npm, Yarn) support workspaces: a root package.json or pnpm-workspace.yaml declares where packages live, and the manager links them locally. A conventional layout:

repo/
  apps/
    web/            # Next.js site
    api/            # Node service
    mobile/         # React Native or Capacitor app
  packages/
    ui/             # shared components
    config/         # eslint, tsconfig, prettier presets
    domain/         # types, validation schemas, business rules
    db/             # database client and migrations
  pnpm-workspace.yaml
  turbo.json
  package.json

The apps/ directory holds deployable things; packages/ holds libraries that are consumed by others. Apps may depend on packages. Packages may depend on other packages. Apps never depend on each other. That one rule prevents most tangles.

pnpm is a popular choice because of its strict, content-addressed node_modules layout, which blocks “phantom dependencies” (importing a package you did not declare because it happens to be hoisted) and saves disk space. Use the workspace:* protocol so internal dependencies always resolve to the local copy.

Technology · Monorepos and Shared Codebases: Turborepo, Nx and Boundaries

Turborepo versus Nx

Both tools solve the same two problems: running tasks in dependency order across packages, and not repeating work that has already been done. They differ in philosophy.

Aspect Turborepo Nx
Philosophy Thin task runner on top of your package scripts Full build system with plugins and generators
Configuration turbo.json pipeline nx.json, project configs, plugins
Learning curve Low Moderate to high
Caching Local and remote, content hashed Local and remote, content hashed
Affected detection Filter by git changes (--filter=...[main]) Built-in nx affected using project graph
Code generation Minimal Strong generators and plugins
Language scope JavaScript and TypeScript focus Multi-language via plugins
Best for Small to mid teams wanting speed with little setup Larger repos needing structure, enforcement and generators

Neither is universally better. Turborepo shines when you already have working package scripts and want caching and parallelism with ten lines of config. Nx is stronger when you want enforced module boundaries, automated migrations of dependencies, generators that scaffold consistent projects and a richer project graph visualization. Bazel and Pants exist for polyglot repositories at very large scale, with a correspondingly steep adoption cost.

A minimal Turborepo pipeline looks like this:

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

The ^build notation means “build this package’s dependencies first”. Declaring outputs accurately is essential: the cache restores those files on a hit, so missing outputs create baffling bugs where a cached build is incomplete.

Package boundaries

The difference between a healthy monorepo and a big ball of mud is how deliberately you manage dependencies between packages.

Design packages around cohesion, not convenience. A package named utils becomes a junk drawer within a year. Prefer names that describe a capability: date-formatting, pricing-rules, auth-client.

Define a public API for each package. Expose a single entry point (index.ts, or the exports field in package.json) and keep everything else private. Deep imports like @acme/ui/src/internal/button couple consumers to implementation details. The exports map in package.json enforces this at the Node resolution level.

Keep the dependency graph acyclic and layered. A typical layering from bottom to top is: foundations (types, config), domain logic, infrastructure adapters (database, HTTP clients), UI, applications. Lower layers never import from higher ones. Circular dependencies make caching and builds unreliable.

Enforce it with tooling. Nx’s @nx/enforce-module-boundaries lint rule lets you tag projects (scope:web, type:ui) and declare which tags may depend on which. In Turborepo setups, use eslint-plugin-boundaries, dependency-cruiser or madge in CI to detect cycles and illegal imports. A rule that exists only in a wiki will be violated within weeks.

Separate shared code from code that merely happens to be reused. Duplicating three lines is cheaper than creating a shared abstraction that two teams then fight over. Extract a package when the code is stable, has at least two real consumers, and has an owner.

Assign owners. A CODEOWNERS file maps directories to teams, so a change to packages/domain automatically requests review from the people responsible.

Versioning and publishing

Internal packages consumed only inside the repo usually need no versions at all: everything always builds from the current commit, which is one of the main advantages of a monorepo. Mark them "private": true to prevent accidental publication.

Versioning becomes relevant when you publish some packages externally, such as an SDK, a design system used by other organizations or a CLI. Then you need a strategy:

  • Changesets is the popular tool in the JavaScript ecosystem. Each pull request includes a small markdown file declaring which packages changed and whether the bump is major, minor or patch. A release job aggregates these into version bumps and changelogs, and publishes.
  • Fixed (lockstep) versioning bumps all packages together; simple to reason about, but forces consumers to upgrade packages that did not change.
  • Independent versioning bumps only what changed; more precise but needs careful dependency range handling.
  • Conventional Commits with automated tooling such as release-please or semantic-release can derive versions from commit messages, if your team is disciplined about them.

For deployed applications, version with git SHAs or build numbers rather than semver, and tag releases. Do not try to apply semantic versioning to an app that no one imports.

If you maintain a mobile app, remember that store builds lag behind server deployments, so API compatibility rules matter even in a monorepo where “everything deploys together” is not actually true.

CI that stays fast

CI is where monorepos either shine or collapse. A naive pipeline that runs every build, lint and test on every commit scales linearly with repository size and eventually takes an hour. The cure is a combination of caching, affected-only execution and parallelism.

  1. Remote caching. Turborepo and Nx can store task outputs in a shared cache keyed by a hash of inputs (source files, dependencies, environment variables, task configuration). If a teammate or a previous CI run already built the same inputs, the result is restored instead of recomputed. Teams commonly cut CI times by half or more once remote caching is on.
  2. Affected-only runs. Compare against the target branch and run tasks only for packages that changed and packages that depend on them. In Turborepo: turbo run test --filter="...[origin/main]". In Nx: nx affected -t lint test build. Ensure the CI checkout has enough git history (fetch-depth) for the comparison to work.
  3. Parallelism and sharding. Run independent tasks concurrently, and split large test suites across multiple CI machines.
  4. Cache dependency installs. Cache the package manager store keyed by lockfile hash.
  5. Path-based deployments. Only deploy an app when it or one of its dependencies changed. Beware: a change to a shared package must trigger deployment of every app that uses it.
  6. Be careful with inputs. Overly broad inputs (such as hashing the whole repo) destroy cache hits; overly narrow inputs produce false hits. Declare environment variables that affect the build in the task configuration so the hash reflects them.
  7. Keep a fast path. Developers should get lint and type-check feedback in a couple of minutes; leave long end-to-end suites for merge queues or nightly runs.

A merge queue is another useful tool: it tests each pull request against the latest main branch before merging, preventing the situation where two individually green PRs break main when combined.

Migrating into a monorepo

Moving existing repositories into one can be done incrementally. Use git subtree or a history-preserving tool (git filter-repo) to import each repository under apps/ or packages/ with its history intact. Unify tooling gradually: first workspace linking, then shared TypeScript and ESLint config, then task orchestration, then caching. Resist the urge to refactor everything during the move; each stage should be shippable on its own. Agree on conventions up front for commit messages, branch policy, code ownership and how a new package is created.

Governance and culture

Technology is the easier half. Decide who can approve changes to shared packages, how breaking changes are announced, and how deprecations are retired. Write a short contributing guide that explains how to add an app or package, how to run things locally with one command and how to debug CI. Measure the developer experience: median CI time, cache hit rate, time to first successful local build for a new hire. When those numbers degrade, treat it as a bug.

At Datainter we have found that the biggest wins come from the simplest setup: pnpm workspaces, a small number of well-named packages and one enforced boundary rule, adding Nx-style structure only when the team and codebase demand it.

A monorepo does not make your architecture better. It makes your architecture visible, for good and for bad.

Key takeaways

  • A monorepo pays off when projects share real code and release together; it adds little for independent teams with nothing in common.
  • Use package-manager workspaces with a clear split between deployable apps and shared packages, and forbid apps from depending on other apps.
  • Choose Turborepo for a light task runner with caching, and Nx when you need enforced boundaries, generators and richer tooling.
  • Give each package a narrow public API, keep the dependency graph acyclic and enforce boundaries with lint rules, not documentation.
  • Keep internal packages private and unversioned; use Changesets or similar only for what you publish externally.
  • Keep CI fast with remote caching, affected-only runs, parallel execution and a merge queue, and track CI time and cache hit rate as team metrics.
#monorepo#turborepo#nx#ci#architecture
DI
Datainter TeamEngineers, designers and operators building software and fintech products from Medellín, Tigard and Luxembourg.

Building something in this space?

Talk to the team that ships and operates it. We reply within one business day.

Start a project
Chat with us on WhatsAppUSUALLY REPLIES WITHIN MINUTES