What is nx import and how does it work?

nx import moves an existing repository into an Nx workspace without discarding its history. You point it at a source repository and a ref, such as a branch. You can also choose a directory within that source. It places the files in a subdirectory of the destination workspace, so payments-service might become apps/payments. Afterward, git log and git blame on files under the new path still show the original commits, authors, and messages.

The flow

  1. Fetch the source. Nx retrieves the chosen ref from the source repository into a temporary working area. Your workspace is not touched at this stage.
  2. Rewrite paths. It rewrites the source history so every commit appears to have always placed its files under the destination directory. Each commit's tree changes, so every commit gets a new SHA. Anything that points to the old SHAs will not resolve in the monorepo. That includes release tags, links in tickets, and deployment records that reference commit hashes. The original repository remains the reference for those.
  3. Merge. Nx merges the rewritten history into the current branch of the destination workspace. Because the history was rewritten into a separate directory first, it can join the existing workspace history without file-level collisions.
  4. Detect tooling. Nx inspects the imported code for tools it has plugins for, such as build tools, test runners, and linters, and offers to add them. Those plugins let Nx infer tasks for the new project.

This approach suits platform and backend teams consolidating a polyrepo into a monorepo one service at a time. Engineers keep the context in the service's history, and the workspace gains a project Nx can build and test.

+--------------------------------+
| Source repo: payments-service  |
| ref: main (optional subdir)    |
+---------------+----------------+
                | 1. fetch ref
                v
+--------------------------------+
| Temporary working area         |
| (destination not touched yet)  |
+---------------+----------------+
                | 2. rewrite paths
                v
+--------------------------------+     +---------------------------+
| Rewritten history              |     | Old SHAs (tags, tickets,  |
|  src/* -> apps/payments/src/*  |     | deploy records) resolve   |
|  every commit gets a NEW SHA   |     | only in the original repo |
+---------------+----------------+     +---------------------------+
                |
                | 3. merge into current branch
                v
+--------------------------------+
| Destination Nx workspace       |
|  apps/payments/ + full history |
|  (git log / git blame intact)  |
+---------------+----------------+
                | 4. detect tooling
                v
+--------------------------------+
| Offer plugins: build, test,    |
| lint -> Nx infers tasks        |
+--------------------------------+

nx import fetches a ref from the source repo, rewrites its history under the destination path so every commit gets a new SHA, merges that history into the current branch, and then offers plugins so Nx can infer tasks.

What are the alternatives to nx import for merging repositories into a monorepo?

Not every merge needs Nx tooling. The approach you pick decides how much history survives and how much setup work remains afterward.

Approach Git history Tooling detection Best fit
Copy files Lost None Throwaway prototypes, code nobody will need to trace
git subtree merge Kept, but old commits show files at their original root paths None Quick merges where path-aware history matters less
Manual rewrite + merge Kept, under the new directory None Non-JavaScript repos, custom layouts, one-off archives
nx import Kept, under the new directory Detects and suggests plugins Services joining an active Nx workspace

Copying files is the fastest option and the most destructive. git blame and git log start from the day of the copy, so the reasons behind past changes are gone.

A subtree merge keeps commits. Because historical commits still reference root-level paths, path-filtered git log and blame across the move can be awkward.

Rewriting history first means moving every path into a subdirectory with a tool such as git filter-repo, then merging with --allow-unrelated-histories. This gives clean, path-correct history. You do every step by hand, though, and it is easy to get the target path or branch wrong.

nx import automates that rewrite-and-merge sequence, then inspects the imported code and offers to add the matching Nx plugins. For a JavaScript or TypeScript service, that removes most of the manual follow-up, which is why it is the safest default. A manual rewrite is still reasonable for a Go or Python service the workspace won't build through Nx plugins, or for archiving a retired repo where you only need the history.

When should you avoid moving a service from polyrepo to monorepo?

…want only a frozen snapshot. Before choosing any mechanism, decide whether the service should move at all.

Situation Why a monorepo hurts
Strict access isolation (compliance scope, contractors) Git hosts grant read access per repository. Anyone who can clone the workspace can read every directory.
Conflicting toolchain A different Node major version, package manager, or build system forces a second lockfile or per-project workarounds.
Release cadence that can't absorb shared dependencies A single-version policy makes one team's framework upgrade block everyone else's.
No affected-based CI Every commit builds and tests every service.

Some costs remain even when importing is the right call:

  • Rewritten SHAs. The imported commits get new hashes. Old SHAs in issues, changelogs, and deploy logs stop resolving unless the source repo stays archived and read-only.
  • Signed commits. The rewritten commits do not carry their original signatures, so the workspace cannot verify them.
  • Coarser ownership. Path-based CODEOWNERS rules replace repository-level permissions.
  • Repo size and CI load. Clones get heavier, and the CI queue is shared.

Illustrative estimate (assumed inputs, not measured):

  • A team makes 6 cross-repo changes per month. Each costs 3 hours of version bumps, publishing, and consumer PRs. Importing saves about 18 h/month.
  • With affected-based CI, the import adds 8 minutes to 400 monthly runs. That is about 53 compute-hours. If engineers wait on a quarter of that time, the cost is about 13 h/month, a small net gain.
  • Without affected-based CI, each run might add 25 minutes instead. Engineer waiting rises to about 42 h/month, and the import becomes a net loss.

How do you prepare the source repo and destination workspace before running nx import?

Source repository checklist

  • Clean working tree. nx import reads committed history, so uncommitted changes are left behind. Run git status --porcelain; empty output means nothing is pending.
  • Choose the branch to import. List branches with git branch -a and merge any unfinished work first. Commits on other branches will not come across.
  • Settle the default branch. git remote show origin shows the HEAD branch. If a master to main rename is planned, do it now, so the import does not point at a branch that is about to disappear.
  • Remove secrets and large binaries from history. Every commit becomes part of the monorepo, so a leaked credential or a 200 MB fixture would be copied into it. To find the largest blobs, pipe git rev-list --objects --all into git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' and sort by size. git count-objects -vH reports the total size of the repository.

Rewriting history with a tool such as git filter-repo is destructive. It changes commit hashes and breaks existing clones. Work on a fresh clone, keep the original remote untouched until the import is verified, and rotate any secret you find, because removing it from history does not revoke it.

Destination workspace checklist

  • Dedicated branch. Create a new branch from an up-to-date main branch, for example import/billing-service. The import then lands as a single reviewable merge.
  • Directory convention. Decide on apps/, services/ or packages/ before importing, so later imports follow the same layout.
  • Collision check. Run nx show projects and confirm the target path does not exist. Duplicate project names cause errors in Nx's project graph, and an existing directory can be overwritten.
#!/usr/bin/env bash
set -euo pipefail

# --- Source repo checks (run from a fresh clone of the service) ---
cd ~/work/billing-service

# Fail if anything is uncommitted; nx import only brings committed history.
if [ -n "$(git status --porcelain)" ]; then
  echo "Working tree not clean" >&2; exit 1
fi

# Show local and remote branches, and which branch the remote treats as default.
git branch -a
git remote show origin | grep 'HEAD branch'

# List the 20 largest blobs anywhere in history (size in bytes, then path).
git rev-list --objects --all \
  | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' \
  | awk '$1 == "blob" { print $3, $4 }' \
  | sort -n -r \
  | head -n 20

# Total repository size, human-readable.
git count-objects -vH

# --- Destination workspace checks ---
cd ~/work/platform-monorepo

# Branch off an up-to-date main so the import is one reviewable change.
git fetch origin
git switch -c import/billing-service origin/main

# Stop if the project name or target directory is already taken.
if npx nx show projects | grep -qx 'billing-service'; then
  echo "Project name billing-service already exists" >&2; exit 1
fi
if [ -e services/billing-service ]; then
  echo "Target path services/billing-service already exists" >&2; exit 1
fi
echo "Ready to import into services/billing-service"

A pre-flight script that checks the source repo for uncommitted changes, branches, the remote default branch and large blobs in history, then creates a dedicated import branch in the destination workspace and checks for project name and path collisions.

How do you run nx import and verify that git history was preserved?

Start from the root of the destination workspace with a clean working tree, then run nx import. The command is interactive, and each prompt decides something that is tedious to undo later:

  • Source repository. Enter a remote URL or a local path. A local clone is faster and lets you import a branch you have not pushed.
  • Source ref. Choose the branch or tag explicitly. The default may not be the branch you prepared, and any commits that exist only on other branches will not come across.
  • Source directory. Use this to import a subfolder instead of the whole repo.
  • Destination directory. Use the path you validated in the collision check, for example services/billing.

Read the summary of changes before you confirm. Check the target path, any Nx plugins it offers to install, and any changes to root files such as package.json or the lockfile. If anything is wrong, abort and rerun. That is cheaper than unpicking a merge commit.

To verify the result, choose a file that has a long history and run git log --follow -- services/billing/src/invoice.ts. You should see commits that predate the import. git blame on the same file should attribute lines to their original authors and dates, not to the import commit.

The import first relocates the source files into the destination directory, then merges that history into your workspace. Every earlier commit therefore records the file at its old root-level path. A plain path-limited git log stops at the move, and --follow traces it back through the rename. Many web UIs and IDE history panels only show the current path by default, so they can make the import look like history was lost. Look for a rename-aware or "follow" option in those tools before you assume a problem.

# Run from the root of the destination Nx workspace.
# 1. Confirm the working tree is clean before importing.
git status --porcelain   # should print nothing

# 2. Start the interactive import. Answer each prompt deliberately:
#    source repo:      ../billing-service (local clone) or its remote URL
#    source ref:       the branch you prepared, e.g. main or prep-for-import
#    source directory: leave empty to import the whole repo
#    destination:      services/billing
# Read the summary of changes before confirming. Abort if anything is wrong.
npx nx import

# 3. Review what the import added on top of your previous HEAD.
git log --oneline -5

# 4. Without --follow, history stops at the point the file moved.
git log --oneline -- services/billing/src/invoice.ts

# 5. With --follow, git traces the file back through the rename
#    to commits made when it lived at the old root-level path.
git log --follow --oneline -- services/billing/src/invoice.ts

# 6. Show the rename itself and the old path it came from.
git log --follow --name-status --format='%h %ad %an' --date=short \
  -- services/billing/src/invoice.ts | head -20

# 7. Blame should credit original authors and dates, not the import commit.
git blame -- services/billing/src/invoice.ts | head -10

A shell session that runs nx import from a clean tree, then checks that a file's history and blame survive by comparing a plain path-limited git log with git log --follow.

How do you turn the imported code into a working Nx project?

Reconcile tooling before running anything

An Nx workspace expects one package manager and one lockfile at the root. Delete the lockfile the import brought in, move the service's dependencies into the workspace's dependency setup, and reinstall from the root. If the service used a different package manager, do not run it alongside the workspace's package manager. Two resolvers writing to the same tree produce installs that differ from machine to machine.

Then compare dependency versions. A service pinned to an older framework or test runner can break when it resolves the workspace's version. Either align it now or keep a project-local package.json until you can.

The same choice applies to TypeScript, lint and formatting configs. Moving the service onto the workspace base config gives you consistency, but it also adds new type errors and lint failures to the same change. Keeping the service's own configs at first separates "the code moved" from "the code changed," which makes regressions easier to trace. Converge in follow-up commits.

Confirm Nx sees the project

Run nx show projects and check that the service appears. nx show project <name> lists its targets, both inferred from config files and explicitly defined. Run nx build <name> and nx test <name> and compare the results against the old repo's CI. Open nx graph to confirm the service depends only on what you expect.

Services driven by custom shell scripts or non-JavaScript toolchains will not get useful inferred targets. Define those targets by hand in the project's project.json, including inputs and outputs so caching stays correct.

# Run from the workspace root after `nx import` has placed the service in services/billing.

# 1. One package manager, one lockfile: drop the lockfile the import brought in.
rm -f services/billing/package-lock.json services/billing/yarn.lock services/billing/pnpm-lock.yaml

# Reinstall from the root with the workspace's package manager (npm here)
# so a single resolver writes node_modules and the root lockfile.
npm install

# 2. Confirm Nx detects the project. The name comes from project.json or package.json.
npx nx show projects | grep billing

# Inspect its targets, both inferred from config files and explicitly defined.
npx nx show project billing

# 3. Run the same checks the old repo's CI ran, but through Nx.
# Compare results and test counts against the last green CI run of the old repo.
npx nx build billing
npx nx test billing

# 4. Check boundaries. The service should depend only on what you expect.
npx nx graph --focus=billing

Shell steps for consolidating the lockfile, confirming that Nx detects the imported billing service and lists its targets, running build and test through Nx, and viewing the project graph focused on that service.

How can you migrate CI and import several services without losing work?

Port pipelines to affected-based runs

Rewrite each service's pipeline as one workspace pipeline. Remove path filters that pointed at the old repo root. Have the job run nx affected -t lint test build against the base branch instead, because Nx's project graph knows which projects a change touches. Path globs only know which folders changed. Turn on caching, and use a shared remote cache if you have one. Without caching, every merged service makes the pipeline slower.

Replace per-repo permissions

Per-repo permissions disappear once the code shares one repository. Add a CODEOWNERS entry for each imported directory and give it the team that owned the old repo. Then require code-owner review in branch protection on the workspace.

Move what nx import does not carry

nx import brings over commits and nothing else. Handle these yourself:

  • Release tags: recreate them with a per-project prefix so tags from different services don't collide.
  • Open issues and PRs: move them by hand or with your Git host's tooling.
  • Branch protection rules: set them up again on the workspace.
  • The old repo: archive it, with a README that points to the new location.

Roll out incrementally

Import one repo per PR. Import shared libraries before the services that consume them, so each consumer can switch to a workspace reference when it lands. Set a short commit freeze on the source repo for the window between import and cutover. If you can't freeze, re-import or cherry-pick any commits made after the import before you archive the repo.

Where the time comes back

After cutover, a change across several services is a single atomic PR. Dependency upgrades also happen once, along one path, instead of separately in N repos that drift apart.

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, 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.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

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.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • 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.