Tutorials Logic, IN info@tutorialslogic.com
Nx

Nx - Modern Monorepo Platform Guide

A complete point-wise Nx guide for beginners and experienced developers covering monorepos, workspace structure, nx.json, caching, affected commands, Nx Cloud, generators, executors, module boundaries, and CI.

Nx 20+MonorepoCI/CDCachingPractice Questions

Published: Jan 2019 Updated: May 2026

What is Nx?

  • Nx is: an open-source build system and monorepo platform.
  • Old meaning: Nx originally stood for Nrwl Extensions and started strongly in the Angular ecosystem.
  • Modern use: Nx now supports Angular, React, Next.js, Vue, Node.js, Express, NestJS, Vite, Storybook, Jest, Playwright, ESLint, and package-based workspaces.
  • Main purpose: manage multiple apps and libraries in one repository without slow builds, duplicated tooling, or messy imports.
  • Nx 20+ package scope: use @nx/* packages for new work instead of older @nrwl/* packages.
  • Best value: project graph, task graph, affected commands, local cache, remote cache, distributed CI, generators, executors, and boundary rules.

Monorepo vs Polyrepo

TopicMonorepo with NxPolyrepo
RepositoryMany apps and libraries live in one repository.Each app or package usually has its own repository.
Shared codeShared directly through workspace libraries.Shared by publishing packages or copying logic.
Cross-project changeOne atomic commit can update app and library together.Changes often need multiple pull requests across repos.
ToolingCommands, linting, tests, builds, and versions stay consistent.Tooling and versions can drift over time.
CINx can run only affected projects and replay cached outputs.CI often rebuilds more than necessary.
Dependency versionsTeams can keep one dependency version policy.Different repos may use different versions.

Key Features in Modern Nx

FeatureMeaningWhy it matters
Smart CachingNx stores task outputs by input hash.Repeated builds, tests, and lint runs become much faster.
Affected CommandsNx finds projects touched by a change.CI runs only the work that can be impacted.
Project GraphVisual map of apps, libraries, and dependencies.Teams can understand architecture and import relationships.
Nx AgentsDistributed CI workers from Nx Cloud.Large pipelines run across multiple machines.
AtomizerSplits large test work into smaller tasks.Long e2e or unit test suites finish faster in CI.
Project CrystalPlugins infer tasks from config files.Less manual target configuration is needed.
Flakiness DetectionNx Cloud can identify unstable tasks.CI failures become easier to diagnose.

Why Use Nx?

  • Share code between frontend, backend, mobile, tooling, and test projects.
  • Run only affected builds, tests, lint checks, and e2e tasks.
  • Keep all teams on consistent generators, commands, and architecture rules.
  • Use local and remote caching to avoid repeating deterministic work.
  • Visualize dependencies with nx graph.
  • Enforce module boundaries so feature code does not import anything it wants.
  • Scale CI with Nx Cloud, remote cache, distributed task execution, and test splitting.

Nx Workspace Structure

Typical workspace layout
myworkspace/
  apps/
    web/
    api/
  libs/
    shared/ui/
    shared/data-access/
    feature/auth/
  tools/
  nx.json
  package.json
  tsconfig.base.json
  • apps/: deployable applications such as Angular apps, React apps, APIs, and e2e projects.
  • libs/: reusable libraries used by one or more apps.
  • tools/: workspace scripts, custom generators, and automation utilities.
  • nx.json: workspace-level Nx configuration.
  • package.json: dependencies and npm scripts.
  • tsconfig.base.json: TypeScript base config and path aliases such as @myorg/shared-ui.

nx.json Configuration

The nx.json file controls caching, named inputs, task pipelines, target defaults, plugins, and the default base branch.

nx.json example
{
  "$schema": "./node_modules/nx/schemas/nx-schema.json",
  "defaultBase": "main",
  "namedInputs": {
    "default": ["{projectRoot}/**/*", "sharedGlobals"],
    "production": ["default", "!{projectRoot}/**/*.spec.ts"]
  },
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "inputs": ["production", "^production"],
      "cache": true
    },
    "test": {
      "inputs": ["default", "^production"],
      "cache": true
    },
    "lint": {
      "inputs": ["default"],
      "cache": true
    }
  },
  "plugins": [
    "@nx/angular/plugin",
    "@nx/eslint/plugin"
  ]
}
  • defaultBase: branch used by affected commands when no base is passed.
  • namedInputs: reusable groups of files used for cache hashing.
  • targetDefaults: default behavior for build, test, lint, and custom targets.
  • dependsOn: ["^build"]: build dependencies first.
  • cache: true: allows Nx to cache and replay the task output.

Library Types in Nx

Library typeResponsibilityExample
FeatureBusiness workflows, route screens, smart/container components.libs/feature-auth
UIPresentational components with no business logic.libs/shared/ui
Data AccessAPI calls, services, state management, repositories, DTO mapping.libs/shared/data-access
UtilityPure helpers, constants, validators, types, formatters.libs/shared/utils
API / NodeBackend libraries, DTOs, server utilities, contracts.libs/api/orders

Getting Started with Nx

Create a new workspace

Create a new workspace
# Angular workspace
npx create-nx-workspace@latest myworkspace --preset=angular

# React workspace
npx create-nx-workspace@latest myworkspace --preset=react

# Empty workspace
npx create-nx-workspace@latest myworkspace --preset=empty

Add Nx to an existing project

Add Nx to an existing project
npx nx@latest init

Add framework plugins

Add framework plugins
npm install --save-dev @nx/angular
npm install --save-dev @nx/react
npm install --save-dev @nx/node
npm install --save-dev @nx/express
npm install --save-dev @nx/nest
npm install --save-dev @nx/next

Generate apps and libraries

Generate apps and libraries
nx g @nx/angular:application myapp
nx g @nx/angular:library mylib
nx g @nx/react:application my-react-app
nx g @nx/node:application my-api

Common Nx Commands

CommandUse
nx serve myappServe an app locally.
nx build myappBuild an app.
nx test myappRun tests for a project.
nx lint myappLint a project.
nx graphOpen dependency graph.
nx show projectsList all projects.
nx run-many --target=buildRun build for all or selected projects.
nx migrate latestMigrate Nx and plugins to the latest version.
npx nx connectConnect workspace to Nx Cloud.
nx resetClear local cache and reset the Nx daemon.

Affected Commands - Run Only What Changed

Nx compares your current branch with a base branch, finds changed files, walks the project graph, and runs tasks only for projects that are directly or indirectly impacted.

Affected command examples
nx affected --target=build
nx affected --target=test
nx affected --target=lint
nx affected --target=build --base=main
nx affected --target=build --base=HEAD~1
nx affected:graph
nx affected --target=build --parallel=3
  • Directly affected: a project has changed files inside its own root.
  • Transitively affected: a project depends on another changed project.
  • CI benefit: a small pull request does not need to rebuild and retest the full workspace.
  • Important: CI must fetch enough Git history for base/head comparison to work correctly.

Nx Caching Explained

Cache typeMeaningBenefit
Local cacheStored on your machine, usually under .nx/cache.Repeated local tasks can replay instantly.
Remote cacheShared through Nx Cloud.Team members and CI can reuse each other's task outputs.
Task hashHash created from source files, config, dependencies, and inputs.Nx knows when cached output is still valid.
Cache replayNx restores terminal output and generated files.Fast feedback without rerunning deterministic work.
Enable caching in nx.json
{
  "targetDefaults": {
    "build": { "cache": true },
    "test":  { "cache": true },
    "lint":  { "cache": true }
  }
}
Clear local cache
nx reset

Nx Cloud and Distributed CI

  • Remote caching: share task results across developers and CI machines.
  • Nx Agents: distribute tasks across multiple CI machines.
  • Atomizer: split long test suites into smaller tasks for parallel execution.
  • Flaky task help: detect unstable tasks and make CI debugging easier.
  • CI insights: understand slow tasks, cache misses, and pipeline behavior.
Connect to Nx Cloud
npx nx connect
npx nx-cloud start-ci-run --distribute-on="3 linux-medium-js"

Executors and Generators

ConceptMeaningExample
GeneratorCreates or updates code and configuration.nx g @nx/angular:library shared-ui
ExecutorRuns a target such as build, serve, test, lint, or e2e.@nx/webpack:webpack
TargetNamed task configured for a project.build, serve, test
Custom generatorTeam-specific scaffold logic.Create approved library structure automatically.
project.json targets example
{
  "name": "my-app",
  "targets": {
    "build": {
      "executor": "@nx/webpack:webpack",
      "options": { "outputPath": "dist/apps/my-app" }
    },
    "serve": {
      "executor": "@nx/webpack:dev-server",
      "options": { "buildTarget": "my-app:build" }
    },
    "test": {
      "executor": "@nx/jest:jest",
      "options": { "jestConfig": "apps/my-app/jest.config.ts" }
    }
  }
}

Module Boundary Enforcement

Nx uses tags and ESLint rules to stop invalid imports between libraries.

Module boundary ESLint rules
{
  "rules": {
    "@nx/enforce-module-boundaries": ["error", {
      "depConstraints": [
        {
          "sourceTag": "type:feature",
          "onlyDependOnLibsWithTags": ["type:ui", "type:data-access", "type:util"]
        },
        {
          "sourceTag": "type:ui",
          "onlyDependOnLibsWithTags": ["type:util"]
        },
        {
          "sourceTag": "type:data-access",
          "onlyDependOnLibsWithTags": ["type:util"]
        }
      ]
    }]
  }
}
  • Tag libraries in project.json, for example "tags": ["type:ui", "scope:shared"].
  • Run nx lint to catch invalid imports.
  • Use tags such as type:feature, type:ui, type:data-access, scope:admin, and platform:web.
  • Boundary rules are important because a monorepo can become tangled without import discipline.

Nx vs Angular CLI

FeatureAngular CLINx
Multiple apps in one repoYesYes
Smart build cachingNo built-in Nx-style cacheYes
Affected commandsNoYes
Dependency graphLimitedYes
Distributed CINoYes, with Nx Cloud
Multi-framework supportAngular-focusedAngular, React, Vue, Node, Next, Nest, and more
Module boundary enforcementNo built-in monorepo boundary systemYes
GeneratorsYesYes, plus workspace/custom generators
Remote cachingNoYes, with Nx Cloud
Task pipeline configurationLimitedYes

Quick Reference Cheatsheet

CommandPurpose
nx serve <app>Serve an application locally.
nx build <app>Build an application.
nx test <project>Run tests.
nx lint <project>Run lint checks.
nx graphOpen dependency graph.
nx affected --target=buildBuild only affected projects.
nx affected --target=testTest only affected projects.
nx run-many --target=buildBuild all or selected projects.
nx g @nx/angular:appGenerate Angular app.
nx g @nx/angular:libGenerate Angular library.
nx g @nx/react:appGenerate React app.
nx g @nx/node:appGenerate Node app.
nx migrate latestUpdate Nx and plugins.
nx resetClear cache and reset daemon.
npx nx connectConnect to Nx Cloud.

25 Most Important Practice Questions

1. What is Nx?
Answer: Nx is an open-source build system and monorepo platform for managing multiple apps and libraries efficiently.
2. What problem does Nx solve?
Answer: It solves slow builds, duplicated tooling, shared-code complexity, CI waste, and architecture drift in large workspaces.
3. Is Nx only for Angular?
Answer: No. Nx supports Angular, React, Vue, Next.js, Node.js, NestJS, Express, Vite, and package-based workspaces.
4. What is the difference between monorepo and polyrepo?
Answer: A monorepo keeps many projects in one repository; a polyrepo keeps projects in separate repositories.
5. What is an app in Nx?
Answer: An app is a deployable unit such as a web app, API, mobile app, or e2e project.
6. What is a library in Nx?
Answer: A library is reusable code shared across apps, usually organized as feature, UI, data-access, utility, or API code.
7. What is the Nx project graph?
Answer: It is Nx's map of all projects and dependencies in the workspace.
8. What command opens the project graph?
Answer: nx graph.
9. What are affected commands?
Answer: Commands that run targets only for projects impacted by current code changes.
10. How does Nx find affected projects?
Answer: Nx compares changed files against a base branch and traverses the project graph to find direct and transitive impact.
11. What is Nx caching?
Answer: Nx stores task outputs using a hash of inputs so identical tasks can be replayed instead of rerun.
12. What is local cache?
Answer: Cache stored on the developer's machine, usually under .nx/cache.
13. What is remote cache?
Answer: Cache shared across team members and CI through Nx Cloud.
14. What is Nx Cloud?
Answer: A service for remote caching, CI insights, distributed execution, flaky task help, and task splitting.
15. What are Nx Agents?
Answer: CI workers that distribute Nx tasks across multiple machines.
16. What is Nx Atomizer?
Answer: A feature that splits large test suites into smaller parallel tasks to speed up CI.
17. What is Project Crystal?
Answer: Nx's inferred-task approach where plugins detect targets from existing config files.
18. What is an Nx generator?
Answer: A tool that scaffolds or updates code and configuration consistently.
19. What is an Nx executor?
Answer: A tool that runs a target such as build, serve, test, lint, or e2e.
20. What is nx.json?
Answer: The workspace-level Nx configuration file for named inputs, target defaults, caching rules, plugins, and base branch settings.
21. What is project.json?
Answer: A project-level config file that defines targets, executors, options, tags, and metadata for one project.
22. What is @nx/enforce-module-boundaries?
Answer: An ESLint rule that uses project tags to prevent invalid imports between libraries.
23. What is the difference between nx run-many and nx affected?
Answer: run-many runs a target for all or selected projects; affected runs only projects impacted by changes.
24. What is nx reset?
Answer: A command that clears local Nx cache and resets the Nx daemon.
25. What is Nx Console?
Answer: A VS Code extension that provides a GUI for Nx commands, generators, project graph, and target execution.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.