What does the NestJS exports array actually guarantee?
In NestJS, a module's exports array controls visibility inside the dependency injection container. If UsersModule registers UsersRepository as a provider but does not export it, any provider in OrdersModule that requests it through its constructor fails at bootstrap. Nest reports that it cannot resolve the dependency, and the application does not start. This is real encapsulation, but it covers only one thing: which instances the container will hand to which modules.
The container has no say over the TypeScript import graph. A file in orders/ can still write import { UsersRepository } from '../users/users.repository' and call new UsersRepository(dataSource) itself, without going through DI. The same applies to entity classes, DTOs, enums and helper functions. These imports compile, pass type checks and run. Nest never sees them, because the code never asks the injector for anything. The example below shows this case: the DI-based injection is rejected, while a deep import of the same class works without complaint.
Type-level coupling is the quieter version of the same problem. If orders imports the User entity only to type a parameter, it now depends on the users module's internal schema. A column rename in users then breaks orders.
This guide treats DI encapsulation and source-level encapsulation as separate concerns and enforces boundaries at three layers:
- DI exports. These decide which providers other modules can inject.
- TypeScript import rules. Lint rules and path aliases decide which files other modules can import.
- A CI-checked dependency graph. This catches violations the first two layers miss before they reach the main branch.
// users/users.repository.ts
import { Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { User } from './user.entity';
@Injectable()
export class UsersRepository {
constructor(private readonly dataSource: DataSource) {}
findById(id: string) {
return this.dataSource.getRepository(User).findOneBy({ id });
}
}
// users/users.module.ts: UsersRepository is a provider but is NOT exported
@Module({ providers: [UsersRepository], exports: [] })
export class UsersModule {}
// orders/orders.service.ts: DI path, rejected by Nest
// OrdersModule imports UsersModule, but the provider is not exported, so
// bootstrap fails with "Nest can't resolve dependencies of the OrdersService".
@Injectable()
export class OrdersService {
constructor(private readonly users: UsersRepository) {}
}
// orders/order-report.ts: deep import path, accepted by tsc and at runtime
import { DataSource } from 'typeorm';
import { UsersRepository } from '../users/users.repository'; // reaches into users internals
import { User } from '../users/user.entity'; // type-level coupling to users' schema
export async function buildOrderReport(ds: DataSource, userId: string) {
// Built by hand, so the injector is never asked and never objects
const repo = new UsersRepository(ds);
const user: User | null = await repo.findById(userId);
return { customer: user?.email };
}
The same non-exported UsersRepository fails at bootstrap when OrdersService injects it, but a relative deep import that constructs it manually compiles and runs without any error from Nest.
How does boundary enforcement work end to end?
Each layer checks a different thing at a different time. Together they cover the gaps the others leave.
- At bootstrap, the Nest injector checks provider visibility. When Nest builds the module graph, it resolves each constructor dependency by looking at the providers registered in the requesting module and the providers exported by the modules it imports. If the requested token is not in either set, resolution fails and the application does not start. This layer only sees what goes through DI.
- At lint time, ESLint checks import specifiers.
no-restricted-importslooks at the string in eachimportstatement and compares it against your patterns. It does not resolve types or run code. It rejects any specifier that reaches past a module'sindex.ts, or that points at a module the current directory is not allowed to depend on. This catches the deep imports and manualnewcalls the injector never sees. - At compile time, path aliases shape the default. An alias such as
@modules/billingmaps to the module's barrel file intsconfig.json. Developers and editor autocompletion reach for the alias, so the legitimate import is also the easiest one to write. - In CI, the lint run becomes a gate. Running ESLint with
--max-warnings=0as a required step means a boundary violation blocks the merge instead of landing on the main branch as a warning. - In code review, the remaining gaps get human attention. Reviewers check that the barrel and the
exportsarray still match, and they question any neweslint-disablecomment,forwardRef()between feature modules, or raw SQL against another module's tables.
The result is that a module's public API is defined twice, once for DI (exports) and once for source imports (index.ts), and each definition has an automated check that rejects anything outside it.
What is a public API module, and how do you design its facade?
A public API module is a module whose consumers can reach it only through one file: an index.ts barrel at the module root. That barrel re-exports the module class, a facade service (or a small, deliberate set of services), and the DTOs or interfaces consumers need. Entities, repositories, internal services and mappers are never re-exported, so other modules have no legitimate path to them.
The facade's methods should map to use cases, such as getContactDetails(userId) or isAccountActive(userId), rather than generic data access. They should return plain DTOs or read models, not ORM entities. An entity exposes the persistence shape and any lazy-loaded relations. A consumer that touches user.profile then depends on your schema and your loading strategy without either side noticing.
In the example below, the orders module first imports UserEntity and queries it directly. After the change, it imports UsersModule and calls UsersFacade.getContactDetails(). The matching @Module declares exports: [UsersFacade].
That exports array is the DI half of the public API, and the barrel is the source-import half. If a service is exported for injection but missing from the barrel, or the reverse, the two halves have drifted apart. Code review should check that they match.
Barrels have costs:
- They make circular imports easier to create.
- They can make it harder for bundlers and test runners to skip unused code.
- A single
export *can widen the API without anyone noticing.
Re-export each name explicitly instead.
// users/index.ts: source-import half of the public API (explicit names, no `export *`)
export { UsersModule } from './users.module';
export { UsersFacade } from './users.facade';
export type { ContactDetailsDto } from './dto/contact-details.dto';
// Deliberately NOT exported: UserEntity, UsersRepository, UserMapper
// users/users.module.ts: DI half; `exports` must match the barrel's services
@Module({
imports: [TypeOrmModule.forFeature([UserEntity])],
providers: [UsersFacade, UsersRepository],
exports: [UsersFacade], // the repository stays injectable only inside this module
})
export class UsersModule {}
// users/users.facade.ts: use-case-shaped methods that return plain DTOs
@Injectable()
export class UsersFacade {
constructor(private readonly users: UsersRepository) {}
async getContactDetails(userId: string): Promise<ContactDetailsDto> {
const user = await this.users.findByIdOrFail(userId);
// Copy fields out so callers never hold the entity or its lazy relations
return { userId: user.id, email: user.email, displayName: user.displayName };
}
}
// orders/orders.service.ts
// BEFORE: reached into users internals and depended on the schema
// import { UserEntity } from '../users/entities/user.entity';
// @InjectRepository(UserEntity) private users: Repository<UserEntity>
// AFTER: imports only from the barrel. OrdersModule adds `imports: [UsersModule]`
import { UsersFacade } from '../users';
@Injectable()
export class OrdersService {
constructor(private readonly usersFacade: UsersFacade) {}
async confirmationEmailFor(userId: string): Promise<string> {
return (await this.usersFacade.getContactDetails(userId)).email;
}
}
A users module whose barrel and @Module exports both expose only UsersFacade and its DTO, and an orders service that switches from querying UserEntity directly to calling the facade.
How do you enforce module boundaries with ESLint, path aliases and CI?
Start with ESLint's built-in no-restricted-imports rule. Configure patterns to reject any path that reaches past another module's entry file, such as **/billing/services/* or **/billing/entities/*. Then add one TypeScript path alias per module, such as @modules/billing, that points only at src/modules/billing/index.ts. The alias becomes the short, autocompleted import, and a deep import becomes the one that fails lint. If the team already runs a boundaries or dependency-graph lint tool, encode the same rules there instead of maintaining two sets.
Entry points alone don't stop orders and billing from importing each other. Write the allowed dependency directions in the repository, enforce them as rules, and forbid cycles:
orders ──────► billing
│ │
▼ ▼
┌─────────────────────┐
│ shared / core │ (depends on no feature module)
└─────────────────────┘
Run the check in CI as a required step so a violation fails the build rather than appearing as a warning nobody reads.
Treat forwardRef() between feature modules as a signal. It resolves Nest's provider cycle at runtime, but the two modules still depend on each other. The usual fixes are to move the shared concept into its own module, invert the call with an event, or merge the modules.
Lint enforcement has limits. It can miss:
- Unusual relative paths (
../../billing/./services) that your patterns don't match. - Dynamic
import()calls built from variables. - Files outside the linted globs, such as scripts and seeds.
eslint-disablecomments added instead of fixing the design. Require a reviewer for any such comment.
// eslint.config.js: module boundaries as lint errors
import tseslint from 'typescript-eslint';
// Everyone: reach other modules only through their entry (index.ts).
const deepImports = {
group: ['@modules/*/*', '**/modules/*/*'],
message: 'Import a module via its entry only, e.g. @modules/billing.',
};
// Ban a module entirely, including its entry, to enforce direction.
const forbid = (...mods) => ({
group: mods.flatMap((m) => [`@modules/${m}`, `**/modules/${m}`, `**/modules/${m}/*`]),
message: 'Dependency direction violation. See docs/module-dependencies.md.',
});
// Later config objects replace this rule rather than merging with it,
// so every override must repeat the deep-import ban.
const restrict = (...extra) => ['error', { patterns: [deepImports, ...extra] }];
export default [
{
files: ['src/**/*.ts'],
languageOptions: { parser: tseslint.parser },
rules: { 'no-restricted-imports': restrict() },
},
// Allowed: orders -> billing -> shared. Reverse edges are errors,
// which also rules out an orders <-> billing cycle.
{
files: ['src/modules/billing/**/*.ts'],
rules: { 'no-restricted-imports': restrict(forbid('orders')) },
},
{
files: ['src/modules/shared/**/*.ts'],
rules: { 'no-restricted-imports': restrict(forbid('orders', 'billing')) },
},
];
// CI (required step): npx eslint src --max-warnings=0
// Not caught: paths like ../billing/services, dynamic import(), files outside src/.
An ESLint flat config that uses the built-in no-restricted-imports rule to block deep imports everywhere and to enforce the orders → billing → shared dependency direction per module directory, run in CI with zero warnings allowed.
How should NestJS modules communicate without tight coupling?
A facade call is the right default, but it gives the caller a compile-time and runtime dependency on the callee. When Orders should not know that Notifications exists, two patterns remove that dependency.
In-process events. The publisher emits a domain event through an event emitter or a small dispatcher, and listeners in other modules react to it. The publisher depends only on the event's shape.
Ports. The dependent module declares an interface and an injection token in its public API. The other module implements that interface and binds the implementation to the token in its providers. The dependency now points toward the module that owns the interface, which should be the more stable side. The example below shows a port interface, its token and the provider binding.
| Approach | Coupling | Debuggability | Transaction behaviour | Durability |
|---|---|---|---|---|
| Facade call | Caller knows callee's API | Linear stack trace | Can share the caller's transaction | Same as caller |
| In-process event | Publisher knows only the event | Indirect; you must find the listeners | Depends on dispatch mode | Lost on crash |
| Port/adapter | Implementer depends on consumer's interface | Linear, one hop through the token | Can share the caller's transaction | Same as caller |
Check how your emitter dispatches before you rely on it. A synchronous listener that throws may abort and roll back the publisher's work. An asynchronous listener fails after the publisher has committed. In-process events also disappear if the process dies, so if delivery must be guaranteed, write events to an outbox table in the same transaction as the business change.
Put generic technical code, such as logging, configuration and base error types, in a core or shared module. Keep domain concepts out of it. A common module that keeps growing with DTOs and helpers becomes a backdoor that bypasses every boundary you enforce.
import { DynamicModule, Inject, Injectable, Module, ModuleMetadata } from '@nestjs/common';
// orders/public-api.ts: Orders owns the port, so the dependency points at Orders.
export interface OrderNotifier {
orderPlaced(orderId: string, customerId: string): Promise<void>;
}
export const ORDER_NOTIFIER = Symbol('ORDER_NOTIFIER');
// orders/orders.service.ts: depends only on the interface and token, never on Notifications.
@Injectable()
export class OrdersService {
constructor(@Inject(ORDER_NOTIFIER) private readonly notifier: OrderNotifier) {}
async placeOrder(orderId: string, customerId: string): Promise<void> {
// ...persist the order...
await this.notifier.orderPlaced(orderId, customerId);
}
}
// orders/orders.module.ts: the adapter module is supplied by the composition root.
@Module({})
export class OrdersModule {
static register(opts: { adapters: ModuleMetadata['imports'] }): DynamicModule {
return { module: OrdersModule, imports: opts.adapters, providers: [OrdersService] };
}
}
// notifications/email-order-notifier.ts: Notifications implements the Orders port.
@Injectable()
export class EmailOrderNotifier implements OrderNotifier {
async orderPlaced(orderId: string, customerId: string): Promise<void> {
// ...send an email to the customer...
}
}
// notifications/notifications.module.ts: bind the implementation to the token and export only the token.
@Module({
providers: [EmailOrderNotifier, { provide: ORDER_NOTIFIER, useExisting: EmailOrderNotifier }],
exports: [ORDER_NOTIFIER],
})
export class NotificationsModule {}
// app.module.ts: imports: [OrdersModule.register({ adapters: [NotificationsModule] })]
Orders defines a port interface and injection token, Notifications binds its adapter to that token, and the app module wires them together, so Orders has no code dependency on Notifications.
How do you enforce data ownership when modules share one database?
A shared database is where boundaries usually erode first, because the ORM makes crossing them effortless. The rule is simple: each module owns its tables. Only that module's repositories read or write them. Other modules do not inject its repositories, declare entity relations pointing into its tables, or write raw SQL against them. When the billing module needs a customer's name, it calls the customers facade, or reads from a read model built for that purpose.
Make ownership visible at the table level. Where the database supports it, give each module its own schema, such as billing or customers. A query that references customers.accounts from billing code then stands out in code review. If schemas are not an option, a table-name prefix per module does the same job less strictly. You can also grant each module's database role access only to its own schema, so a violation fails at runtime instead of relying on reviewers to catch it.
This costs you some convenience:
- No cross-module joins or transactions. Workflows that span modules need explicit coordination, for example an outbox table and eventual consistency, rather than one database transaction.
- Reporting gets harder. Analytical queries often need data from many modules. Serve them from a dedicated read model, or allow a documented exception that names the queries and the tables they touch.
- Extra round trips. Mapping DTOs through facades can turn a cheap join into N+1 calls. Design facades with batch methods such as
findByIdsfrom the start.
Who should use an enforced modular monolith?
This approach fits teams that want one deployable NestJS application but need the internal structure to hold up as the codebase and headcount grow. Typical candidates:
- Several teams sharing one repository. When different teams own
billing,ordersandcustomers, enforced public APIs let each team change its internals without negotiating with every importer. - Products whose domains are reasonably well understood. You can name the business capabilities and who owns each one, even if the details are still changing.
- Teams that may extract services later but are not ready to run them now. Facades, ports and per-module data ownership are the same seams a service split would need, without the operational cost of a distributed system today.
- Codebases already feeling coupling pain. Signs include
forwardRef()between feature modules, refactors that break unrelated tests, and repositories injected across module lines.
It is a weaker fit for a single developer or a very small team, a prototype whose domain model is still being discovered, or an application with only a handful of modules. In those cases the facades, DTO mappings and lint configuration cost more than the coupling they prevent. The next section covers this trade-off and the alternatives in more detail.
When should you use strict module boundaries, and what are the alternatives?
Strict boundaries pay off when several teams work in one codebase, when domains are still growing, or when you expect to extract services later. In those cases, an unenforced import between two teams' modules becomes a coordination cost that nobody planned for. For a small team, a few modules or an early product, the trade usually runs the other way. You write facades and DTOs for coupling that one person could untangle in an afternoon.
Timing matters more than tooling. If you draw boundaries before the domain is understood, or along technical layers such as controllers, repositories and utils instead of business capabilities such as billing or fulfilment, you lock in the wrong seams. Enforcement does not tell a good boundary from a bad one. It makes both harder to move, so a misplaced boundary now needs rule changes, facade rewrites and review sign-off before it can shift.
| Approach | Development cost | Enforcement strength | Operational overhead |
|---|---|---|---|
Conventional NestJS app, DI exports only |
Low | Weak: deep imports still compile | Low |
| Folder convention, no tooling | Low | None: depends on code review | Low |
| Fully enforced modular monolith | Medium | Strong at build and CI time | Low |
| Separate packages in a monorepo | Medium to high | Strong: package manifests gate imports | Medium |
| Microservices | High | Strongest: network boundary | High |
A well-bounded monolith makes later extraction easier, but not free. Once a facade call becomes a network call, you still have to design for partial failure, added latency and distributed data consistency. In-process calls never forced you to handle any of these.
How can enforced boundaries save engineering time?
The time savings come from shrinking the set of code a change can affect, and from catching mistakes earlier, when they are cheaper to fix.
- Smaller blast radius for refactors. If only the facade and its DTOs are public, you can rename an entity column, split a repository or change a loading strategy inside a module without searching the whole codebase for importers. The facade's callers are the only code you need to check.
- Violations are caught at lint time, not in production or review. A deep import fails in the editor or in CI within the same pull request that introduced it. Without the rule, the same coupling is often found much later, when a schema change in one module breaks another.
- Faster, more focused code review. Reviewers of a module change look at its public API for breaking changes and can treat internals as private. Cross-module changes stand out because they touch a barrel file or an
exportsarray. - Simpler tests. A consumer that depends on a facade or a port token can be tested with a small stub of that interface, instead of a database fixture for another module's tables.
- Clearer ownership. When something breaks, the module that owns the table or the facade owns the fix, which cuts down on back-and-forth between teams.
- Cheaper extraction later. If a module does need to become a separate service, its callers already go through one facade, so the change is replacing an in-process implementation rather than untangling scattered imports.
Illustrative estimate, using assumed inputs rather than measured results: assume a team changes an internal detail of the users module about four times a month, and that without enforced boundaries each change requires roughly two hours of searching for and fixing deep importers in other modules. With a facade in place, assume that drops to about half an hour of checking the facade's callers. That is an assumed saving of about six hours a month on that one module. Set that against the assumed ongoing cost of maintaining facades, DTO mappings and lint configuration, which the next section notes is real and continuous. Plug in your own change frequency and fix times. If the result is small or negative, the boundaries are not yet worth enforcing for that module.
How do you adopt module boundaries in an existing NestJS codebase?
Pick one module with a clear owner and moderate inbound traffic, not the most tangled one. Add its barrel file, route external callers through the facade, and leave other modules alone. Each conversion is then a reviewable pull request rather than a branch that drifts for weeks.
Roll out the lint rule in stages
Turn the deep-import rule on as a warning across the whole repository first. Record the existing violations as a baseline, either as a suppression list or as inline disables tagged with a ticket reference, so CI fails only on new violations. Feature teams keep shipping, and the backlog stays visible.
When a module's inbound violations reach zero, promote the rule to an error for that module's paths. In ESLint's flat config, this is an extra config object whose files glob matches that module's directory, with the rule severity set to "error". Modules still being cleaned up stay on "warn". This prevents a cleaned-up module from regressing while the others catch up. The example below shows this layering.
What you gain, and what it costs
The gains are qualitative, not measured:
- Reviewers check changes against a small public surface instead of every importer.
- Internal refactors stop breaking distant callers.
- Accidental joins against another module's tables become rare.
- Ownership questions have a clear answer.
The costs continue for as long as the boundaries exist. Someone has to maintain the facades and the DTO mappings, and someone has to keep the lint configuration in step with the directory layout. Budget for that work explicitly. If nobody owns it, the boundaries erode back into deep imports.
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 nestjs modular monolith, 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.