---
title: "CLI Commands"
description: "The Next.js Command-Line Interface (CLI) serves as the primary orchestration and entry point for building, developing, serving, and diagnosing Next.js applications. Architected around Commander.js ..."
last_updated: "2026-09-23T10:52:03.144385+00:00"
canonical_url: "https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-and-config/cli-commands"
---

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [packages/next/src/bin/next.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/bin/next.ts)
- [packages/next/taskfile.js](https://github.com/blade47/next.js/blob/main/packages/next/taskfile.js)
- [packages/next/src/cli/next-dev.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-dev.ts)
- [packages/next/src/cli/next-info.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-info.ts)
- [packages/next/src/cli/internal/static-routes-info.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/static-routes-info.ts)
- [packages/next/src/cli/next-build.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-build.ts)
- [package.json](https://github.com/blade47/next.js/blob/main/package.json)
- [packages/next-codemod/bin/next-codemod.ts](https://github.com/blade47/next-codemod/bin/next-codemod.ts)
- [packages/next/src/cli/next-export.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-export.ts)
- [packages/create-next-app/index.ts](https://github.com/blade47/create-next-app/index.ts)
- [packages/next/src/cli/next-start.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-start.ts)
- [packages/next/src/cli/internal/upload-trace.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/upload-trace.ts)
- [packages/next/src/cli/internal/query-trace.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/query-trace.ts)
- [packages/next/src/server/config.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/config.ts)
- [packages/next/src/cli/next-analyze.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-analyze.ts)
- [packages/next/src/cli/next-telemetry.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-telemetry.ts)
- [packages/next/package.json](https://github.com/blade47/next.js/blob/main/packages/next/package.json)
- [packages/next/src/server/lib/app-info-log.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/lib/app-info-log.ts)
- [packages/next/types.js](https://github.com/blade47/next.js/blob/main/packages/next/types.js)
- [packages/next/src/telemetry/events/version.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/telemetry/events/version.ts)
- [packages/next/src/server/config-schema.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/config-schema.ts)
- [packages/next/src/server/lib/utils.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/lib/utils.ts)
- [packages/next/src/server/config-shared.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/server/config-shared.ts)
- [packages/next/src/cli/next-post-build.ts](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-post-build.ts)
</details>

## Overview

### Background and Architecture
The Next.js Command-Line Interface (CLI) serves as the primary orchestration and entry point for building, developing, serving, and diagnosing Next.js applications. Architected around Commander.js within `packages/next/src/bin/next.ts`, the CLI defines root commands that map user flags and positional arguments to asynchronous execution handlers. These handlers bootstrap runtime configurations, manage child process lifecycles, and interface directly with underlying compiler pipelines such as Webpack and Turbopack.
Sources: [packages/next/src/bin/next.ts:137-155](https://github.com/blade47/next.js/blob/main/packages/next/src/bin/next.ts#L137-L155)

### Subsystem Interaction and Design Principles
By decoupling command-line parsing from domain logic, the CLI architecture enforces strict separation between user-facing options and core server infrastructure. Commands validate project root directories, inject environment variables (such as `__NEXT_VERSION` and `NODE_OPTIONS`), and capture session-level telemetry or diagnostic profiles (`.next-profiles/`). Adjacent tooling—including `next-codemod`, `create-next-app`, and internal trace query systems—leverage this same command routing structure to offer developers a unified terminal experience across workspace boundaries.
Sources: [packages/next/src/bin/next.ts:296-402](https://github.com/blade47/next.js/blob/main/packages/next/src/bin/next.ts#L296-L402)

## Root Command and Execution Dispatch

### Dispatch Architecture
The Next.js binary entry point (`packages/next/src/bin/next.ts`) initializes a `NextRootCommand` instance configured with standard metadata, help formatting, and version flags. When executed, Commander evaluates `process.argv` and dispatches control to the registered command action handler.
Sources: [packages/next/src/bin/next.ts:137-156](https://github.com/blade47/next.js/blob/main/packages/next/src/bin/next.ts#L137-L156)

### Command Mapping Flow
```mermaid
flowchart TD
    A["CLI Invocation<br>node packages/next/dist/bin/next"] --> B["NextRootCommand<br>packages/next/src/bin/next.ts"]
    B --> C{"Command Match"}
    C -->|dev / (default)| D["nextDev Options<br>packages/next/src/cli/next-dev.ts"]
    C -->|build| E["nextBuild Options<br>packages/next/src/cli/next-build.ts"]
    C -->|start| F["nextStart Options<br>packages/next/src/cli/next-start.ts"]
    C -->|info| G["nextInfo Options<br>packages/next/src/cli/next-info.ts"]
    C -->|telemetry| H["nextTelemetry<br>packages/next/src/cli/next-telemetry.ts"]
    D --> I["Server Bootstrap / Child Fork"]
    E --> J["Compiler Pipeline (`build()`)"]
    F --> K["Production Server (`startServer()`)"]
```
Sources: [packages/next/src/bin/next.ts:296-400](https://github.com/blade47/next.js/blob/main/packages/next/src/bin/next.ts#L296-L400)

## Development Server (`next dev`)

### Lifecycle and Execution Mechanism
The `next dev` command starts Next.js in development mode with hot-code reloading, error reporting, and watcher orchestration. Defined as the default command in `packages/next/src/bin/next.ts`, it accepts an optional `[directory]` argument and a broad set of configuration options. When `nextDev` executes, it performs bundler resolution via `parseBundlerArgs(options)`, verifies the project root via `fileExists()`, sets up CPU profiling directories, and registers signal handlers (`SIGINT`, `SIGTERM`) to flush telemetry via `eventCliSessionStopped()` and upload traces.
Sources: [packages/next/src/cli/next-dev.ts:45-189](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-dev.ts#L45-L189), [packages/next/src/cli/next-dev.ts:204-242](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-dev.ts#L204-L242)

> [!NOTE]
> If the development server is restarted within `90,000` ms (`RAGE_RESTART_THRESHOLD_MS`), the CLI marks the session span attribute `'rage-restart'` as `true` for telemetry analysis.
Sources: [packages/next/src/cli/next-dev.ts:81-83](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-dev.ts#L81-L83)

### Dev Options Reference Table
| Option Flag | Type / Default | Description |
| :--- | :--- | :--- |
| `[directory]` | `string` (cwd) | Target application directory. |
| `-p, --port ort>` | `number` (3000) | Port number to start the application on (env: `PORT`). |
| `-H, --hostname <hostname>` | `string` (0.0.0.0) | Hostname on which to start the application. |
| `--turbo`, `--turbopack` | `boolean` | Starts development mode using Turbopack. |
| `--webpack` | `boolean` | Starts development mode using Webpack. |
| `--inspect [[host:]port]` | `DebugAddress \| true` | Allows inspecting server-side code. |
| `--disable-source-maps` | `boolean` (false) | Disables Dev server source maps. |
| `--experimental-https` | `boolean` | Starts server with HTTPS using a self-signed certificate. |
| `--experimental-cpu-prof` | `boolean` | Enables CPU profiling; saves profiles to `.next-profiles/` on exit. |
| `--internal-trace [level]` | `'all' \| 'overview'` | Enables Turbopack tracing (`turbo-tasks` level or overview). |

Sources: [packages/next/src/bin/next.ts:297-374](https://github.com/blade47/next.js/blob/main/packages/next/src/bin/next.ts#L297-L374), [packages/next/src/cli/next-dev.ts:45-63](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-dev.ts#L45-L63)

## Production Build (`next build`)

### Build Mechanism and Trade-Offs
The `next build` command compiles the application for production deployment. Implemented in `packages/next/src/cli/next-build.ts`, it establishes process titles, configures signal handlers for CPU profile dumping on termination, and validates bundler compatibility. When invoked, `nextBuild` initializes environment options, validates project root existence via `existsSync(dir)`, and parses selective build path patterns when `--debug-build-paths` is provided.
Sources: [packages/next/src/cli/next-build.ts:39-170](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-build.ts#L39-L170)

### Build Sequence Flow
```mermaid
sequenceDiagram
    participant User
    participant NextBuild as nextBuild()
    participant Bundler as parseBundlerArgs()
    participant CoreBuild as build()

    User->>NextBuild: next build [options]
    NextBuild->>NextBuild: Set process.title & SIGINT/SIGTERM handlers
    NextBuild->>Bundler: parseBundlerArgs(options)
    alt experimentalAnalyze && !Turbopack
        NextBuild-->>User: Print error & exit (Incompatible bundler)
    end
    NextBuild->>CoreBuild: build(dir, experimentalAnalyze, profile, debug, ...)
    CoreBuild-->>NextBuild: Compilation Result / Error
    alt WEBPACK_ERRORS / BUILD_OPTIMIZATION_FAILED
        NextBuild-->>User: Print formatted error message & exit
    end
```
Sources: [packages/next/src/cli/next-build.ts:39-170](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-build.ts#L39-L170)

### Design Trade-Offs Table
| Design Choice | Benefit | Cost |
| :--- | :--- | :--- |
| **Mangling Disabled (`--no-mangling`)** | Preserves original variable names for readable stack traces during debugging. | Increases bundle size and reduces execution performance in production. |
| **Selective Build Paths (`--debug-build-paths`)** | Isolates compilation to specific route patterns, speeding up iterative debugging. | Skips full application graph validation, potentially missing cross-route type or export errors. |
| **Memory Debugging Mode (`--experimental-debug-memory-usage`)** | Enables hooks to trace heap allocations and identify memory leaks. | Adds tracking overhead, degrading peak build speed. |

Sources: [packages/next/src/cli/next-build.ts:76-99](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-build.ts#L76-L99)

## Production Server (`next start`)

### Startup Execution Mechanism
The `next start` command launches the Next.js production server for a pre-compiled application. Implemented in `packages/next/src/cli/next-start.ts`, it enforces start-time environment contracts and manages inspector attachments through strict sequencing: populating `NEXT_PRIVATE_START_TIME`, validating port reservation via `isPortIsReserved()`, opening the Node inspector via `inspector.open()`, attaching CPU profile signal handlers, and invoking `startServer()`.
Sources: [packages/next/src/cli/next-start.ts:6-91](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-start.ts#L6-L91)

> [!WARNING]
> Running `next start` without executing `next build` first will fail because production manifests (such as `routes-manifest.json` and build artifacts) will be missing from the `.next` directory.
Sources: [packages/next/src/cli/next-start.ts:42-90](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-start.ts#L42-L90)

### Startup Sequence
```mermaid
sequenceDiagram
    participant User
    participant NextStart as nextStart()
    participant Utils as get-reserved-port
    participant Server as startServer()

    User->>NextStart: next start [options]
    NextStart->>NextStart: Set NEXT_PRIVATE_START_TIME
    NextStart->>Utils: isPortIsReserved(port)
    alt Port Reserved
        Utils-->>NextStart: True
        NextStart-->>User: Print explanation & exit(1)
    end
    NextStart->>NextStart: Open inspector if --inspect supplied
    NextStart->>Server: startServer({ dir, isDev: false, hostname, port, keepAliveTimeout })
```
Sources: [packages/next/src/cli/next-start.ts:6-91](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-start.ts#L6-L91)

## System Diagnostics (`next info`)

### Diagnostics Collection Mechanism
The `next info` command collects and outputs environment diagnostics, binary versions, relevant package versions, and Next.js configuration properties to aid in bug reporting. Implemented in `packages/next/src/cli/next-info.ts`, it gathers system stats asynchronously across operating system properties, package manager binaries, package versions, and configuration outputs.
Sources: [packages/next/src/cli/next-info.ts:55-169](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-info.ts#L55-L169)

### Diagnostic Categories
- **Operating System**: Platform, architecture, OS version, total available memory in MB, and CPU core count via Node.js `os` module.
Sources: [packages/next/src/cli/next-info.ts:148-153](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-info.ts#L148-L153)
- **Binaries & Packages**: Node version, npm, Yarn, pnpm, and installed dependencies (`next`, `eslint-config-next`, `react`, `react-dom`, `typescript`, `next-rspack`).
Sources: [packages/next/src/cli/next-info.ts:136-160](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-info.ts#L136-L160)
- **Staleness Verification**: Queries npm registry dist-tags (`-/package/next/dist-tags`) to compare installed release against latest/canary versions using `parseVersionInfo()` and `getStaleness()`.
Sources: [packages/next/src/cli/next-info.ts:104-120](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/next-info.ts#L104-L120)

## Internal Trace & Static Route Analysis

### Static Route Analysis Mechanism
The Next.js CLI includes internal diagnostic commands for analyzing static route bundle sizes (`next internal static-routes-info`) and querying active Turbopack trace servers (`next internal query-trace`). Static route analysis partitions route files into 6 disjoint categories to prevent double-counting across pages and app router outputs.
Sources: [packages/next/src/cli/internal/static-routes-info.ts:2-79](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/static-routes-info.ts#L2-L79)

### File Categories Reference Table
| File Category | Description |
| :--- | :--- |
| `clientJs` | Client-side JavaScript bundles and chunks. |
| `clientCss` | Client-side stylesheet assets. |
| `clientMaps` | Client source map files. |
| `serverBundled` | Server-bundled JavaScript entries. |
| `serverUnbundled` | Server unbundled assets (e.g., traced `node_modules` dependencies). |
| `serverMaps` | Server source map files. |

Sources: [packages/next/src/cli/internal/static-routes-info.ts:61-79](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/static-routes-info.ts#L61-L79)

### Trace Server Query Client Flow
The `query-trace` CLI client communicates with a running Turbopack trace server via its Model Context Protocol (MCP) endpoint (`http://127.0.0.1:{port}/mcp`).
```mermaid
sequenceDiagram
    participant User
    participant CLI as queryTraceCli()
    participant Server as MCP Trace Server (Port 5748)

    User->>CLI: next internal query-trace [options]
    CLI->>Server: POST /mcp (JSON-RPC: tools/call, query_spans)
    alt Connection Refused
        Server-->>CLI: Error (Socket hang up / ECONNREFUSED)
        CLI-->>User: Print instructions to start `next internal trace <file>`
    end
    Server-->>CLI: HTTP 200 OK (Server-Sent Events stream)
    CLI->>CLI: Scan for "data: " lines & parse JSON
    CLI-->>User: Output formatted markdown or JSON response
```
Sources: [packages/next/src/cli/internal/query-trace.ts:21-106](https://github.com/blade47/next.js/blob/main/packages/next/src/cli/internal/query-trace.ts#L21-L106)

## Related

- [Configuration Loading](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-and-config/configuration-loading)
- [Telemetry and Diagnostics](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/technical/build-and-config/telemetry-and-diagnostics)


## Sitemap

See the full [sitemap](https://www.doc0.dev/docs/8f4009b0-65bd-4480-9b00-e201f0914bb3/llms.txt) for all pages in this wiki.
