Next.js course Β· Module 9: Integrations and Advanced Features

Monorepo with Turborepo - Scaling Next.js Projects

6 min read Β·
In this lesson8

In the vast infrastructure of Metropolis Quantum 2150, where dozens of microservices and frontend applications work together, you need a tool for managing code at a massive scale. Turborepo is a build system for monorepos that works with Next.js like a precise quantum processor - fast, efficient and reliable.

Why a monorepo for Next.js?

A monorepo is a strategy of storing multiple projects in a single repository. For the Next.js ecosystem it brings huge benefits:

  • Code sharing - UI components, configurations and types used across many applications
  • Atomic changes - a change in a shared library is instantly visible everywhere
  • Consistent tooling - one ESLint, TypeScript and Prettier configuration
  • Simplified CI/CD - one pipeline for the whole ecosystem
  • Better collaboration - everything in one place, easy code review

Turborepo configuration

Initializing the monorepo

# Create a new monorepo with Turborepo
npx create-turbo@latest quantum-monorepo

# Or add Turborepo to an existing project
npm install turbo --save-dev

Directory structure

quantum-monorepo/
  apps/
    web/                 # Main Next.js application
      package.json
      next.config.js
    admin/               # Next.js admin panel
      package.json
      next.config.js
    docs/                # Next.js documentation
      package.json

  packages/
    ui/                  # Shared React components
      package.json
      src/
        Button.tsx
        Card.tsx
        index.ts
    config-eslint/       # Shared ESLint configuration
      package.json
    config-typescript/   # Shared TypeScript configuration
      package.json
    types/               # Shared TypeScript interfaces
      package.json
      src/
        user.ts
        product.ts

  turbo.json             # Turborepo configuration
  package.json           # Root package.json

The turbo.json configuration

{
  "$schema": "https://turbo.build/schema.json",
  "globalDependencies": ["**/.env.*local"],
  "pipeline": {
    "build": {
      "dependsOn": ["^build"],
      "outputs": [".next/**", "!.next/cache/**", "dist/**"]
    },
    "lint": {
      "dependsOn": ["^build"]
    },
    "dev": {
      "cache": false,
      "persistent": true
    },
    "test": {
      "dependsOn": ["^build"]
    },
    "type-check": {
      "dependsOn": ["^build"]
    }
  }
}

Key elements of the configuration:

  • dependsOn: ["^build"] - build the dependencies before you build the package
  • outputs - what to cache (output folders)
  • cache: false - the dev server should not be cached
  • persistent: true - long-running processes (dev server)

Root package.json

{
  "name": "quantum-monorepo",
  "private": true,
  "workspaces": ["apps/*", "packages/*"],
  "scripts": {
    "build": "turbo build",
    "dev": "turbo dev",
    "lint": "turbo lint",
    "test": "turbo test",
    "type-check": "turbo type-check"
  },
  "devDependencies": {
    "turbo": "^2.0.0"
  }
}

Shared packages

The UI package - React components

// packages/ui/package.json
{
  "name": "@quantum/ui",
  "version": "0.1.0",
  "main": "./src/index.ts",
  "types": "./src/index.ts",
  "dependencies": {
    "react": "^19.2.0"
  },
  "devDependencies": {
    "@quantum/config-typescript": "workspace:*",
    "typescript": "^5.5.0"
  }
}
// packages/ui/src/Button.tsx
import React from 'react';

interface ButtonProps {
  children: React.ReactNode;
  variant?: 'primary' | 'secondary' | 'danger';
  onClick?: () => void;
  disabled?: boolean;
}

export function Button({ children, variant = 'primary', onClick, disabled }: ButtonProps) {
  const styles = {
    primary: { background: '#7c4dff', color: '#fff' },
    secondary: { background: '#64ffda', color: '#000' },
    danger: { background: '#f44336', color: '#fff' },
  };

  return (
    <button
      onClick={onClick}
      disabled={disabled}
      style={{
        ...styles[variant],
        padding: '10px 24px',
        borderRadius: '8px',
        border: 'none',
        cursor: disabled ? 'not-allowed' : 'pointer',
        opacity: disabled ? 0.5 : 1,
      }}
    >
      {children}
    </button>
  );
}
// packages/ui/src/index.ts
export { Button } from './Button';
export { Card } from './Card';

The types package - shared interfaces

// packages/types/src/user.ts
export interface User {
  id: string;
  email: string;
  name: string;
  role: 'admin' | 'user' | 'moderator';
  createdAt: string;
}
// packages/types/src/index.ts
export * from './user';
export * from './product';

Workspace dependencies

To use a shared package in a Next.js application:

// apps/web/package.json
{
  "name": "@quantum/web",
  "dependencies": {
    "@quantum/ui": "workspace:*",
    "@quantum/types": "workspace:*",
    "next": "^16.0.0",
    "react": "^19.2.0",
    "react-dom": "^19.2.0"
  },
  "devDependencies": {
    "@quantum/config-typescript": "workspace:*",
    "@quantum/config-eslint": "workspace:*"
  }
}

Usage in the application code:

// apps/web/app/page.tsx
import { Button, Card } from '@quantum/ui';
import type { Product } from '@quantum/types';

export default async function HomePage() {
  return (
    <div>
      <h1>Quantum Store</h1>
      <Button variant="primary">Add to cart</Button>
    </div>
  );
}

Turborepo cache and pipeline

Turborepo uses an intelligent cache system that remembers build results and skips unchanged packages.

How the cache works

# First build - everything from scratch
npx turbo build
# Output: 5 tasks, 0 cached, 5 not cached
# Time: 45s

# Second build (no changes) - full cache
npx turbo build
# Output: 5 tasks, 5 cached, 0 not cached
# Time: 0.3s

Remote Caching with Vercel

# Connect to the Vercel Remote Cache
npx turbo login
npx turbo link

# Now the cache is shared between developers and CI

Filtering builds

# Build only a specific application
npx turbo build --filter=@quantum/web

# Build the application and its dependencies
npx turbo build --filter=@quantum/web...

# Build only what has changed since the last commit
npx turbo build --filter=[HEAD^1]

Deploying a monorepo to Vercel

The next.config.js configuration for a monorepo

// apps/web/next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  transpilePackages: ['@quantum/ui'],
  output: 'standalone',
};

module.exports = nextConfig;

The transpilePackages option tells Next.js to transpile code from the monorepo packages (by default Next.js does not transpile node_modules).

Multi-application deployment

Vercel automatically builds only the changed applications. If you change packages/ui, the applications that depend on that package will be rebuilt, and the independent ones will be skipped.

Best practices

1. Package naming conventions

Use a scope (@organization-name/) for all packages and applications:

@quantum/ui
@quantum/types
@quantum/config-eslint
@quantum/web
@quantum/admin

2. Versioning

Use workspace:* for internal dependencies - never hardcode versions:

"@quantum/ui": "workspace:*"

3. Managing environment variables

Each application has its own .env file, and turbo.json declares global dependencies on the environment files.

Summary

Turborepo is a powerful tool for scaling Next.js projects in a monorepo architecture:

  1. Shared packages - UI, types and configurations used across many applications
  2. Intelligent cache - skipping unchanged packages, faster builds
  3. Pipeline - dependencies between tasks, parallel builds
  4. Workspace dependencies - workspace:* for internal packages
  5. Remote caching - a cache shared between developers and CI
  6. Deploy to Vercel - native support, automatic change detection

In Metropolis Quantum 2150, where every project grows and needs scaling, Turborepo is the foundation of the architecture - it lets you manage dozens of applications and libraries from one place.

Code for this lesson: App.tsx
import React, { useState } from 'react';

interface Package {
  name: string;
  type: 'app' | 'package';
  status: 'cached' | 'building' | 'built' | 'pending';
  duration?: number;
  deps: string[];
}

const TurborepoDemo = () => {
  const [packages, setPackages] = useState<Package[]>([
    { name: '@quantum/web', type: 'app', status: 'pending', deps: ['@quantum/ui', '@quantum/types'] },
    { name: '@quantum/admin', type: 'app', status: 'pending', deps: ['@quantum/ui', '@quantum/types'] },
    { name: '@quantum/docs', type: 'app', status: 'pending', deps: [] },
    { name: '@quantum/ui', type: 'package', status: 'pending', deps: ['@quantum/types'] },
    { name: '@quantum/types', type: 'package', status: 'pending', deps: [] },
    { name: '@quantum/config-ts', type: 'package', status: 'pending', deps: [] },
    { name: '@quantum/config-eslint', type: 'package', status: 'pending', deps: [] },
  ]);
  const [running, setRunning] = useState(false);
  const [logs, setLogs] = useState<string[]>([]);
  const [cacheEnabled, setCacheEnabled] = useState(true);
  const [buildCount, setBuildCount] = useState(0);
  const [changedPkg, setChangedPkg] = useState<string | null>(null);

  const addLog = (msg: string) => setLogs(prev => [...prev.slice(-12), msg]);
  const sleep = (ms: number) => new Promise(r => setTimeout(r, ms));

  const statusIcon = (s: string) => {
    switch (s) {
      case 'built': case 'cached': return 'βœ…';
      case 'building': return '⏳';
      default: return 'βšͺ';
    }
  };

  const statusColor = (s: string) => {
    switch (s) {
      case 'built': return '#4caf50';
      case 'cached': return '#64ffda';
      case 'building': return '#ff9800';
      default: return '#555';
    }
  };

  const runBuild = async () => {
    setRunning(true);
    setLogs([]);
    setPackages(prev => prev.map(p => ({ ...p, status: 'pending', duration: undefined })));
    setBuildCount(c => c + 1);
    const isSecondBuild = buildCount > 0;

    addLog('$ npx turbo build' + (changedPkg ? ' --filter=' + changedPkg + '...' : ''));

    // Build packages first (no deps first)
    const noDeps = packages.filter(p => p.type === 'package' && p.deps.length === 0);
    for (const pkg of noDeps) {
      const isCached = isSecondBuild && cacheEnabled && pkg.name !== changedPkg;
      setPackages(prev => prev.map(p => p.name === pkg.name ? { ...p, status: 'building' } : p));
      addLog((isCached ? 'CACHE HIT ' : 'Building ') + pkg.name);
      await sleep(isCached ? 100 : 300);
      setPackages(prev => prev.map(p => p.name === pkg.name ? { ...p, status: isCached ? 'cached' : 'built', duration: isCached ? 0 : 2 } : p));
    }

    // Then packages with deps
    const withDeps = packages.filter(p => p.type === 'package' && p.deps.length > 0);
    for (const pkg of withDeps) {
      const isCached = isSecondBuild && cacheEnabled && pkg.name !== changedPkg && !pkg.deps.includes(changedPkg || '');
      setPackages(prev => prev.map(p => p.name === pkg.name ? { ...p, status: 'building' } : p));
      addLog((isCached ? 'CACHE HIT ' : 'Building ') + pkg.name);
      await sleep(isCached ? 100 : 400);
      setPackages(prev => prev.map(p => p.name === pkg.name ? { ...p, status: isCached ? 'cached' : 'built', duration: isCached ? 0 : 5 } : p));
    }

    // Then apps
    const apps = packages.filter(p => p.type === 'app');
    for (const pkg of apps) {
      const affectedByChange = changedPkg && (pkg.deps.includes(changedPkg) || pkg.name === changedPkg);
      const isCached = isSecondBuild && cacheEnabled && !affectedByChange;
      if (changedPkg && !affectedByChange && pkg.name !== changedPkg) {
        setPackages(prev => prev.map(p => p.name === pkg.name ? { ...p, status: 'cached', duration: 0 } : p));
        addLog('SKIP ' + pkg.name + ' (not affected)');
        await sleep(80);
        continue;
      }
      setPackages(prev => prev.map(p => p.name === pkg.name ? { ...p, status: 'building' } : p));
      addLog((isCached ? 'CACHE HIT ' : 'Building ') + pkg.name);
      await sleep(isCached ? 150 : 600);
      setPackages(prev => prev.map(p => p.name === pkg.name ? { ...p, status: isCached ? 'cached' : 'built', duration: isCached ? 0 : 15 } : p));
    }

    const cached = packages.filter(() => true).length; // placeholder
    addLog('Build complete!');
    setRunning(false);
    setChangedPkg(null);
  };

  const simulateChange = (pkgName: string) => {
    setChangedPkg(pkgName);
    addLog('Changed: ' + pkgName);
  };

  const reset = () => {
    setPackages(prev => prev.map(p => ({ ...p, status: 'pending', duration: undefined })));
    setLogs([]);
    setBuildCount(0);
    setChangedPkg(null);
  };

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#fff', fontFamily: 'sans-serif' }}>
      <h1 style={{ color: '#64ffda', textAlign: 'center' }}>Monorepo with Turborepo</h1>
      <p style={{ textAlign: 'center', color: '#888', marginBottom: '20px' }}>Shared packages + Intelligent caching + Pipeline</p>

      <div style={{ maxWidth: '900px', margin: '0 auto' }}>
        <div style={{ display: 'flex', gap: '8px', justifyContent: 'center', marginBottom: '16px', flexWrap: 'wrap' }}>
          <button onClick={runBuild} disabled={running}
            style={{ padding: '8px 20px', background: running ? '#555' : '#4caf50', border: 'none', borderRadius: '6px', color: '#fff', cursor: running ? 'default' : 'pointer', fontWeight: 'bold' }}>
            {running ? 'Building...' : 'turbo build'}
          </button>
          <button onClick={reset} disabled={running}
            style={{ padding: '8px 20px', background: 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '6px', color: '#fff', cursor: 'pointer' }}>
            Reset
          </button>
          <label style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
            <input type="checkbox" checked={cacheEnabled} onChange={() => setCacheEnabled(!cacheEnabled)} />
            <span style={{ color: cacheEnabled ? '#64ffda' : '#666', fontSize: '13px' }}>Remote Cache</span>
          </label>
        </div>

        {buildCount > 0 && !running && (
          <div style={{ display: 'flex', gap: '6px', justifyContent: 'center', marginBottom: '12px', flexWrap: 'wrap' }}>
            <span style={{ color: '#888', fontSize: '12px', padding: '4px 0' }}>Simulate change in:</span>
            {packages.filter(p => p.type === 'package').map(p => (
              <button key={p.name} onClick={() => simulateChange(p.name)}
                style={{ padding: '4px 10px', background: changedPkg === p.name ? '#ff9800' : 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '4px', color: '#fff', cursor: 'pointer', fontSize: '11px' }}>
                {p.name.replace('@quantum/', '')}
              </button>
            ))}
          </div>
        )}

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
          <div>
            <h3 style={{ color: '#7c4dff', marginBottom: '10px' }}>Workspace Packages</h3>
            <div style={{ background: 'rgba(255,255,255,0.05)', borderRadius: '10px', overflow: 'hidden' }}>
              {packages.map(pkg => (
                <div key={pkg.name} style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '10px 12px', borderBottom: '1px solid #1a1a2e' }}>
                  <span>{statusIcon(pkg.status)}</span>
                  <span style={{ background: pkg.type === 'app' ? '#7c4dff33' : '#64ffda33', color: pkg.type === 'app' ? '#7c4dff' : '#64ffda', padding: '2px 6px', borderRadius: '4px', fontSize: '10px' }}>
                    {pkg.type}
                  </span>
                  <span style={{ flex: 1, color: statusColor(pkg.status), fontSize: '13px' }}>{pkg.name}</span>
                  {pkg.status === 'cached' && <span style={{ color: '#64ffda', fontSize: '10px' }}>CACHED</span>}
                  {pkg.duration !== undefined && pkg.duration > 0 && <span style={{ color: '#555', fontSize: '11px' }}>{pkg.duration}s</span>}
                </div>
              ))}
            </div>

            <div style={{ marginTop: '12px', background: 'rgba(255,255,255,0.05)', padding: '12px', borderRadius: '8px' }}>
              <h4 style={{ color: '#64ffda', fontSize: '12px', marginBottom: '8px' }}>Dependency Graph</h4>
              <div style={{ fontSize: '11px', fontFamily: 'monospace', color: '#888' }}>
                <div>@quantum/web ── @quantum/ui ── @quantum/types</div>
                <div>@quantum/admin ── @quantum/ui ── @quantum/types</div>
                <div>@quantum/docs (no internal deps)</div>
              </div>
            </div>
          </div>

          <div>
            <h3 style={{ color: '#7c4dff', marginBottom: '10px' }}>Build Log</h3>
            <div style={{ background: '#000', padding: '12px', borderRadius: '8px', minHeight: '300px', maxHeight: '400px', overflowY: 'auto', fontFamily: 'monospace', fontSize: '11px' }}>
              {logs.length === 0 ? (
                <span style={{ color: '#555' }}>Click "turbo build" to start...</span>
              ) : logs.map((log, i) => (
                <div key={i} style={{ color: log.includes('CACHE') ? '#64ffda' : log.includes('SKIP') ? '#888' : log.includes('Building') ? '#ff9800' : '#0f0', padding: '2px 0' }}>
                  {log}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default TurborepoDemo;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which statement best describes the main advantage of Turborepo in Next.js projects?

Hands-on tasks in the game

  • Vertical ordering

    Arrange the order of building packages in a Turborepo monorepo (from packages without dependencies to applications)

  1. QuestionTurborepo - Monorepo Management
  2. Put in orderBuild Pipeline in Turborepo

Useful articles