Every growing engineering team eventually faces the same architectural crossroads: either maintain separate repositories for your web app, admin dashboard, marketing site, and backend API - copy-pasting types and UI components between them - or consolidate everything into a monorepo.
However, without the right build tooling, monorepos quickly become a bottleneck. Running your build script compiles twenty packages even when you only edited a single CSS file. Your local feedback loop grinds to a halt, and continuous integration pipelines take twenty minutes to finish.
Building a monorepo with Turborepo and pnpm solves this completely. By pairing pnpm workspaces with Turborepo's intelligent task graph and content-aware hashing, you get instant local caching, zero-duplicate dependencies, and sub-second builds.
Below is a complete, production-tested walkthrough on structuring a TypeScript monorepo with Turborepo, configuring shared internal packages, setting up remote caching, and generating minimal Docker container layers with pruning.
Why Pair pnpm Workspaces with Turborepo for a monorepo?
Before looking at configuration files, it helps to understand how the responsibilities are split between your package manager and your build orchestrator:
- pnpm Workspaces handles dependency management: It creates a shared, content-addressable store on your hard drive, symlinks local packages instantly using the
workspace:*protocol, and prevents "phantom dependencies" where packages accidentally import modules they never declared in their ownpackage.json. - Turborepo handles task execution and caching: Turborepo parses the dependencies between your packages, runs independent tasks in parallel, caches output files based on git and file-hash fingerprints, and skips tasks entirely when nothing has changed.
Together, they provide the velocity of working in a single codebase with the isolation of modular packages.
Production Monorepo Directory Architecture
A scalable TypeScript monorepo separates runnable applications from shared, internal libraries. Here is the recommended directory structure:
my-monorepo/
├── apps/
│ ├── web/ # Next.js customer-facing application
│ │ └── package.json
│ └── admin/ # Internal admin dashboard
│ └── package.json
├── packages/
│ ├── ui/ # Shared design system & React components
│ │ └── package.json
│ ├── tsconfig/ # Shared TypeScript base configs
│ │ └── package.json
│ └── database/ # Prisma / Drizzle ORM models and client
│ └── package.json
├── pnpm-workspace.yaml # Declares workspace package directories
├── package.json # Root package.json (dev tooling only)
└── turbo.json # Turborepo task pipeline definition
1. Root pnpm-workspace.yaml
In the root of your project, tell pnpm where your packages live:
packages:
- "apps/*"
- "packages/*"
2. Root package.json
Install Turborepo to the workspace root using the -w flag:
pnpm add -D turbo -w
Your root package.json stays lean and delegates all lifecycle scripts to turbo:
{
"name": "my-monorepo",
"private": true,
"scripts": {
"build": "turbo build",
"dev": "turbo dev",
"lint": "turbo lint",
"check": "turbo check",
"clean": "turbo clean"
},
"devDependencies": {
"turbo": "^2.4.0"
},
"packageManager": "pnpm@9.15.0"
}
Configuring the turbo.json Task Pipeline
Turborepo relies on turbo.json at the root of your workspace to declare dependencies between tasks.
{
"$schema": "https://turbo.build/schema.json",
"tasks": {
"build": {
"dependsOn": ["^build"],
"inputs": ["$TURBO_DEFAULT$", ".env*"],
"outputs": [".next/**", "!.next/cache/**", "dist/**"]
},
"lint": {
"dependsOn": ["^build"]
},
"check": {
"cache": true
},
"dev": {
"cache": false,
"persistent": true
}
}
}
Understanding the Key Parameters
dependsOn: ["^build"](Topological Dependency): The caret (^) tells Turborepo: "Before building this package, build all the internal packages this package depends on first." Ifapps/webimportspackages/ui, Turborepo buildspackages/uifirst. Independent packages build simultaneously across all available CPU cores.inputs: Tells Turborepo which files to include in the cache fingerprint. If only a test file changes, the build task does not need to re-run.outputs: Directories that Turborepo stores in cache. When a cache hit occurs, Turborepo restores these folders instantly instead of running the compiler.persistent: true: Used for long-running processes like local development servers (turbo dev) to prevent them from blocking the terminal pipeline.
Sharing Internal Packages Without Publishing to npm
The most powerful benefit of a TypeScript monorepo is consuming internal packages directly without publishing them to an npm registry.
Creating @repo/ui
Inside packages/ui/package.json:
{
"name": "@repo/ui",
"version": "0.0.0",
"private": true,
"exports": {
"./button": "./src/button.tsx",
"./card": "./src/card.tsx"
},
"scripts": {
"check": "biome check ."
},
"peerDependencies": {
"react": "^19.0.0"
},
"devDependencies": {
"@repo/tsconfig": "workspace:*",
"@types/react": "^19.0.0"
}
}
Consuming @repo/ui Inside apps/web
In apps/web/package.json, link the internal package using workspace:*:
{
"name": "web",
"dependencies": {
"@repo/ui": "workspace:*",
"next": "^15.0.0",
"react": "^19.0.0"
}
}
Because modern bundlers (Next.js with Turbopack, Vite) compile TypeScript on the fly, you do not need complex pre-compilation build scripts inside your internal packages. You can export TypeScript source files directly via the exports map. To ensure consistent code quality across packages, pairing your workspace with Biome allows single-pass formatting and linting across all apps and packages in milliseconds.
Remote Caching and Sharing Build Artifacts Across Your Team
Local caching is great, but remote caching is where monorepos become truly transformative.
With remote caching, whenever one developer or a CI runner builds a package, the hashed build artifacts are uploaded to a remote cache server. When another team member pulls the branch or opens a pull request, Turborepo downloads the cached output in milliseconds instead of running the compiler.
Option 1 - Vercel Remote Cache (Zero Config)
If your team deploys on Vercel, linking your monorepo requires two terminal commands:
npx turbo login
npx turbo link
Turborepo will automatically authenticate with your team's Vercel account and stream cache artifacts securely during local builds and CI runs.
Option 2 - Self-Hosted Remote Cache (AWS S3 and Ducktape)
For teams hosting on private infrastructure or looking to cut cloud costs, you can run an open-source, S3-compatible remote cache server like Ducktape:
# Run a self-hosted remote cache container
docker run -d -p 3000:3000 \
-e STORAGE_TYPE=s3 \
-e AWS_BUCKET=my-turbo-cache \
ghcr.io/ducktape/ducktape:latest
In your CI environment (e.g. GitHub Actions), configure Turborepo via environment variables:
- name: Build monorepo with Remote Cache
run: pnpm turbo build
env:
TURBO_API: "https://cache.mycompany.internal"
TURBO_TOKEN: ${{ secrets.TURBO_CACHE_TOKEN }}
TURBO_TEAM: "engineering"
Docker Optimization and Minimal Builds with Turbo Prune
One common objection to monorepos is Docker build bloat. If you copy the entire repository into a Docker image to deploy one service, every tiny change invalidates Docker's layer cache, making builds slow and container sizes enormous.
Turborepo includes a specialized command: turbo prune.
turbo prune <target-app> --docker analyzes your dependency graph and extracts only the code, internal packages, and package.json files required for that single app, generating an isolated ./out directory.
Production Multi-Stage Dockerfile for Next.js
Here is the industry-standard multi-stage Dockerfile for deploying apps/web:
# 1. Prune step - Extract only what 'web' needs
FROM node:22-alpine AS pruner
WORKDIR /app
RUN npm install -g pnpm turbo
COPY . .
RUN turbo prune web --docker
# 2. Dependency installation step
FROM node:22-alpine AS installer
WORKDIR /app
RUN npm install -g pnpm
COPY --from=pruner /app/out/json/ .
COPY --from=pruner /app/out/pnpm-lock.yaml ./pnpm-lock.yaml
RUN pnpm install --frozen-lockfile
# 3. Build step
FROM node:22-alpine AS builder
WORKDIR /app
RUN npm install -g pnpm
COPY --from=installer /app .
COPY --from=pruner /app/out/full/ .
RUN pnpm turbo build --filter=web
# 4. Production Runner step - Ultra-lean container
FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
# Copy standalone build output generated by Next.js
COPY --from=builder /app/apps/web/.next/standalone ./
COPY --from=builder /app/apps/web/.next/static ./apps/web/.next/static
COPY --from=builder /app/apps/web/public ./apps/web/public
EXPOSE 3000
CMD ["node", "apps/web/server.js"]
This Dockerfile guarantees that editing code in apps/admin will never bust the Docker layer cache for apps/web. For deep deployment configurations on Next.js standalone outputs, check our Next.js Architectural Guide.
Running CI Pipelines with Affected Filters
In pull requests, you never want to run tests and builds across every package. Turborepo provides git-aware filtering:
# Build only packages affected by changes compared to the main branch
pnpm turbo build --filter="...[origin/main]"
# Run tests only on the web app and all packages that depend on it
pnpm turbo test --filter=web...
# Run linting on all apps, excluding packages
pnpm turbo lint --filter="./apps/*"
The ...[origin/main] syntax checks your git diff against origin/main and only builds the changed packages plus any downstream packages that consume them.
Turborepo vs Nx - An Honest Comparison
Both tools are exceptional monorepo orchestrators, but they target different team sizes and philosophies:
| Feature | Turborepo | Nx |
|---|---|---|
| Configuration | Single turbo.json, zero boilerplate | Modular project.json or nx.json |
| Learning Curve | 30 minutes | Several days |
| Code Generation | Minimal (leaves scaffolding to user) | Extensive generators & plugin ecosystem |
| Dependency Graph | Fast, Rust-powered binary | Comprehensive graph visualization tools |
| Target Teams | Startups & product teams (2 to 20 packages) | Large enterprises (50+ enterprise packages) |
If your team is already using TypeScript, React, and pnpm workspaces, Turborepo is the fastest, cleanest path to monorepo success without adopting complex framework plugins. For official reference, review the Turborepo Documentation and the Turborepo GitHub.
Frequently Asked Questions from Developer Forums
Do I need to build internal packages before running dev servers?
- In modern TypeScript workflows, use package
exportsmaps that point directly to.tsand.tsxsource files. Bundlers like Next.js (Turbopack/Webpack) and Vite will transpile the TypeScript code on demand, meaning you don't need a background watcher compiling internal packages.
How do I handle shared TypeScript configs?
Create a @repo/tsconfig package with base.json, nextjs.json, and react-library.json. In your apps, extend the configuration:
{
"extends": "@repo/tsconfig/nextjs.json"
}
For in-depth typing strategies, see our guide on TypeScript for React Developers.
Why is Turborepo missing the cache in CI?
The two most common reasons are:
- Uncommitted lockfile changes: Turborepo includes lockfile hashes in its cache calculation. Always ensure your lockfile is committed and clean.
- Undeclared environment variables: If your build relies on environment variables (like
NEXT_PUBLIC_API_URL), you must declare them in theenvarray insideturbo.jsonso Turborepo includes them in the cache fingerprint.
When Should You Switch?
- Teams with Two or More Applications: If you maintain a user-facing web app and an admin dashboard that share authentication models, UI components, or types, migrate to a monorepo immediately.
- Teams Struggling with npm Packages: If you are wasting time publishing private packages to npm just to share a utility function between projects, pnpm workspaces and Turborepo will eliminate that friction overnight.
- Explore More Developer Tools: Discover additional production tooling workflows in our Developer Tools section.




Comments
Have a question or something to add? Sign in to join the discussion.