How does Nx see a Python project in a polyglot monorepo?

An Nx Python monorepo is a single repository where Nx orchestrates Python services and TypeScript packages with the same task runner, cache, and project graph. Nx does not need to understand Python to do this. Any directory that has project configuration, such as a project.json or a project inferred by a plugin, becomes a node in the graph. Its targets run as ordinary shell commands like uv run pytest or uv build. Nx tracks which files a task reads, hashes them, and replays cached output when nothing relevant has changed.

What Nx does not do is read Python source. For TypeScript, Nx's JavaScript support analyzes import statements and package.json dependencies to draw edges between projects automatically. For Python, no equivalent analysis happens. If services/billing imports from libs/py-common, Nx has no record of that unless you supply one. That information can come from two places: a plugin that reads each member's pyproject.toml and turns declared dependencies into graph edges, or implicitDependencies entries that you maintain by hand.

Teams accept this extra work because of what a shared repo gives them. A change that touches a TypeScript API and the Python worker that consumes its payloads produces one nx affected result and one set of target names (test, lint, build) across both languages.

This guide's core claim is that the arrangement only holds up when two things are explicit: the Python dependency graph and the API contract between the TypeScript and Python sides. If either one is implicit, affected will skip projects that actually changed behavior.

      Nx project graph: one repo, one task runner, one cache

   TypeScript side                     Python side
   edges inferred from imports         Python imports are NOT parsed;
   and package.json                    edges must be supplied

 +-----------------+   API contract    +--------------------+
 | apps/api        |------------------>| services/billing   |
 | (project.json)  |  explicit edge    | (pyproject.toml)   |
 +-----------------+                   +--------------------+
          |                                      |
          | auto edge                            | edge from plugin reading
          v                                      | pyproject.toml, or from
 +-----------------+                             | implicitDependencies
 | libs/ts-types   |                             v
 +-----------------+                   +--------------------+
                                       | libs/py-common     |
                                       +--------------------+
          |                                      |
          +------------------+-------------------+
                             |
                             v
 +-------------------------------------------------------------+
 | Same targets in both languages: test | lint | build        |
 | Run as shell commands, e.g. uv run pytest, uv build         |
 | Inputs hashed; cached output replayed when unchanged        |
 | One nx affected result across TS and Python changes         |
 +-------------------------------------------------------------+

Nx infers TypeScript edges from imports and package.json, but Python edges come only from a pyproject.toml-reading plugin or hand-written implicitDependencies, and the TypeScript-to-Python API contract must also be an explicit edge so that one shared nx affected result covers both languages.

How does an Nx Python monorepo work, step by step?

Nx and uv split the work. uv owns the Python environment: it resolves dependencies for every workspace member, writes uv.lock, and installs packages into a virtual environment. Nx owns orchestration: which tasks run, in what order, and whether they need to run at all. Nx never creates or activates a virtual environment itself. It runs the commands you give it, and those commands call uv run to enter the environment.

When you run a command such as nx affected -t test, the sequence is:

  1. Build the project graph. Nx reads project.json files and any plugin-inferred projects, then adds edges. TypeScript edges come from imports and package.json. Python edges come from a plugin reading pyproject.toml or from implicitDependencies.
  2. Find affected projects. Nx asks git which files changed between a base and a head commit, maps each file to the project that owns it, and then walks the graph to add every project that depends on a changed one. Changes to global inputs, such as a root lockfile, can mark many projects at once.
  3. Build the task graph. For each affected project that has the requested target, Nx creates a task. dependsOn adds prerequisite tasks, for example running build on upstream libraries before a service's docker-build.
  4. Hash each task. Nx computes a hash from the task's inputs: matching files, runtime command output, env values, and, via ^ inputs, the relevant files of the projects it depends on.
  5. Check the cache. If a task with the same hash has run before, locally or in a configured remote cache, Nx restores the declared outputs and replays the terminal output without running the command. On a miss, it runs the command and stores the result.

Each step depends on configuration you supply. Missing edges break step 2, missing dependsOn entries break step 3, and missing inputs break step 4. The rest of this guide covers how to get each of those right for Python.

Who should use an Nx Python monorepo?

This setup suits a fairly specific kind of team:

  • Teams with TypeScript APIs and Python services that change together. A typical case is a TypeScript backend-for-frontend or public API in front of Python services that do data processing, ML inference, or billing logic, where a single feature often touches both sides.
  • Organizations already using Nx for TypeScript. The task runner, caching setup, and CI conventions are already in place. Adding Python projects extends them instead of introducing a second build system.
  • Teams with several Python services sharing internal libraries. A uv workspace with shared packages benefits from affected detection even without the TypeScript side. Nx adds most value when that Python graph also connects to TypeScript consumers.
  • Teams that can assign an owner for build configuration. Someone, often a platform or developer-experience engineer, has to maintain plugin versions, cache inputs, and contract edges. Without an owner, the graph drifts and affected becomes unreliable.

If your Python and TypeScript code rarely change in the same pull request, or nobody can own the configuration, look at the alternatives in the last section before you adopt this.

Should you use an Nx uv plugin or plain run-commands targets?

The first decision is how Nx learns about the Python side at all. You have two options: a community Nx plugin that understands uv, or nx:run-commands targets that you write in each project.json.

Concern Community uv plugin Hand-written run-commands
Project scaffolding Generators create a package, pyproject.toml and targets in one step You copy an existing project and edit it
Targets Inferred from project files, so new projects get lint, test and build automatically Declared explicitly in each project.json
Graph edges Derived from uv workspace members and path dependencies Added by hand with implicitDependencies
Extra dependency One more package in the toolchain None beyond Nx and uv
Debugging You may need to read plugin source to see why an edge or input exists The command Nx runs is the command you wrote

The plugin's main advantage is the graph. When Nx reads dependencies from pyproject.toml, the edges stay in sync with what uv actually installs, and affected stays correct without anyone having to remember an update. Hand-written edges drift. The usual failure is that someone adds a path dependency and forgets the matching implicitDependencies entry.

Community plugins are maintained outside the core Nx team. Their support for a new Nx or uv release can arrive late, and inference rules can change between their releases. Pin the plugin version exactly, and upgrade it in the same tested change as Nx itself.

Decision rule: if you have only a few Python projects and their dependencies rarely change, use run-commands. If you have more than a handful of projects, or teams add packages and dependencies regularly, use a plugin.

How do you structure a uv workspace so each member maps to one Nx project?

Put a single pyproject.toml at the repository root that declares the workspace under [tool.uv.workspace], with members globs such as services/* and libs/py/*. uv then resolves every member together and writes one uv.lock at the root. A single lockfile means a shared library and the services that import it always resolve to the same third-party versions. It also gives Nx one file to treat as a global input, so a dependency bump invalidates the cache for every Python project.

Each member has its own pyproject.toml and its own project.json. A service that consumes a shared library lists the library by name in dependencies and marks it { workspace = true } under [tool.uv.sources]. uv installs the library as an editable package instead of fetching it from an index. That same declaration is what an inference plugin, or your own implicitDependencies, turns into a graph edge.

Give Python projects the same target names your TypeScript projects use. When the names match, nx run-many -t lint test and nx affected -t typecheck work across both languages without special cases.

Target Runs Typical Python tool
lint Static style and correctness checks ruff, or your existing linter
typecheck Type analysis mypy or pyright
test Unit tests pytest
build Wheel or sdist uv build --package <name>
serve Local dev server your ASGI/WSGI runner

Wrap each target in uv run --package <name> so it runs inside the synced environment.

Nx does not manage editors or type checkers. Configure virtual-environment discovery and import-path resolution separately for each tool, for example in your pyright or mypy settings and your editor's interpreter selection.

{
  "name": "orders-api",
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "projectType": "application",
  "sourceRoot": "services/orders-api/src",
  "implicitDependencies": ["py-shared"],
  "targets": {
    "lint": {
      "executor": "nx:run-commands",
      "options": { "command": "uv run --package orders-api ruff check src tests", "cwd": "{projectRoot}" },
      "inputs": ["default", "{workspaceRoot}/uv.lock"],
      "cache": true
    },
    "typecheck": {
      "executor": "nx:run-commands",
      "options": { "command": "uv run --package orders-api mypy src", "cwd": "{projectRoot}" },
      "inputs": ["default", "^default", "{workspaceRoot}/uv.lock"],
      "cache": true
    },
    "test": {
      "executor": "nx:run-commands",
      "options": { "command": "uv run --package orders-api pytest", "cwd": "{projectRoot}" },
      "inputs": ["default", "^default", "{workspaceRoot}/uv.lock"],
      "cache": true
    },
    "build": {
      "executor": "nx:run-commands",
      "options": { "command": "uv build --package orders-api", "cwd": "{workspaceRoot}" },
      "inputs": ["default", "^default", "{workspaceRoot}/uv.lock"],
      "outputs": ["{workspaceRoot}/dist"],
      "cache": true
    },
    "serve": {
      "executor": "nx:run-commands",
      "options": { "command": "uv run --package orders-api uvicorn orders_api.main:app --reload", "cwd": "{projectRoot}" }
    }
  }
}

A project.json for a Python service in a uv workspace that exposes the same lint, typecheck, test, build and serve targets as the TypeScript projects, runs each through uv run --package, and treats the root uv.lock as a cache input.

How do you make the Python project graph and cache inputs trustworthy?

Start by checking the graph instead of trusting it. Run nx graph and confirm that every service has an edge to the shared libraries it imports. Then test the edges directly: touch a file in a shared library and run nx show projects --affected. If a consumer is missing from the list, the graph is wrong. Treat that as a correctness bug, not a cosmetic one, because nx affected will skip that consumer's tests and CI will pass.

Plugins infer edges from declared dependencies and static imports. They cannot see importlib calls, plugin registries loaded by string, or a shared logging.yaml read at runtime. Declare those relationships with implicitDependencies in the consuming project's configuration.

Next, define a named input for Python targets. It should cover:

  • source files
  • pyproject.toml
  • the lockfile
  • .python-version
  • a runtime input such as python --version combined with the platform
  • an env input for every variable that changes behavior

Give each target explicit outputs, for example the dist directory and the JUnit or coverage reports. Without them, a cache hit restores nothing useful.

Under-specified inputs cause stale cache hits. If you leave out the interpreter version, a test run from Python 3.11 can be replayed as a pass on 3.12. A single workspace lockfile has the opposite effect: any dependency bump invalidates every Python project's cache. Accept that cost, or scope the inputs if your tooling can.

Remote cache hits carry more risk for Python because native wheels are platform-specific. An artifact built on macOS ARM is not valid on Linux x86. Disable caching (cache: false) for targets that depend on network state or that publish artifacts.

// nx.json (Nx reads this file with comments allowed)
{
  "namedInputs": {
    // Everything that can change a Python target's result
    "python": [
      "{projectRoot}/**/*.py",
      "{projectRoot}/pyproject.toml",
      // One shared lockfile: any bump invalidates every Python project
      "{workspaceRoot}/uv.lock",
      "{workspaceRoot}/.python-version",
      // Interpreter and platform, so 3.11/x86 never replays as 3.12/ARM
      { "runtime": "python --version" },
      { "runtime": "uname -sm" },
      // Env vars that change behavior must be part of the hash
      { "env": "APP_SETTINGS_PROFILE" }
    ]
  },
  "targetDefaults": {
    "test": {
      "cache": true,
      "inputs": ["python", "^python"],
      // Without outputs, a cache hit restores no reports
      "outputs": [
        "{workspaceRoot}/reports/{projectRoot}/junit.xml",
        "{workspaceRoot}/reports/{projectRoot}/coverage.xml"
      ]
    },
    "build": {
      "cache": true,
      "inputs": ["python", "^python"],
      "outputs": ["{projectRoot}/dist"]
    },
    // Publishing has side effects; never replay it from cache
    "publish": {
      "cache": false
    }
  }
}

An nx.json that defines a shared Python named input (source, pyproject.toml, lockfile, version marker, runtime, env), declares explicit test and build outputs, and disables caching for publish.

How do you make the TypeScript-to-Python API contract a graph edge?

Python and TypeScript share no import statements, so Nx cannot infer the dependency between a FastAPI service and the TypeScript code that calls it. You have to declare it, and the cleanest place to anchor it is a file that changes whenever the contract changes.

Use three projects. First, give the Python service an export-openapi target that writes the schema to a known path, such as dist/openapi.json. For FastAPI, that can be a short script that serializes app.openapi(). Declare that path in outputs, and set inputs to the service's source files and lockfile so the target is cacheable. Second, create an api-client project whose generate target lists export-openapi from the service in dependsOn and reads the emitted schema. Third, make the TypeScript APIs import api-client as an ordinary workspace package. Nx infers that edge from the imports. Add implicitDependencies from api-client to the Python service as well. The task dependency only orders execution. The implicit dependency is what puts the client and its consumers in the affected set when only Python files change.

The cost appears in TypeScript workflows. Typechecking the consumers now runs the client generator, which runs the Python export, so a TypeScript-only contributor needs uv, the right interpreter, and a synced environment. CI runners for TypeScript jobs need the same setup.

To avoid this, commit the generated schema and make it the client's only input. Python contributors regenerate it as part of their change, and CI fails if the regenerated file differs from the committed one. TypeScript work then never invokes Python, and the schema diff shows up in review alongside the code that caused it.

{
  "name": "api-client",
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "libs/api-client/src",
  "projectType": "library",
  "implicitDependencies": ["orders-service"],
  "targets": {
    "generate": {
      "executor": "nx:run-commands",
      "dependsOn": [
        { "projects": ["orders-service"], "target": "export-openapi" }
      ],
      "inputs": [
        "{workspaceRoot}/apps/orders-service/dist/openapi.json"
      ],
      "outputs": ["{projectRoot}/src/generated"],
      "options": {
        "command": "npx openapi-typescript apps/orders-service/dist/openapi.json -o libs/api-client/src/generated/schema.d.ts"
      }
    },
    "typecheck": {
      "executor": "nx:run-commands",
      "dependsOn": ["generate"],
      "options": {
        "command": "tsc -p libs/api-client/tsconfig.lib.json --noEmit"
      }
    }
  }
}

The api-client project.json: dependsOn runs the Python service's export-openapi target before generation, while implicitDependencies puts api-client and its TypeScript importers in nx affected when only Python files change.

Running nx affected in CI and building per-service container images

The CI job needs both toolchains before Nx starts. Install Node and your package manager, install uv, then run uv sync --frozen at the workspace root. --frozen makes uv install exactly what uv.lock records and fail rather than re-resolve, so every Python target Nx runs uses the same environment the lockfile describes. Cache uv's download cache under its own key, derived from uv.lock, and keep it separate from the Nx task cache. The two change for different reasons: a dependency bump should refresh wheels without wiping cached test results, and a source edit should do the opposite. Running uv cache prune --ci before saving keeps that cache from growing with wheels that are cheap to rebuild.

Then run nx affected -t lint test docker-build against the merge base.

Model the image build as a docker-build target with dependsOn pointing at the project's own build and at ^build. That way, upstream workspace members are built first. Inside the target, run uv export --package <service> --frozen --no-dev to write a requirements file that contains only that service and the workspace members it depends on. Set the target's inputs to the service's sources, its dependencies' sources, uv.lock, and the Dockerfile. Nx then skips the image when none of those changed, instead of rebuilding every container on each merge.

Illustrative estimate, with assumed inputs: 12 services, 6-minute test-and-image cost per service, a typical change affecting 3 services. Running everything takes 72 minutes of runner time per pipeline. Running only the affected projects takes 18 minutes, which saves 54 minutes per run before any cache hits.

How can an Nx Python monorepo save engineering time?

The time savings come from four places, and only the first is about CI minutes.

Less work per pipeline. nx affected limits a run to changed projects and their dependents, as in the estimate above. The task cache then removes repeat work inside that set. A retried pipeline after a flaky failure, or a second push that only changes one service, replays cached results for every task whose inputs did not change. With a remote cache configured, a result computed in CI can also be reused on a developer's machine, and the reverse.

Shorter waits for developers. Running nx affected -t lint test locally before pushing checks the same scope CI will check. Developers get the failure in minutes on their own machine instead of after a queued pipeline. Cache hits make re-running after a small edit cheap, which encourages people to run checks at all.

One command surface across languages. With matching target names, a TypeScript engineer can run the Python tests a change affects without learning which test runner, flags, or virtual environment each service uses, and a Python engineer can do the same for TypeScript. New contributors learn one set of commands, and CI configuration does not need a separate job definition per language and service.

Fewer cross-language coordination cycles. When the API contract is a graph edge, a breaking change to a Python service's schema fails the TypeScript typecheck in the same pull request. Without that edge, the same break is usually found after deployment or after a client package is published and upgraded. At that point, fixing it takes a second change, a second review, and often a second release in another repository.

Illustrative estimate, with assumed inputs: a team merges 15 pull requests per day, 20% of them change a Python service's API contract, and 1 in 10 of those would otherwise ship a client-breaking change that is found after merge, costing an assumed 2 engineer-hours to diagnose, fix, and re-release. That is 15 × 0.2 × 0.1 = 0.3 incidents per day, or about 0.6 engineer-hours per working day that the contract edge moves into normal review. Your numbers will differ. Measure your own rate of cross-language breakages before you rely on this argument.

These savings disappear if the graph is wrong. A missing edge produces a faster pipeline that skips the tests that mattered, so the verification steps in the graph section are part of the time savings, not overhead on top of them.

When should you avoid an Nx polyglot monorepo, and what are the alternatives?

Those savings depend on one assumption: that changes regularly cross the language boundary. The setup pays off when a TypeScript API and its Python consumers change in the same pull request, share a contract, and need nx affected to catch the downstream breakage. If those things rarely happen, you pay the costs and get little back.

The costs are ongoing. Every contributor needs Node, a package manager, uv, and a matching Python interpreter installed, including the data engineer who never touches TypeScript. Nx's built-in inference does not cover Python. Whether you use a plugin or hand-written targets, someone must keep dependency declarations, cache inputs, and contract edges accurate as services are added. When that upkeep lapses, affected silently skips projects that should have run. That is worse than running everything.

Avoid this setup if your Python services rarely interact with the TypeScript code, if the team is small enough that a full CI run is cheap, or if nobody will own the manual graph declarations.

Alternative Fits when What you give up
Separate repos, published client package Contract changes are infrequent and can be versioned Atomic cross-language changes; you coordinate releases instead
Python-only uv workspace with a lighter task runner Python services interact mostly with each other Affected detection and caching shared with TypeScript
Nx for TypeScript, Python outside the graph Python lives in the repo but changes independently Contract edges; CI must run Python checks on path filters

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to nx python monorepo, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.