Nx Workspace Patterns
Configure and optimize Nx monorepo workspaces with deterministic project-graph structure, boundary enforcement, cache-aware pipelines, and affected-command CI workflows; use when designing workspace architecture, tightening dependency rules, or reducing CI cost through Nx task orchestration.
npx skills add github:pantheon-org/tekhne --skill repository-mgmt--nx--workspace-patternsNavigation hub for Nx workspace architecture and operations.
When to Use
- You are structuring or refactoring an Nx monorepo.
- You need dependency boundaries enforced by tags and lint rules.
- You need reliable affected-command CI and caching performance.
When Not to Use
- The repository is single-project with no monorepo coordination needs.
- The task is framework-specific build setup unrelated to Nx graph and task orchestration.
Workflow
- Structure workspace domains (
apps/,libs/,tools/). - Define tags and project graph conventions.
- Configure target pipelines and caching defaults.
- Enforce module boundaries and verify violations fail with
nx lint --skip-nx-cache. - Integrate affected commands in CI with explicit base/head strategy.
Constraint Guidelines
Hard Constraints
- MUST tag projects consistently for scope/type-based constraints.
- MUST configure
targetDefaultsfor build/test/lint dependency flow. - MUST use affected commands in CI for scalable execution.
Flexible Choices
- CAN choose tag vocabulary (
scope:*,type:*,platform:*) if consistent. - CAN choose cache backend (Nx Cloud or self-hosted) by org constraints.
- CAN choose library granularity based on team ownership and release cadence.
Fallback Behaviors
| Missing Config | Fallback |
|---|---|
| no explicit tags | allow broad deps temporarily with warning and migration plan |
| no target defaults | tasks run independently with reduced optimization |
| no CI base/head | default to main branch and document tradeoff |
Quick Commands
nx graph
nx affected -t lint,test,build --base=origin/main --parallel=3
nx show project my-app --web
nx reset
rg -n "@nx/enforce-module-boundaries|depConstraints" .
Configuration Examples
nx.json targetDefaults
{
"targetDefaults": {
"build": {
"dependsOn": ["^build"],
"inputs": ["production", "^production"],
"cache": true
},
"test": {
"dependsOn": ["build"],
"inputs": ["default", "^production", "{workspaceRoot}/jest.preset.js"],
"cache": true
},
"lint": {
"inputs": ["default", "{workspaceRoot}/.eslintrc.json"],
"cache": true
}
}
}
ESLint depConstraints (tag-based boundaries)
{
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {
"@nx/enforce-module-boundaries": [
"error",
{
"enforceBuildableLibDependency": true,
"allow": [],
"depConstraints": [
{
"sourceTag": "scope:web",
"onlyDependOnLibsWithTags": ["scope:web", "scope:shared"]
},
{
"sourceTag": "type:feature",
"onlyDependOnLibsWithTags": ["type:feature", "type:ui", "type:data-access", "type:util"]
},
{
"sourceTag": "type:ui",
"onlyDependOnLibsWithTags": ["type:ui", "type:util"]
}
]
}
]
}
}
]
}
Anti-Patterns
NEVER create circular dependencies between projects
- WHY: cycles degrade graph clarity and destabilize build ordering.
- BAD:
libs/uidepends onlibs/datawhilelibs/datadepends onlibs/ui. - GOOD: extract shared contracts to a lower-level library.
NEVER run run-many --all in CI as the default verification path
- WHY: full-workspace execution wastes CI budget and slows feedback loops.
- BAD: always build/test every project on each PR.
- GOOD: use
nx affectedwith explicit base/head.
NEVER tag projects inconsistently
- WHY: boundary rules are only as strong as tag consistency.
- BAD: mixed ad hoc tags with no vocabulary.
- GOOD: defined tag taxonomy with lint enforcement.
NEVER skip target pipeline dependencies in targetDefaults
- WHY: missing
dependsOnprevents optimal scheduling and can hide ordering bugs. - BAD: implicit task order assumptions.
- GOOD: explicit
dependsOnfor build/test/lint behavior.
NEVER ignore cache inputs and outputs for critical targets
- WHY: incomplete cache metadata causes stale hits or unnecessary misses.
- BAD: cache enabled but no stable inputs/outputs.
- GOOD: declare outputs and relevant named inputs per target.
References
| Topic | Reference |
|---|---|
| Project graph and nx.json patterns | references/project-graph-configuration.md |
| Caching and optimization | references/caching-strategies.md |
| Boundaries and tags | references/project-boundaries.md |
| Affected commands and CI | references/affected-commands.md |
Explicit NEVER/WHY/consequence triplets with side-by-side bad/good examples. Generic warnings score low — concrete failure modes with real impact (security, correctness, performance) score high.
Runtime validation via eval scenarios proving the skill actually changes agent behaviour. Requires evals/ directory, instructions.json, ≥3 scenarios, and ≥80% instruction coverage in summary.json.
Appropriate rigidity for the skill type: strict rules for critical/security skills, balanced steps for process skills, flexible options for tool skills. Mismatched calibration (too rigid or too loose) reduces score.
Expert-only knowledge the AI couldn't derive on its own — domain-specific patterns, production gotchas, decision frameworks, and non-obvious tool behaviour. High scores mean <5% redundancy with what the model already knows.
A clear philosophy plus numbered step-by-step workflows with explicit entry/exit points. Should answer: what is the core principle, how to execute it, and when (and when not) to apply it.
Rich activation keywords and trigger scenarios in the description so the skill fires when needed. Best descriptions read like an exhaustive list of the tasks and concepts that should invoke this skill.
Copy-paste-ready code, complete runnable examples, real file paths and commands. Pseudocode and abstract descriptions score low — concrete, executable content scores high.
SKILL.md as a <100-line navigation hub pointing to focused references/ files. Content should be lazy-loaded on demand, not front-loaded. Includes actionable 'When to Use' conditions per reference.
Proper frontmatter, single-task focus, activation keywords, and cross-harness portability. Skills must work across 40+ agentic harnesses without hardcoded paths or agent-specific references.
Expert-only knowledge the AI couldn't derive on its own — domain-specific patterns, production gotchas, decision frameworks, and non-obvious tool behaviour. High scores mean <5% redundancy with what the model already knows.
A clear philosophy plus numbered step-by-step workflows with explicit entry/exit points. Should answer: what is the core principle, how to execute it, and when (and when not) to apply it.
Explicit NEVER/WHY/consequence triplets with side-by-side bad/good examples. Generic warnings score low — concrete failure modes with real impact (security, correctness, performance) score high.
Proper frontmatter, single-task focus, activation keywords, and cross-harness portability. Skills must work across 40+ agentic harnesses without hardcoded paths or agent-specific references.
SKILL.md as a <100-line navigation hub pointing to focused references/ files. Content should be lazy-loaded on demand, not front-loaded. Includes actionable 'When to Use' conditions per reference.
Appropriate rigidity for the skill type: strict rules for critical/security skills, balanced steps for process skills, flexible options for tool skills. Mismatched calibration (too rigid or too loose) reduces score.
Rich activation keywords and trigger scenarios in the description so the skill fires when needed. Best descriptions read like an exhaustive list of the tasks and concepts that should invoke this skill.
Copy-paste-ready code, complete runnable examples, real file paths and commands. Pseudocode and abstract descriptions score low — concrete, executable content scores high.
No eval scenarios available.
Affected Commands
Use this reference for CI and local workflows that execute only changed scope.
Core Commands
nx affected -t lint --base=origin/main
nx affected -t test --base=origin/main
nx affected -t build --base=origin/main
CI Integration
- Ensure full git history or sufficient fetch depth for SHA resolution.
- Use CI-provided base/head SHAs when available.
- Keep affected target set aligned with required quality gates.
Base/Head Strategy
- PR pipelines: base = target branch, head = PR commit.
- Main branch pipelines: compare against previous successful commit.
Troubleshooting
- If affected scope is unexpectedly large, inspect changed files and named inputs.
- If unexpectedly small, verify base/head derivation and fetch depth.
Caching Strategies
Use this reference to optimize local and CI task execution.
Local Cache Basics
- Enable caching for stable targets (
build,test,lint,e2e). - Ensure target
outputsare explicit when artifacts are produced. - Keep named inputs focused; avoid over-broad invalidation.
Remote Cache Options
- Nx Cloud for managed remote caching.
- Self-hosted runners/plugins for regulated environments.
Optimization Patterns
- Use
dependsOnwith^buildwhere dependency builds are required. - Keep CI parallelism tuned to compute resources.
- Reset cache after significant executor/plugin refactors.
Common Pitfalls
- Cache enabled but no outputs declared.
- Shared config files missing from named inputs.
- Mixing inconsistent environment variables across CI jobs.
Project Boundaries
Use this reference to enforce dependency constraints and ownership boundaries.
Tagging Strategy
Define a small stable vocabulary, for example:
type:app,type:feature,type:ui,type:data-access,type:utilscope:web,scope:api,scope:shared
Boundary Enforcement
Use @nx/enforce-module-boundaries with depConstraints to encode rules.
Principles:
- apps depend downward on feature/data/ui/util layers.
- util libraries remain dependency sinks.
- scopes import within scope unless explicitly shared.
Rule Hygiene
- Keep constraints understandable; avoid overfitting edge cases.
- Add tests or intentional-violation checks during rule changes.
- Update tag docs whenever the taxonomy changes.
Project Graph Configuration
Use this reference for nx.json and graph-level configuration patterns.
Workspace Shape
workspace/
apps/
libs/
tools/
nx.json
nx.json Core Ideas
- Set
affected.defaultBaseto your primary integration branch. - Define
namedInputsso build/test/lint can share deterministic input sets. - Use
targetDefaultsto keep task behavior consistent across projects.
Implicit Dependencies
Use implicit/global inputs for files that impact many projects, such as:
- root TypeScript config
- lint config
- shared build or test presets
Graph Visualization Tips
- Run
nx graphduring architecture changes. - Validate that feature and shared layers remain acyclic.
- Use graph views in PR reviews for dependency-heavy changes.