What is an Nx custom generator, and what belongs in a scaffold-service generator?

An Nx custom generator is code that lives in your workspace and uses the Nx Devkit to create or change files and project configuration. You run it like any built-in generator. Instead of copying a starter folder, it writes a new project from templates and registers the project with Nx in the same step.

For a backend team, the value is where the standards live. A template repo or a wiki page records the standards at the moment someone wrote it, and nothing tells you when it stops matching what production expects. A generator is code. You can review it, test it, and change it in the same pull request that changes the standard. When the logging format changes, you update the generator once, and every service scaffolded after that gets the new format.

A scaffold-service generator should produce the parts every service needs and nobody should have to rethink:

  • A health endpoint with the path and response shape your orchestrator and load balancers expect
  • Structured logging configured with the shared fields and format
  • Config loading that validates required values at startup and fails fast
  • A Dockerfile or build target that matches your deployment pipeline
  • A working test setup with one passing test
  • Ownership and type tags, so module boundary rules and code ownership apply from the first commit

Business logic stays out, along with anything that legitimately differs between teams. If a choice needs an option to work for everyone, it probably does not belong in the generator.

This fits platform and backend teams in an Nx monorepo who create services often enough that small inconsistencies become a recurring cost in reviews, on-call work, and CI fixes.

Why is an Nx custom generator used?

Teams use a custom generator to make the correct way to start a service the default way. Without one, every new service depends on whoever creates it remembering the current conventions. Over time, that produces predictable problems:

  • Inconsistent operational surface. Health checks answer on different paths, logs use different field names, and config errors show up at request time instead of at startup. On-call engineers then have to learn each service's quirks before they can debug it.
  • Repeated review comments. Reviewers flag the same missing tag, misnamed CI target, or unvalidated environment variable on every new service.
  • CI and deployment mismatches. A service whose targets are named differently from what the pipeline runs either gets skipped or fails until someone renames them.
  • Module boundary gaps. A project without the right type: and scope: tags is not covered by boundary lint rules, so it can import things it shouldn't until someone notices.

A generator addresses all of these at the point of creation. Because it is code inside the workspace, it can also do things a copied folder cannot: register the project with Nx, add tags to project configuration, update shared files such as tsconfig.base.json, and run formatting so the output passes the same checks as the rest of the repo.

Who should use an Nx custom generator?

There are two audiences, with different responsibilities.

Platform or developer-experience teams build and own the generator. They decide which standards are mandatory, keep the templates current, write the generator's tests, and fix it when an Nx upgrade changes Devkit APIs or the output of a wrapped framework generator. If nobody is willing to own it, do not build it (see the cost section below).

Backend engineers run it. Every engineer who creates a new API or worker in the monorepo should start from the generator instead of copying an existing service. This includes new hires, who otherwise have to learn the conventions from scattered docs or by imitation.

A generator is a good fit when most of these hold:

  • Services live in one Nx monorepo, so the project graph, tags, and module boundary rules apply to them.
  • New services are created regularly, not once or twice a year.
  • The team has a standard that is stable enough to encode: logging, health checks, config, Docker build, CI targets.
  • Several teams create services, so consistency cannot rely on one person's memory.

It is a poor fit for one-off prototypes, for organizations where each service lives in its own repository, or for teams whose conventions are still changing week to week.

How does it work?

At a high level, a generator is a function that Nx calls with two arguments: a Tree representing the workspace and the options the user passed on the command line. The sequence is:

  1. You invoke it with nx g <plugin>:<generator> <name> plus any flags.
  2. Nx validates the options against the generator's schema.json, applying defaults and prompting for missing values when running interactively.
  3. The generator function runs against the Tree, an in-memory view of the workspace. It renders templates from a files/ directory, creates or updates project configuration, and edits shared JSON files. None of this touches disk yet.
  4. Nx commits the changes to disk only if the function finishes without throwing. With --dry-run, it lists the changes and writes nothing.
  5. An optional callback runs after the files are written, for side effects such as installing packages.

Because every change is staged in memory, a failure partway through leaves the workspace untouched, and you can unit test the generator by running it against an empty in-memory workspace and inspecting the result. The sections below cover where the generator lives, how the schema, Tree, and templates fit together, how to implement it, and how to test it.

Where should generators live: nx workspace generator or a local plugin?

Older Nx workspaces kept generators in a tools/generators folder and ran them through the nx workspace-generator command. That approach treated generators as a special case: they lived outside the normal project graph, had their own compilation path, and could not easily share code or tests with the rest of the workspace.

Current guidance is to put generators in a local plugin. This is an ordinary library inside the monorepo, created with the generators from @nx/plugin. The plugin is a regular Nx project with its own build, lint, and test targets. Your scaffold-service generator gets the same CI treatment as any other code. It can also import shared helpers, such as your logging or config conventions, instead of duplicating them.

Layout and registration

A typical local plugin sits under a folder such as tools/ and contains the following:

  • A generators.json manifest at the plugin root. It maps each generator name to its implementation and its schema.
  • A package.json whose generators field points to that manifest. This field is how Nx discovers what the plugin offers.
  • One directory per generator under src/generators/. Each holds the implementation, schema.json, a typed schema interface, a files/ template folder, and a spec file.

Nx resolves the plugin through the workspace's TypeScript path mapping, so you invoke it by its import name. You do not need to publish it to a registry.

The exact commands, flags, and folder defaults changed between major Nx versions. If you are migrating from workspace generators, check the documentation and available migrations for your installed version before running anything.

tools/workspace-plugin/
├── generators.json          # manifest: generator name -> implementation + schema
├── package.json             # "generators" field points Nx at the manifest
├── project.json             # normal Nx project: build, lint, test targets
└── src/generators/scaffold-service/
    ├── scaffold-service.ts      # generator implementation
    ├── scaffold-service.spec.ts # tested like any other code
    ├── schema.json              # options exposed to users
    ├── schema.d.ts              # typed interface for those options
    └── files/                   # templates copied into new services

{
  "name": "@acme/workspace-plugin",
  "generators": "./generators.json"
}

{
  "generators": {
    "scaffold-service": {
      "factory": "./src/generators/scaffold-service/scaffold-service",
      "schema": "./src/generators/scaffold-service/schema.json",
      "description": "Scaffold a backend API service with team standards"
    }
  }
}

nx g @acme/workspace-plugin:scaffold-service orders-api

The example shows a local plugin's directory layout and how package.json, generators.json, and the TypeScript path mapping let Nx discover and run the scaffold-service generator.

How does an Nx generator work? Schema, Tree and templates

A generator has four parts. schema.json declares the options: each property gets a type, an optional default, an enum where only certain values make sense (for example a transport option limited to http or grpc), and an optional x-prompt that asks the user when the value is missing. A TypeScript interface, conventionally schema.d.ts, mirrors that schema so the generator body is type-checked. You keep the two in sync by hand, so treat a mismatch as a bug. The generator function receives a Tree and the validated options. A files/ directory holds templates that generateFiles renders with substitutions such as __name__ in paths and EJS tags in file contents.

The flow looks like this:

CLI options -> schema validation -> generator(Tree) -> in-memory changes -> formatFiles -> commit to disk -> post-write callback

The Tree is a virtual file system. Every read, write and delete is staged in memory, and nothing reaches disk until the generator finishes without throwing. This has two practical effects. First, --dry-run can list every file the generator would create or modify without writing anything. Second, a generator that fails halfway leaves no half-built service behind.

Some work cannot run against the Tree, such as installing dependencies. The generator handles this by returning a callback, for example installPackagesTask, which Nx runs after the files are written. Return a callback only for side effects that need the files on disk first.

An x-prompt waits for input, so it can hang in CI. Give every prompted option a sensible default, and document the full set of flags plus --no-interactive for pipelines.

// generator.ts - scaffolds a backend service into the virtual Tree
import {
  Tree,
  formatFiles,
  generateFiles,
  installPackagesTask,
  joinPathFragments,
  names,
} from '@nx/devkit';

// Mirrors schema.json by hand (normally kept in schema.d.ts). A mismatch is a bug.
export interface ServiceGeneratorSchema {
  name: string;
  transport: 'http' | 'grpc'; // enum in schema.json, default 'http'
  port?: number;
}

export default async function serviceGenerator(tree: Tree, options: ServiceGeneratorSchema) {
  const { fileName, className } = names(options.name);
  const projectRoot = joinPathFragments('apps', fileName);

  // Render files/ into the in-memory Tree. __name__ in paths and <%= %> tags
  // in contents are substituted. Nothing touches disk yet.
  generateFiles(tree, joinPathFragments(__dirname, 'files'), projectRoot, {
    ...options,
    name: fileName,
    className,
    port: options.port ?? 3000,
    tmpl: '', // strips the __tmpl__ suffix from template file names
  });

  // Format staged files so every generated service matches repo style.
  await formatFiles(tree);

  // Nx runs this only after the Tree has been committed to disk,
  // and skips writing entirely on --dry-run.
  return () => {
    installPackagesTask(tree);
  };
}

A minimal generator that stages templated files in the virtual Tree, formats them, and returns a post-write callback that installs packages only after Nx writes the files to disk.

How do you implement a scaffold-service generator with the Nx Devkit?

Start by normalizing input. Pass the raw name option through names() and use its fileName, className and propertyName everywhere, so a service requested as OrderBilling doesn't end up as order-billing on disk and orderBilling in a route. Build every path with joinPathFragments, which normalizes separators and stray slashes, rather than concatenating strings.

Next, call generateFiles with a files/ directory of EJS templates. Name files like __name__.controller.ts.template, and __name__ becomes the substituted value in the output path. Pass names() output as template variables so the casing rules stay in one place.

Register the project with addProjectConfiguration. Give it build, serve, test, lint and docker targets whose names match what CI already runs. Add type:api and scope:<domain> tags so module boundary rules apply from the first commit. Use updateJson for shared files such as the tsconfig path aliases. Call formatFiles last so the output passes the formatting check without manual fixes.

Prefer composition over reimplementation. Await the official Node or Nest application generator first. That generator already registers the project, so use updateProjectConfiguration to add your team's targets and tags, then layer your own templates on top. When the upstream generator improves, you get the change without editing your code.

Keep the mandatory surface small: a health endpoint, logging setup, a Dockerfile. Put database clients, queues and auth behind boolean schema options that default to off. When <% if %> blocks start nesting inside templates, move each option into its own file set selected in code, or into a separate generator.

import {
  Tree, names, joinPathFragments, generateFiles, formatFiles,
  readProjectConfiguration, updateProjectConfiguration, updateJson,
} from '@nx/devkit';
import { applicationGenerator } from '@nx/node';

interface Schema { name: string; domain: string; database?: boolean }

export default async function scaffoldService(tree: Tree, options: Schema) {
  const n = names(options.name); // 'OrderBilling' -> fileName 'order-billing', className 'OrderBilling'
  const root = joinPathFragments('apps', options.domain, n.fileName);

  // Compose: the official generator creates the app and registers the project
  await applicationGenerator(tree, { name: n.fileName, directory: root });

  // Mandatory team files (health endpoint, logger, Dockerfile); __name__ in paths -> n.fileName
  generateFiles(tree, joinPathFragments(__dirname, 'files'), root, { ...n, domain: options.domain });
  // Opt-in pieces live in their own file set instead of <% if %> blocks
  if (options.database) {
    generateFiles(tree, joinPathFragments(__dirname, 'files-database'), root, { ...n });
  }

  // Add tags for module boundary rules and a docker target named like the CI step
  const project = readProjectConfiguration(tree, n.fileName);
  project.tags = [...(project.tags ?? []), 'type:api', `scope:${options.domain}`];
  project.targets = {
    ...project.targets,
    docker: { executor: 'nx:run-commands', options: { command: `docker build -f ${root}/Dockerfile -t ${n.fileName} .` } },
  };
  updateProjectConfiguration(tree, n.fileName, project);

  // Shared config: path alias for the service's exported contracts
  if (tree.exists('tsconfig.base.json')) {
    updateJson(tree, 'tsconfig.base.json', (json) => {
      json.compilerOptions ??= {};
      json.compilerOptions.paths ??= {};
      json.compilerOptions.paths[`@acme/${n.fileName}-contracts`] = [joinPathFragments(root, 'src/contracts/index.ts')];
      return json;
    });
  }
  await formatFiles(tree); // last, so output passes the format check untouched
}

A scaffold-service generator that calls the official @nx/node application generator first, then uses names(), joinPathFragments, generateFiles with an opt-in file set, updateProjectConfiguration for tags and a docker target, updateJson for a tsconfig path alias, and formatFiles before returning.

How do you test an Nx custom generator?

Generators run against a virtual file system, so you can test them without touching disk or spinning up a real workspace. The devkit testing utilities provide createTreeWithEmptyWorkspace, which returns an in-memory Tree with a minimal workspace configuration. Call your generator against that tree, then inspect the result.

What to assert

  • Generated files. Check that tree.exists() returns true for the paths your standards require, such as the health-check route, the Dockerfile and the OpenAPI stub. Read key files with tree.read(path, 'utf-8') and assert on specific content, like the port variable or the logger import, rather than on the whole file.
  • Project configuration. Use readProjectConfiguration(tree, name) to verify the project root, the targets you added and the tags array. Tags drive module-boundary lint rules, so a missing type:service or scope: tag is a policy failure, not a cosmetic one.
  • Name collisions. Run the generator twice with the same name. Decide whether it should throw or no-op, then assert that behavior. Never let a second run silently overwrite a working service.

Use snapshots sparingly

Use snapshots for templates, where a reviewer benefits from seeing the rendered diff. Avoid snapshotting entire trees or config objects. Those snapshots churn on every unrelated change, and reviewers learn to approve them without reading.

Test the composed output

If your generator wraps a framework generator for Node, Express or Nest, assert on the files and targets that the upstream generator produces, not only on your own additions. When an Nx upgrade renames a target or moves a file, your tests fail and the change shows up in review instead of in someone's new service.

Run these tests in CI on every pull request, including the ones that bump Nx versions.

import { Tree, readProjectConfiguration } from '@nx/devkit';
import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing';
import { serviceGenerator } from './generator';

describe('service generator', () => {
  let tree: Tree;
  const options = { name: 'orders-api', scope: 'orders' };

  beforeEach(() => {
    // Fresh in-memory workspace per test: no disk, no shared state
    tree = createTreeWithEmptyWorkspace();
  });

  it('creates the files our standards require', async () => {
    await serviceGenerator(tree, options);
    const { root } = readProjectConfiguration(tree, 'orders-api');
    expect(tree.exists(`${root}/src/routes/health.ts`)).toBe(true);
    expect(tree.exists(`${root}/openapi.yaml`)).toBe(true);
    // Assert on the specific line that matters, not the whole file
    expect(tree.read(`${root}/src/main.ts`, 'utf-8')).toContain('process.env.PORT');
    // Snapshot only the template a reviewer should see rendered
    expect(tree.read(`${root}/Dockerfile`, 'utf-8')).toMatchSnapshot();
  });

  it('sets tags and keeps the upstream targets', async () => {
    await serviceGenerator(tree, options);
    const config = readProjectConfiguration(tree, 'orders-api');
    // Tags feed module-boundary lint rules, so treat them as policy
    expect(config.tags).toEqual(expect.arrayContaining(['type:service', 'scope:orders']));
    // Targets come from the wrapped framework generator; this fails if an Nx upgrade renames them
    expect(config.targets?.build).toBeDefined();
    expect(config.targets?.serve).toBeDefined();
  });

  it('refuses to overwrite an existing service', async () => {
    await serviceGenerator(tree, options);
    // Our chosen contract: a second run throws instead of silently overwriting
    await expect(serviceGenerator(tree, options)).rejects.toThrow(/already exists/);
  });
});

A Jest spec that runs a hypothetical service generator against createTreeWithEmptyWorkspace and asserts on required files, one template snapshot, tags, upstream targets, and name-collision behavior.

How can an Nx custom generator save engineering time?

The savings come from removing repeated, low-value work at several points in a service's life, not only on the day it is created.

  • Setup. Creating a service by hand means copying a folder, renaming identifiers, fixing paths, adding project configuration, wiring logging and health checks, and getting CI green. A generator does this in one command, and --dry-run shows the result before anything is written.
  • Code review. When the standard parts are generated, reviewers of a new service only need to look at what is specific to it. The recurring comments about missing tags, misnamed targets, or unvalidated config largely disappear.
  • CI fixes. Generated targets use the names the pipeline already runs, and formatFiles makes the output pass formatting checks. That avoids the cycle of pushing, waiting for a failed check, and fixing it.
  • On-call and debugging. Services that share health endpoints, log fields, and startup config validation behave the same way under failure. Engineers can apply what they know from one service to the next instead of investigating each one from scratch.
  • Onboarding. New engineers do not need to reconstruct the conventions from wikis or existing services. The generator encodes them, and its templates serve as readable reference code.
  • Changing the standard. Updating a convention means changing the generator and its tests in one pull request, instead of updating docs and hoping people notice. Paired with migrations or an update generator, the same change can reach existing services too.

These savings scale with how often services are created and how many teams create them. The illustrative estimate in the next section shows how to weigh them against the generator's maintenance cost with your own assumed inputs.

What are the alternatives to an Nx generator for scaffolding services?

Each alternative moves the point where your standards get enforced. That point determines how much drift you accumulate.

Option Enforcement point Drift over time Maintenance owner Testability Fit with project graph tags
Nx custom generator At creation Low; template changes ship with the workspace Platform team Unit tests against a virtual Tree Writes tags directly into project config
Template repository At creation, outside the workspace High; copies diverge from the template immediately Template owner Manual None; tags must be added by hand
Wiki or checklist Never; relies on the reader High; the docs and the code age separately Whoever last edited the page None Describes tags but cannot apply them
Copy an existing service At creation Highest; you inherit that service's quirks and leftovers Nobody None Copies tags, including wrong ones
Wrapped generic scaffolding tool At creation Medium Platform team Possible, but it can't see the Nx workspace Needs custom code to edit project config
Lint and CI checks only After the code is written Low for rules you check, unchecked elsewhere Platform team Rules are testable Strong; module boundary rules read tags

Use a template repository when services live in separate repos. A checklist fits when you create a new service once or twice a year. Copying an existing service only works for a throwaway prototype. A wrapped generic tool makes sense if teams outside the monorepo also need the same scaffold. Lint and CI checks complement a generator rather than replace one. A generator puts a correct starting point in place, and the checks catch drift after that. If you can afford only one, choose the checks.

When should you avoid a custom generator, and what does it cost to maintain?

A generator copies files once. Services created last year never receive this year's template changes, so drift still happens, only more slowly. Closing that gap requires an update generator or Nx migrations that rewrite existing projects. The generator is also code the platform team owns. It depends on Nx Devkit APIs, so every Nx major upgrade means re-running its tests and possibly fixing it. If it wraps a framework generator, your output changes whenever that upstream output changes. Over-standardizing has its own cost: teams delete the files they don't want or fork the generator. Finally, a generator enforces nothing after creation. Lint rules, module boundary checks and CI still do that work.

Situation Build a generator?
Several new services per quarter, stable standard, named owner Yes
One or two new services a year No. A documented reference service is enough
Standard still changing week to week Not yet. Let it settle first
No team willing to own it No. It will rot

Illustrative estimate (assumed numbers, not a benchmark)

Net hours per quarter = (services per quarter × setup hours avoided) − (Nx upgrades per quarter × hours per upgrade) − template upkeep hours

Assumed inputs: 4 services, 6 hours avoided each, 0.5 upgrades at 8 hours each, and 4 hours of upkeep. That gives 24 − 4 − 4 = 16 hours saved. With 1 service per quarter, the result is 6 − 4 − 4 = −2 hours, so the generator costs more than it saves.

Rolling it out

Document the generator next to its source: the command, its options and what it produces. Use it in onboarding so new engineers create their first service with it. Ship migrations or an update generator alongside it so existing services keep up with the standard.

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.
  • 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.