What is nx import and how does it preserve git history?

nx import takes a source repository, or a single subdirectory within it, and places it at a destination directory you choose inside an existing Nx workspace. It does more than copy files. It replays the source's commit history so that each imported commit shows its changes under the new path. A file that lived at src/server.ts in the old repo shows up at something like apps/billing-api/src/server.ts, and git log and git blame on that file still list the original authors, timestamps, and commit messages.

To make this work, the command rewrites history. A git commit hash is derived from the commit's content, which includes the tree of file paths, plus its parent hashes. Moving every file to a new path changes every tree, so every rewritten commit gets a new hash, and so does each descendant. The authorship and dates stay the same, but the identifiers don't. Any external record that points to an old SHA will no longer resolve in the monorepo. That includes commit links in tickets, release notes, and deploy logs.

You import one ref, usually the main branch. Other branches and tags stay behind. So do issues, pull request discussions, review comments, and CI history, because those live on the source host and are not stored in git.

The command handles the history rewrite reliably. Whether the migration succeeds depends on the planning around it: which ref to import, where the code lands, how dependencies merge, and how you cut over from the old repository.

 SOURCE REPO (one ref)                   NX WORKSPACE
+---------------------------+            +-----------------------------+
| ref imported: main        |            | apps/billing-api/           |
|   src/server.ts           |            |   src/server.ts             |
|   commit A  old SHA       |            |   commit A' new SHA         |
|   commit B  old SHA       |            |   commit B' new SHA         |
|   author, date, msg       |            |   same author, date, msg    |
+-------------+-------------+            +--------------^--------------+
              |                                         |
              |         +-----------------------+       |
              +-------->| nx import             |-------+
                        | 1 replay each commit  |
                        | 2 prefix every path   |
                        | 3 new tree => new SHA |
                        | 4 keep author/date/msg|
                        +-----------------------+

+----------------------------------------------------------------------+
| LEFT BEHIND (not in the imported ref or not stored in git)           |
| git:  other branches, tags                                           |
| host: issues, PR discussions, review comments, CI history            |
| old SHAs in tickets, release notes, deploy logs stop resolving       |
+----------------------------------------------------------------------+

nx import replays one ref's commits under a new path in the Nx workspace. Authors, dates and messages stay the same, but every commit gets a new hash, and branches, tags and host-side records stay in the old repository.

Who should migrate polyrepos to an Nx monorepo, and when should you avoid it?

The strongest reason to consolidate is the atomic change. In a polyrepo, updating a shared library's API means one PR to publish the library, a version bump, and a separate PR in every consumer, merged in the right order. In a monorepo the change and every caller update land in one commit, reviewed together, and they either pass CI together or fail together. Shared tooling follows from that: one lint config, one TypeScript or build setup, and one place to upgrade it. Affected-based CI makes the larger repo practical, because Nx uses the project graph to run tasks only for projects touched by a change and their dependents. Engineers don't wait on the full suite for a one-service fix.

Backend and platform teams benefit most when their services share libraries, contracts, or deployment tooling and already change in lockstep.

Signal Consolidate Avoid or delay
Coupling Services share libraries or contracts Services rarely change together
Access Same team or org can read all code Strict per-repo access boundaries are required
Releases Coordinated or continuous Independent cadence with separate version lines
History Mostly source code Large binaries committed in history
Source repos Can be frozen during import Active development can't pause
Ownership Capacity to redesign CODEOWNERS and versioning No one owns that redesign

Count the costs before you start. Imported history accumulates, so repo size and clone times grow with every repo you add. The bigger risk is dependency unification. If two repos pin incompatible major versions of a framework, aligning them can turn into a project of its own and stall the migration.

How do you prepare the workspace and source repository before importing?

Before running anything, get both repositories into a predictable state. The import replays commits from the source into the destination, so uncommitted changes or a stale local branch in either repo make the result harder to reason about.

Checklist

  • Clean working trees in both repos. Commit or stash everything. The import writes files and creates commits in the workspace, and you want a clean diff to review afterward.
  • Pull the latest default branch. Import from a ref that matches the remote, not a local copy that is weeks behind. Otherwise you will need a second sync before cutover.
  • Pick one source branch. Import the branch that represents production, usually main. Merge or close long-lived feature branches first, or accept that they will need to be rebased onto the new layout by hand.
  • Fix the destination convention up front. Decide whether deployable backends go under apps/, shared code under libs/, or whether you group by domain, such as services/billing. Moving a project after import works, but it adds a rename commit to the history and changes the paths in every tool and CODEOWNERS rule that references it.

Optional: shrink history first

If the source repo carries large binaries, such as old build artifacts or database dumps, you can strip them with a history-rewriting tool like git filter-repo before importing. This keeps those objects out of the monorepo, where every future clone would otherwise download them.

The cost is that rewriting changes every commit SHA from the first modified commit onward. Release notes, issue trackers, deploy logs, and any tooling that pins SHAs will point at commits that no longer exist in the new history. Keep the original repository archived and read-only so old references still resolve.

#!/usr/bin/env bash
# Pre-import checks for the workspace and the source repo.
set -euo pipefail

WORKSPACE=~/code/acme-monorepo     # destination Nx workspace
SOURCE=~/code/billing-service      # polyrepo being imported
BRANCH=main                        # the one source branch to import

check_repo() {
  local dir=$1 branch=$2
  cd "$dir"
  # Refuse to continue with uncommitted or untracked changes.
  if [ -n "$(git status --porcelain)" ]; then
    echo "$dir: working tree not clean; commit or stash first" >&2
    exit 1
  fi
  # Make sure the local branch matches the remote, not a stale copy.
  git fetch origin
  git checkout "$branch"
  git pull --ff-only origin "$branch"
  echo "$dir: $branch at $(git rev-parse --short HEAD), in sync with origin"
}

check_repo "$WORKSPACE" main
check_repo "$SOURCE" "$BRANCH"

# Optional: strip large blobs from history before importing.
# This rewrites history, so work on a fresh clone and keep the
# original repo archived read-only so old SHAs still resolve.
# git clone git@github.com:acme/billing-service.git /tmp/billing-clean
# cd /tmp/billing-clean
# git filter-repo --analyze                    # report in .git/filter-repo/analysis
# git filter-repo --strip-blobs-bigger-than 10M

A bash script that verifies clean, up-to-date working trees in both repositories before import, with commented-out optional steps to strip large blobs from the source history using git filter-repo on a fresh clone.

How do you run nx import and verify the history came through?

Start from a clean working tree at the workspace root and create a branch for this import alone, for example import/billing-service. Run npx nx import with no arguments so it prompts you for each input. It asks for the source repository, which can be a remote URL or a local path. It then asks for the source branch, usually the repository's default branch, and the destination directory, such as apps/billing-service. The interactive prompts let you confirm each value before any history is rewritten. Positional arguments are easier to mistype in a way that drops code into the wrong directory.

When the command finishes, check the result before changing anything else:

  • Inspect the merge commit. git log --graph --oneline should show the source repository's commits joining your branch through a single merge. git show --stat on that merge commit shows which files arrived under the destination directory.
  • Check a single file's history. git log --follow apps/billing-service/src/main.ts should reach back to the file's original creation. --follow tracks a file across renames, so it shows commits from before the file moved into the new directory.
  • Check the whole directory. git log -- apps/billing-service should show the full commit sequence, not only the import commit.
  • Check authorship. Run git blame on a file that has seen a lot of changes. You should see the original authors and dates. The commit hashes will differ from the old repository, because the commits were rewritten.

Open a pull request for this branch and run the full build and test suite in CI. Merge it before you import the next repository. Importing one repository per pull request keeps each review small. If something breaks, you know which import caused it, and you can revert that merge without undoing the others.

# Run from the workspace root. Stop if the working tree is not clean.
test -z "$(git status --porcelain)" || { echo "Commit or stash changes first"; exit 1; }

# One branch per imported repository
git switch -c import/billing-service

# No arguments, so nx import prompts for each input:
#   source repository  ->  (or a local path)
#   source branch      -> main
#   destination dir    -> apps/billing-service
npx nx import

# 1. Find the merge commit that brought the history in
git log --graph --oneline -n 20
MERGE=$(git log --merges -n 1 --format=%H)

# List the files the merge added, compared with this branch's state before the import
git diff --stat "$MERGE^1" "$MERGE" | tail -n 5

# 2. A single file's history should reach back to its original creation
git log --follow --format='%h %an %ad %s' --date=short \
  -- apps/billing-service/src/main.ts | tail -n 3

# 3. The whole directory should show the full commit sequence, not just the import
git log --oneline -- apps/billing-service | wc -l

# 4. Blame should show the original authors and dates. Hashes will differ from the old repo.
git blame --date=short apps/billing-service/src/main.ts | head -n 10

# Build and test locally before opening the PR. Run the full suite again in CI.
npx nx run-many -t build test
git push -u origin import/billing-service

This script imports one repository interactively on its own branch, then uses standard git commands to check that the merge commit, per-file history, directory history and blame authorship came through before the branch goes to review.

How do you reconcile dependencies and integrate imported code with Nx?

Once the imported code sits in the workspace, the first conflict is usually dependencies. Two repositories rarely pin the same versions: one service may be on an older major of a test runner or ORM while another has already upgraded. You have two options.

Approach Benefit Cost
Single-version policy One version per package, one lockfile, shared code behaves the same in every project You must upgrade lagging projects, which can surface breaking API changes
Multiple versions tolerated Faster import, no forced upgrades Duplicate installs, confusing type errors when shared libraries cross version boundaries, and drift that keeps growing

A single-version policy is usually worth the upfront cost. Unifying versions exposes the breaking changes you deferred in the polyrepo, such as renamed APIs, changed defaults, or stricter type checks. Fix them per project, inside the same pull request as the import, while the scope is still small.

Next, delete the lockfiles that came along with the imported repository and reinstall from the workspace root. Your package manager then resolves the whole dependency tree once and writes a single root lockfile. CI caching and security scanning only need to read that one file.

Nx plugins infer targets from tool configuration they recognize, such as Jest, Vite, or ESLint config files. Run nx show project <name> to confirm which targets were detected. Where inference does not apply, such as with a custom shell script, define the targets explicitly in a project.json. Finally, open nx graph and check that each imported project depends on the libraries it actually imports. A missing edge means affected-based CI will skip builds it should run.

#!/usr/bin/env bash
# Run from the workspace root after the import has landed.
set -euo pipefail

# 1. Find duplicate versions of a shared package (here: jest) across projects.
#    More than one version in the output breaks a single-version policy.
npm ls jest --all || true

# 2. Remove lockfiles and installs that came with the imported repo.
#    The root lockfile becomes the only source of truth.
find apps libs \( -name package-lock.json -o -name yarn.lock -o -name pnpm-lock.yaml \) \
  -not -path '*/node_modules/*' -print -delete
find apps libs -name node_modules -type d -prune -exec rm -rf {} +

# 3. Reinstall once from the root so npm resolves the whole tree
#    and writes a single package-lock.json.
npm install

# 4. Confirm which targets Nx inferred from tool config (Jest, Vite, ESLint).
#    Anything missing here, such as a custom script, needs an explicit
#    target in that project's project.json.
npx nx show project billing-service

# 5. Export the project graph and check that billing-service has edges
#    to the libraries it actually imports. A missing edge means
#    'nx affected' will skip work it should run.
npx nx graph --file=graph.json
node -e '
  const g = require("./graph.json").graph;
  console.log((g.dependencies["billing-service"] || []).map(d => d.target));
'

This shell sequence checks for duplicate package versions, replaces the imported repo's lockfiles with a single root lockfile, and then verifies inferred targets and project graph edges for an imported project.

How do you handle non-JavaScript backends in an Nx workspace?

Nx's project graph is built from what its plugins can read. For JavaScript and TypeScript it parses package.json files and source imports, so dependency edges come for free. For a Go service, a Rust crate, or a Python package, Nx sees a directory of files. It treats the folder as a project once it has a project.json, but it will not infer build targets or cross-project dependencies unless a plugin for that ecosystem is installed and configured.

The practical approach is to keep the build tooling you already trust and wrap it. Define each target in project.json with the nx:run-commands executor, pointing command at your existing make build, cargo test, go test ./..., or shell script. Set cwd to the project root so relative paths inside those tools still resolve. Nx then schedules, parallelizes, and caches the commands without needing to understand them.

Caching only works when Nx knows what goes in and what comes out:

  • inputs should list the source files, lockfiles, and toolchain config that affect the result, scoped with {projectRoot}.
  • outputs should list the directories the command writes, such as bin/ or target/. Without them, a cache hit replays the logs but restores no artifacts.

Inputs that are too broad, such as a glob over the whole workspace root, cause every commit anywhere to invalidate the cache and mark the project affected. CI then rebuilds everything on every change.

Nx cannot see that a Go service calls a shared protobuf package, so it will not create that edge on its own. Declare the relationship with implicitDependencies. Otherwise a change to the shared package will not trigger a rebuild of the services that use it.

How do you plan the cutover, and what are the alternatives to nx import?

Cutover

Pick a cutover date and treat it as a hard edge. Before that date, ask teams to merge or close open pull requests in the source repository. Every branch left open has to be ported by hand later. For a branch that must survive, export it with git format-patch and apply it inside the monorepo with git am --directory=<project-path> so the paths line up with the new layout. Then make the old repository read-only with branch protection or archiving. Do not mirror commits between the two repositories over a long period. Two-way syncing is where drift begins, and conflicts compound until nobody trusts either copy. Leave a README in the archived repository that points to the new location.

Rewrite CODEOWNERS around project paths, not the old repository boundaries. If the services shipped on separate release cycles, configure Nx release for independent per-project versioning. A single lockstep version would force every team onto the same release schedule.

Switch CI to nx affected against the main branch base, and turn on remote caching before the first busy week. Without them, every pull request rebuilds every imported project.

Alternatives

Approach History preserved Upfront effort Ongoing cost
nx import Yes, with rewritten paths Low Low
git subtree Yes, but squashing or splitting can obscure it Medium Medium if you keep syncing
git filter-repo + manual merge Yes, full control High Low
Copy without history No Lowest Lost blame and bisect
Polyrepo with shared tooling N/A Low High cross-repo coordination

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 import repository, 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.