Next.js Monorepos with Turborepo and Workspaces
A monorepo earns its keep when the same design system, validation schema, or API client is consumed by more than one application. Instead of publishing packages to a private registry and juggling versions, every consumer imports workspace-local code and a single pull request updates the library and every app that depends on it. Turborepo adds the piece that makes this practical at scale: a task graph with caching, so building the docs site does not rebuild the API package that did not change.
The failure mode is equally common â a monorepo that works beautifully on one laptop and collapses in CI because path aliases leak, transpilation of workspace packages is misconfigured, or the cache never hits due to unstable inputs. This lesson sets up the structure correctly the first time.
Prerequisites
- !Comfort with npm scripts and package.json
- !A Next.js app that currently lives in its own repository
- !Basic understanding of TypeScript path aliases
What You'll Learn
- 1Configure npm workspaces with apps and packages directories
- 2Wire Turborepo task pipelines with correct cache inputs and outputs
- 3Consume a workspace UI package from a Next.js app
- 4Debug the two most common monorepo build failures
Repository layout
Start with three top-level directories: apps holds deployable projects, packages holds shared libraries, and tooling optionally holds shared config. Each workspace declares its own name and dependencies; npm links them locally so imports resolve without publishing.
my-monorepo/
apps/
web/ Next.js storefront
admin/ Next.js admin
packages/
ui/ Shared React components
config/ Shared eslint and tsconfig
package.json
turbo.json
tsconfig.base.json
The root package.json declares the workspace globs and the orchestration scripts. Private is set true because a monorepo root should never be publishable by accident.
{
"name": "acme",
"private": true,
"workspaces": ["apps/*", "packages/*"],
"scripts": {
"dev": "turbo run dev",
"build": "turbo run build",
"lint": "turbo run lint",
"test": "turbo run test",
"format": "prettier --write ."
},
"devDependencies": {
"turbo": "^2.0.0",
"prettier": "^3.0.0"
}
}
The Turborepo pipeline
turbo.json defines tasks, what they depend on, what inputs invalidate the cache, and which outputs the cache stores. Getting dependsOn right is the difference between a correct incremental build and one that ships stale code.
{
"$schema": "https://turbo.build/schema.json",
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": [".next/**", "!.next/cache/**", "dist/**"],
"env": ["NODE_ENV", "NEXT_PUBLIC_*"]
},
"dev": {
"cache": false,
"persistent": true
},
"lint": {
"dependsOn": ["^build"]
},
"test": {
"dependsOn": ["build"],
"outputs": ["coverage/**"]
}
}
}
dependsOn: ["^build"] means a task waits for its workspace dependencies' builds first â the Next.js app builds only after packages/ui has produced its dist. env lists the variables that should participate in the cache key; forgetting NEXT_PUBLIC_* is a classic source of builds that reuse a cache entry generated with the wrong public configuration.
Consuming a workspace package
Shared packages should ship compiled output with clean entry points, not raw source that each consumer must transpile differently. A simple tsup or tsc build producing dist, paired with exports in package.json, keeps Next.js happy without next-transpile-modules gymnastics.
// packages/ui/package.json
{
"name": "@acme/ui",
"version": "0.1.0",
"private": true,
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"scripts": {
"build": "tsup src/index.ts --format esm --dts --clean",
"dev": "tsup src/index.ts --format esm --watch"
},
"peerDependencies": {
"react": "^18.0.0",
"react-dom": "^18.0.0"
},
"devDependencies": {
"tsup": "^8.0.0",
"typescript": "^5.0.0"
}
}
// packages/ui/src/Button.tsx
import type { ButtonHTMLAttributes, ReactNode } from 'react';
type Props = ButtonHTMLAttributes<HTMLButtonElement> & {
variant?: 'primary' | 'ghost';
children: ReactNode;
};
export function Button({ variant = 'primary', children, ...rest }: Props) {
return (
<button className={`btn btn--${variant}`} {...rest}>
{children}
</button>
);
}
// apps/web/app/page.tsx
import { Button } from '@acme/ui';
export default function HomePage() {
return (
<main>
<h1>Acme Store</h1>
<Button variant="primary">Shop new arrivals</Button>
</main>
);
}
React stays a peer dependency so both the app and the package resolve to a single React instance â a duplicated React is the monorepo equivalent of two wizards fighting over one wand.
Debugging the two classic failures
The first failure is a module-not-found error on a workspace import. Almost always, dependencies were installed before the workspace was added, or the package's build output does not exist yet. Running npm install at the root, then building the package once, fixes it. Keep a root postinstall or a turbo prerequisite if the team hits this repeatedly.
The second failure is stale or mismatched types: the app compiles against an old .d.ts because the package's build step did not run before the app's typecheck. dependsOn: ["^build"] in the pipeline prevents it; if you bypass turbo and run the app script directly, you bypass the dependency ordering too.
# Full clean when caches feel haunted
rm -rf node_modules .turbo apps/*/node_modules apps/*/.next packages/*/dist
npm install
npx turbo run build
Continuous integration built on the same graph
CI is where the task graph stops being a convenience and starts being the difference between a ten-minute pipeline and a forty-minute one. The first principle is that CI should run the same turbo commands developers run locally, with the same cache configuration â a pipeline that invokes npm run build directly in each app directory bypasses dependency ordering and reinstalls work that a cache hit would have skipped. The second is dependency-aware checkout: filter the pipeline to tasks whose inputs actually changed. Turborepo's changed filter lets a pull request that only touches the storefront skip the admin app's build entirely, while a change to the shared UI package correctly fans out to every consumer.
Seed the remote cache in CI so the build a teammate already paid for is reused by the pipeline, not repeated. The practical sequence is: install with a frozen lockfile, run lint and test tasks through turbo, build only the changed filter, and upload artifacts for deploy only from the filtered set. Because env variables participate in cache keys, the pipeline's environment must mirror production's public configuration or hits will be invalidated constantly â a symptom that looks like a broken cache and is really a misconfigured one.
Watch the hit rate as a health metric rather than a vanity metric. A sudden drop after a dependency bump is expected; a persistent drop usually means an unstated input â a code generator writing files outside the declared outputs, a plugin reading a file turbo cannot see, or a timestamp creeping into generated content. Adding the missing input to the task definition restores the cache and, with it, the pipeline's value.
Remote caching for teams
Local caching helps one machine; remote caching helps everyone. Turbo's remote cache stores task outputs in the cloud so a teammate or CI runner that already built @acme/ui reuses that artifact instead of rebuilding it. Configure a team token in CI, and treat cache hits as a deploy-quality signal: a healthy pipeline sits at high hit rates for unchanged packages.
Enable it with the login flow on developer machines and by setting TURBO_TOKEN and TURBO_TEAM in CI secrets. Because the cache keys include inputs and environment variables, the earlier decision to list NEXT_PUBLIC_* in env directly determines whether remote hits are safe or catastrophic.
When to split the repo instead
Monorepos are not free. A repo where every team deploys on a different cadence fights over CI minutes and lockfile conflicts may be better split. Good splitting signals include genuinely independent release cycles, compliance boundaries that forbid shared build agents, or a repo checkout time that dominates developer patience. The reverse â three repositories importing slightly different forks of the same UI package â is the state that monorepos exist to fix.
There is also a middle path worth knowing about before committing: keep the shared code in the monorepo and publish versioned artifacts from it, while letting the applications that need loose coupling consume the published package instead of the workspace link. That arrangement preserves single-source-of-truth for the design system while giving a slow-moving consumer a version to pin, which defuses most lockfile and release-cadence friction without a repository split. Reach for an actual split only when the friction survives that compromise â at which point the boundaries in your dependency graph will have already told you exactly where to cut.
Common Mistakes
Running the app's dev script without building workspace packages first
Fix: Run through turbo so dependsOn ordering builds libraries before the app consumes them.
Forgetting NEXT_PUBLIC_ variables in the build env list
Fix: List them in turbo.json env so cache entries are keyed by the public configuration they were built with.
Bundling React inside a shared package
Fix: Declare React as a peer dependency and provide it from the app to avoid duplicate instances.
Leaving packages as raw TypeScript with no build step
Fix: Compile to dist with tsup or tsc and expose entry points through package.json exports.
Best Practices
- Name packages with a scope such as @acme/ui so imports signal ownership
- Keep shared eslint and tsconfig in a config package to enforce consistency
- Watch turbo's task graph output once per quarter to spot missing dependencies
- Split the repository only when release cadence or compliance genuinely diverge
Interview Questions
Q1: What does dependsOn: ["^build"] mean in turbo.json?
The caret refers to workspace dependencies: the current task runs only after the build tasks of any packages it depends on have completed.
Q2: Why must NEXT_PUBLIC_ variables be listed in the cache env?
Turborepo includes listed env values in the cache key; without them a cached build could reuse artifacts compiled with a different public configuration.
Q3: Why should React be a peer dependency of a shared UI package?
So the application provides a single React copy; a regular dependency risks two React instances and broken hooks behavior.
Key Takeaways
- Workspaces link local packages; Turborepo adds the task graph and caching on top.
- dependsOn controls build order; env controls cache correctness â both must be explicit.
- Shared packages should ship compiled dist output with proper exports.
- Remote caching turns local incremental builds into team-wide speed.
- Two failures explain most monorepo pain: uninstalled workspaces and stale type outputs.