What is an Nx custom generator and when is it worth building?
An Nx custom generator is code that receives the workspace as a virtual file tree (Tree), reads typed options, and creates or modifies files in that tree. Nx writes the changes to disk only after the generator finishes, so a run can be previewed with --dry-run before anything is written.
Teams build one so that every new service starts from the team's actual conventions. Without one, engineers copy whichever service they remember. That copy brings along stale dependencies, one-off workarounds and the wrong owners. The payoff is largest for platform teams that support several backend teams creating services regularly. In that setting, convention drift becomes a support burden.
Before writing any code, audit your last five to ten services. For each decision, note whether it was the same everywhere or varied for a reason:
| Decision | Fixed convention | Per-service input |
|---|---|---|
| Folder structure | src/, test/, infra/ layout |
Service name, directory |
| Base tsconfig | Extends shared base | — |
| Lint/test targets | Shared config and executors | — |
| Dockerfile | Base image, non-root user | Exposed port |
| Health endpoint | Path and response shape | — |
| Logging | Shared logger setup | Log level default |
| CODEOWNERS | Entry format | Owning team |
The fixed column belongs in templates. The input column becomes the generator's schema.
Illustrative estimate. These figures are assumptions, not measurements:
- Manual setup takes 3 hours, plus 1 hour of review fixes.
- With the generator, setup takes 30 minutes.
- Building the generator costs 24 hours.
- Maintenance costs 2 hours a month.
- The team creates 20 services a year.
At 3.5 hours saved per service, that is 70 hours saved against 48 hours spent. At 10 services a year, the savings drop to 35 hours, which is below the cost.
How do you set up a local plugin to host team generators?
Once the numbers justify a generator, it needs a home. In current Nx workspaces that home is a local plugin: an ordinary library inside the repo that follows the same structure as a published Nx plugin.
Earlier Nx versions offered workspace generators, which were loose scripts in a tools folder that Nx ran in a special mode. They had no project configuration, so you couldn't lint, test, or build them through the project graph, and moving one into a shareable package meant restructuring it. A local plugin removes that gap. It has its own project configuration with targets like any other library, it can be type-checked and unit tested in CI, and it can later be published unchanged if another repository needs it.
Creating the plugin
Install the plugin tooling with nx add @nx/plugin. Then run the @nx/plugin:plugin generator to create a library, for example under tools/service-plugin. Inside that library, run @nx/plugin:generator to add a generator named service. The exact prompts and path arguments differ between Nx versions, so check --help on each command.
What you end up with
tools/service-plugin/project.jsondefines the build, lint, and test targets.package.jsonhas ageneratorsfield that points to the manifest.generators.jsonis the manifest. Each entry maps a generator name to afactory(the implementation file), aschema(the options definition), and adescription.src/generators/service/holdsgenerator.ts,schema.json,schema.d.ts, a spec file, and afiles/directory for templates.
Nx finds generators only through the manifest. If a generator isn't listed in generators.json, it can't be invoked, even when its files exist.
{
"generators": {
"service": {
"factory": "./src/generators/service/generator",
"schema": "./src/generators/service/schema.json",
"description": "Scaffold a new service from the team template"
}
}
}
A minimal tools/service-plugin/generators.json manifest that registers the service generator by mapping its name to the factory implementation, the options schema, and a description; Nx can only invoke generators listed here.
How does an Nx generator work? Schema, options, and the virtual Tree
Every generator has three parts that need to agree with each other.
The schema
schema.json is the generator's public contract. It declares each option's type, default value, and whether it is required. It can also attach an x-prompt so Nx asks for missing values interactively. Nx validates CLI input against this file before your code runs. That means a misspelled flag or a wrong type fails early, with a clear message, instead of producing a half-built service. For team templates, the schema is also where you encode conventions. An enum of allowed service types, or a default directory, is enforced at the input boundary instead of being left to documentation.
The options interface
schema.d.ts mirrors the schema as a TypeScript interface. Nx does not keep the two files in sync for you. If you add a property to one, add it to the other, or the compiler will check your generator against a shape that no longer matches what users can pass.
The generator function and the Tree
The generator function receives a Tree and the parsed options. The Tree is a virtual file system: write, read, exists, and delete operate on an in-memory change set, not on disk. Nx writes those changes to disk only after the function finishes without throwing. If anything fails, nothing is written. --dry-run uses the same mechanism. It runs the generator in full, prints the list of files that would be created, updated, or deleted, and then discards the changes. You can iterate on templates repeatedly without cleaning up a broken workspace.
That guarantee only holds if the generator is a pure transformation of the Tree. Avoid network calls, reading environment variables, checking the current date, and inspecting files outside the Tree. Any of these makes a dry run differ from the real run, or makes output differ between two engineers' machines. Side effects such as installing dependencies belong in the callback the generator returns. Nx runs that callback after the files have been written.
// tools/generators/service/generator.ts
import { Tree, formatFiles, generateFiles, joinPathFragments, names } from '@nx/devkit';
// Mirrors schema.json by hand. Nx does not sync these for you.
export interface ServiceGeneratorSchema {
name: string;
type: 'http' | 'worker'; // enum enforced in schema.json
directory?: string; // schema.json default: "services"
}
export default async function serviceGenerator(tree: Tree, options: ServiceGeneratorSchema) {
const { fileName, className } = names(options.name);
const root = joinPathFragments(options.directory ?? 'services', fileName);
// Read only from the Tree, not from disk or the environment,
// so a dry run and a real run see the same inputs.
if (tree.exists(root)) {
// Throwing discards every staged change. Nothing reaches disk.
throw new Error(`${root} already exists`);
}
// Stages the rendered template files in the in-memory change set.
generateFiles(tree, joinPathFragments(__dirname, 'files', options.type), root, {
fileName,
className,
tmpl: '', // strips the __tmpl__ suffix from template file names
});
// Formatting also runs against the Tree, so --dry-run output matches the real result.
await formatFiles(tree);
}
// Preview without writing anything:
// nx g ./tools/generators/service:service billing --type=http --dry-run
A generator that reads its typed options, stages template files on the virtual Tree, and throws on conflict so no partial output is written. The same code runs under --dry-run with identical results.
Implementing the service generator with @nx/devkit
Start by normalizing input. Pass the raw name option through names() once and reuse the result: fileName for directories, className for the service class, constantName for environment variable prefixes. If each template derives its own casing, billing-api turns into three spellings across three files. Build every path with joinPathFragments so that a trailing slash or a Windows separator in user input does not produce apps//billing-api.
generateFiles copies a files/ directory into the target root and renders each file through EJS with the substitutions you pass. That directory holds the Dockerfile, the health endpoint, and the logger setup. Register the project with addProjectConfiguration and declare lint, test, and build targets explicitly. That way nx affected and CI pick the service up on day one instead of after someone notices it is missing.
For the path alias, updateJson on tsconfig.base.json is safer than string edits. Check whether the key already exists before you write it. CODEOWNERS is plain text, so read it with tree.read(path, 'utf-8'), test whether the exact line is already present, and append only if it is not. Rerunning the generator should leave the file unchanged. End with formatFiles so generated output matches the repo's Prettier config.
Template pitfalls
EJS claims <% and %>. If a template legitimately contains those characters, as some shell or templating snippets do, write <%% to emit a literal opening tag.
Filenames confuse newcomers. A segment like __fileName__ is replaced by the substitution with that key. The common __tmpl__ suffix only works if you pass tmpl: '', which strips it. That suffix exists so editors and linters do not treat main.ts__tmpl__ as real source. Explain this in a README inside files/.
import { Tree, names, joinPathFragments, generateFiles, addProjectConfiguration, updateJson, formatFiles } from '@nx/devkit';
export default async function serviceGenerator(tree: Tree, opts: { name: string }) {
const n = names(opts.name); // normalize once: fileName, className, constantName
const root = joinPathFragments('apps', n.fileName); // never apps//billing-api
// Render files/ through EJS; tmpl: '' strips the __tmpl__ filename suffix
generateFiles(tree, joinPathFragments(__dirname, 'files'), root, { ...n, tmpl: '' });
// Explicit targets so nx affected and CI see the service immediately
addProjectConfiguration(tree, n.fileName, {
root,
sourceRoot: joinPathFragments(root, 'src'),
projectType: 'application',
targets: {
lint: { executor: '@nx/eslint:lint' },
test: { executor: '@nx/jest:jest', options: { jestConfig: joinPathFragments(root, 'jest.config.ts') } },
build: { executor: '@nx/js:tsc', options: { main: joinPathFragments(root, 'src/main.ts'), tsConfig: joinPathFragments(root, 'tsconfig.app.json'), outputPath: joinPathFragments('dist', root) } },
},
});
// Add the path alias only if it is not already mapped
updateJson(tree, 'tsconfig.base.json', (json) => {
json.compilerOptions ??= {};
json.compilerOptions.paths ??= {};
json.compilerOptions.paths[`@acme/${n.fileName}`] ??= [joinPathFragments(root, 'src/index.ts')];
return json;
});
// Append the CODEOWNERS line once; reruns leave the file unchanged
const owners = '.github/CODEOWNERS';
const line = `/${root}/ @acme/platform-team`;
const current = tree.exists(owners) ? tree.read(owners, 'utf-8') ?? '' : '';
if (!current.split('\n').some((l) => l.trim() === line)) {
const sep = current === '' || current.endsWith('\n') ? '' : '\n';
tree.write(owners, `${current}${sep}${line}\n`);
}
await formatFiles(tree); // match the repo's Prettier config
}
A minimal service generator that normalizes the name with names(), renders the files/ templates, registers lint/test/build targets, adds a tsconfig path alias without overwriting an existing one, and appends the CODEOWNERS entry only once.
Should you compose official generators or write everything yourself?
Composition means your generator imports the official one and awaits it against the same Tree before doing anything else. For a Node service, call applicationGenerator from @nx/node with the options your team has standardized: framework, linter, test runner, directory layout. Then read the result with readProjectConfiguration. Add your own files with generateFiles, merge team targets such as a container build or a contract-test step into the project configuration, and write it back with updateProjectConfiguration. The official generator returns a task callback, usually for dependency installation. Combine it with yours using runTasksInSerial so that callback still runs.
The trade-off is ownership of the baseline:
| Concern | Compose official generator | Write from scratch |
|---|---|---|
| Code you maintain | Only the team-specific layer | Every file and target |
| Upstream fixes and new defaults | Arrive with Nx upgrades | Must be ported by hand |
| Stability of output | Can change on any upgrade | Changes only when you edit it |
| Coupling | To its option names and file layout | None beyond @nx/devkit |
Composition is usually the better default. The coupling is real, though. If an upgrade renames an option, moves main.ts, or reshapes a target, your overlay can patch the wrong path or silently produce a different service.
To catch that early, write tests that pin the assumptions your layer depends on. Assert that the files you modify exist at the expected paths, and that the targets you extend have the executor you expect. Snapshot the generated project.json. After an Nx upgrade, a failing snapshot shows you exactly what changed upstream, so you can review it before generating any new services.
import {
Tree, formatFiles, generateFiles, joinPathFragments,
readProjectConfiguration, updateProjectConfiguration, runTasksInSerial,
} from '@nx/devkit';
import { applicationGenerator } from '@nx/node';
interface ServiceSchema { name: string; directory: string; }
export default async function serviceGenerator(tree: Tree, options: ServiceSchema) {
// 1. Let the official generator create the baseline using team-standard options.
// These option names are a coupling point. Re-check them after every Nx upgrade.
const installTask = await applicationGenerator(tree, {
name: options.name,
directory: options.directory, // e.g. 'apps/orders-service'
framework: 'express',
linter: 'eslint',
unitTestRunner: 'jest',
});
// 2. Read the generated output instead of guessing its paths.
const project = readProjectConfiguration(tree, options.name);
// 3. Add team files (Dockerfile, contract-test config) from ./files.
generateFiles(tree, joinPathFragments(__dirname, 'files'), project.root, { ...options, tmpl: '' });
// 4. Merge the team targets and keep the official build/serve/test targets.
project.targets = {
...project.targets,
'container-build': {
executor: 'nx:run-commands',
options: { command: `docker build -f ${project.root}/Dockerfile -t ${options.name}:local .` },
},
'contract-test': {
executor: 'nx:run-commands',
options: { command: `jest --config ${project.root}/jest.contract.config.ts` },
},
};
updateProjectConfiguration(tree, options.name, project);
await formatFiles(tree);
// 5. Return the official generator's callback so dependency installation still runs.
return runTasksInSerial(installTask);
}
A custom generator calls the official @nx/node application generator, then adds team files and container-build and contract-test targets to the project configuration it produces, and returns the official install task so it still runs.
How do you test an Nx generator?
Generator tests run against an in-memory workspace, so they take milliseconds and never touch disk. createTreeWithEmptyWorkspace from @nx/devkit/testing gives each test a fresh Tree. Call your generator function directly with that tree and a set of options, then inspect the result.
What to assert
- Files exist. Check
tree.exists()for every path the template should produce, including dotfiles. Dotfiles are easy to lose when someone renames a template directory. - Project registration. Use
readProjectConfiguration(tree, name)and check the project root, tags, and the targets your team depends on. A missinglintortesttarget fails silently until a pipeline skips the new service. - Path mappings. Read
tsconfig.base.jsonwithreadJsonand confirm the import alias points at the new project's entry file. A wrong path breaks imports in other projects, often far from the generator. - Idempotency. Run the generator twice with the same options. The second run should either fail with a clear error or produce identical output. Assert that the CODEOWNERS file contains the new entry exactly once. Appending without checking is the most common bug in this kind of generator.
Smoke-test in CI
Unit tests prove the generator writes what you intended. They don't prove that the output compiles. Add a CI job that:
- Generates a throwaway service with a fixed name.
- Runs that project's
build,lint, andtesttargets. - Discards the workspace.
This catches a template that references a removed API or a dependency version that no longer resolves. Without the job, the problem surfaces months later, when someone needs a new service before a deadline and finds the scaffold broken.
When should you avoid a custom generator, and what are the alternatives?
A generator only shapes day-one output. Once a service exists, nothing ties it back to the template. A team edits its lint config, another pins a different logger, and within a year "generated from the standard template" says little about what the code looks like now. Conventions stay enforced only if migrations or lint rules carry them forward. Options cost more than they appear to. Every boolean doubles the combinations you have to test, and a generator with a dozen flags is usually two or three generators that should be split, or a template that should make the decision itself. A local plugin is also internal tooling, so it needs a named owner, or it decays like any unowned code.
| Approach | Maintenance cost | Consistency over time |
|---|---|---|
| Nx custom generator | Medium: code, tests, and an owner | Strong at creation, weak afterward without migrations |
| Documented reference service | Low | Weak: relies on people reading it |
| Copy-paste from an existing service | None up front | Poor: copies whatever drift the source has |
| External scaffolding tool | Medium, plus less workspace awareness | Strong at creation only |
| Lint rules | Low to medium | Strong and ongoing, but cannot create files |
Rolling it out
- Publish one invocation, such as
nx g @acme/tooling:service, using your local plugin's name. - Document every option and its default.
- Review generator changes as carefully as production code.
- When a convention changes, ship a migration alongside the template update so services that already exist move with it.
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 custom generator, 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
.envby 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.