Cursor rules for NestJS feature modules with deliberate exports, few globals, no circular imports, ConfigurableModuleBuilder modules and serverless-only lazy loading.
.cursor/rules/nestjs-module-structure.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rules for NestJS feature modules with deliberate exports, few globals, no circular imports, ConfigurableModuleBuilder modules and serverless-only lazy loading."
globs: "**/*"
alwaysApply: false
---
# NestJS Module Structure
Applies to: NestJS feature modules, their providers and controllers, and shared or configurable modules (`src/**/*.module.ts`, `*.service.ts`, `*.controller.ts`).
Version baseline: checked against the current NestJS documentation (npm `@nestjs/core` 12.x at review time; the module system is the same in 11.x). Read `package.json` for the installed `@nestjs/*` versions and follow them.
## One module per feature
- A feature module owns one area of the domain (`UsersModule`, `BillingModule`): its controllers, providers and persistence wiring.
- Keep a module's files together: `users/users.module.ts`, `users/users.controller.ts`, `users/users.service.ts`, `users/dto/`, `users/entities/`.
- Split a module when it serves unrelated features or when other modules import it for only a small part of it.
## Naming
- Classes in PascalCase with a role suffix (`UsersModule`, `UsersService`, `UsersController`); files in kebab-case with the role (`users.service.ts`), as generated by `nest g`.
- Variables and methods in camelCase.
## Module metadata
- `imports`: modules whose exported providers this module uses.
- `controllers`: controllers instantiated by this module.
- `providers`: services, repositories and factories created by this module's injector.
- `exports`: the subset of providers (or imported modules) other modules may inject. Export only the public API of the feature; keep internal helpers unexported.
```ts
// users/users.module.ts
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { UsersRepository } from './users.repository';
@Module({
controllers: [UsersController],
providers: [UsersService, UsersRepository],
exports: [UsersService],
})
export class UsersModule {}
```
If the project uses TypeORM, register entities per feature with `imports: [TypeOrmModule.forFeature([UserEntity])]` and keep `TypeOrmModule.forRoot(...)` in the root module; with Prisma or another ORM, provide a shared database module instead.
## Dependencies between modules
- Depend on another feature through its exported service, by importing its module. Do not reach into another module's repository or entities.
- Modules are singletons; importing a module in several places shares the same provider instances.
- Avoid `@Global()` except for truly cross-cutting infrastructure (configuration, logging); global modules hide dependencies.
- Avoid circular imports between modules. Extract the shared part into a third module or use events. Use `forwardRef(() => OtherModule)` on both sides only as a last resort; instantiation order is then indeterminate.
## Configurable (dynamic) modules
- Expose configuration through static methods that return a `DynamicModule`. By convention: `register()` for per-consumer configuration, `forRoot()` to configure once for the app, `forFeature()` for per-module additions. Provide `...Async` variants when options come from `ConfigService`.
- Build them with `ConfigurableModuleBuilder` instead of hand-writing option providers.
- Read environment variables through `@nestjs/config` (`ConfigModule.forRoot({ isGlobal: true })` with validation), not `process.env` scattered across services.
```ts
// cache/cache.module-definition.ts
import { ConfigurableModuleBuilder } from '@nestjs/common';
export interface CacheModuleOptions {
ttlSeconds: number;
}
export const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =
new ConfigurableModuleBuilder<CacheModuleOptions>().setClassMethodName('forRoot').build();
```
## Lazy loading
`LazyModuleLoader` exists to reduce bootstrap time in serverless functions that need only some modules per invocation. Do not use it in long-running servers by default. Lazy-loaded modules do not run lifecycle hooks, and controllers cannot be lazy-loaded.
## Decoupling and testing
- Inject abstractions with custom provider tokens (`{ provide: PAYMENT_GATEWAY, useClass: StripeGateway }`) where you expect to swap implementations; inject concrete classes otherwise.
- Test a module's providers with `Test.createTestingModule`, overriding external dependencies with `.overrideProvider(...)`.
## Verify before finishing
Run these when they are available in the project:
- `npm run build` (Nest compiles with `tsc`; missing exports or imports surface at startup)
- `npm test` and the e2e suite (`npm run test:e2e`), which boot the module graph
- Start the app once and check the log for "Nest can't resolve dependencies" errors
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
coding
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A NestJS API has this rule attached while a developer asks Cursor to add an orders feature that needs user lookups and a configurable cache.
Create an OrdersModule with a controller and service. OrdersService needs UsersService to look up the buyer, and a CacheModule configured once with a TTL from config.
Illustrative; not a recorded model run. UsersModule exporting only UsersService; OrdersModule importing UsersModule (not UsersRepository) and declaring its own controller and providers; a CacheModule built with ConfigurableModuleBuilder exposing forRoot/forRootAsync and registered once in AppModule using ConfigService; no @Global() on feature modules, no forwardRef, no LazyModuleLoader in the long-running server; a Test.createTestingModule test overriding UsersService.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/nestjs-module-structure.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "NestJS Module Structure: Feature Modules, Exports and Dynamic Modules project conventions"
globs: "**/*"
alwaysApply: false
---
# NestJS Module Structure
Applies to: NestJS feature modules, their providers and controllers, and shared or configurable modules (`src/**/*.module.ts`, `*.service.ts`, `*.controller.ts`).
Version baseline: checked against the current NestJS documentation (npm `@nestjs/core` 12.x at review time; the module system is the same in 11.x). Read `package.json` for the installed `@nestjs/*` versions and follow them.
## One module per feature
- A feature module owns one area of the domain (`UsersModule`, `BillingModule`): its controllers, providers and persistence wiring.
- Keep a module's files together: `users/users.module.ts`, `users/users.controller.ts`, `users/users.service.ts`, `users/dto/`, `users/entities/`.
- Split a module when it serves unrelated features or when other modules import it for only a small part of it.
## Naming
- Classes in PascalCase with a role suffix (`UsersModule`, `UsersService`, `UsersController`); files in kebab-case with the role (`users.service.ts`), as generated by `nest g`.
- Variables and methods in camelCase.
## Module metadata
- `imports`: modules whose exported providers this module uses.
- `controllers`: controllers instantiated by this module.
- `providers`: services, repositories and factories created by this module's injector.
- `exports`: the subset of providers (or imported modules) other modules may inject. Export only the public API of the feature; keep internal helpers unexported.
```ts
// users/users.module.ts
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { UsersRepository } from './users.repository';
@Module({
controllers: [UsersController],
providers: [UsersService, UsersRepository],
exports: [UsersService],
})
export class UsersModule {}
```
If the project uses TypeORM, register entities per feature with `imports: [TypeOrmModule.forFeature([UserEntity])]` and keep `TypeOrmModule.forRoot(...)` in the root module; with Prisma or another ORM, provide a shared database module instead.
## Dependencies between modules
- Depend on another feature through its exported service, by importing its module. Do not reach into another module's repository or entities.
- Modules are singletons; importing a module in several places shares the same provider instances.
- Avoid `@Global()` except for truly cross-cutting infrastructure (configuration, logging); global modules hide dependencies.
- Avoid circular imports between modules. Extract the shared part into a third module or use events. Use `forwardRef(() => OtherModule)` on both sides only as a last resort; instantiation order is then indeterminate.
## Configurable (dynamic) modules
- Expose configuration through static methods that return a `DynamicModule`. By convention: `register()` for per-consumer configuration, `forRoot()` to configure once for the app, `forFeature()` for per-module additions. Provide `...Async` variants when options come from `ConfigService`.
- Build them with `ConfigurableModuleBuilder` instead of hand-writing option providers.
- Read environment variables through `@nestjs/config` (`ConfigModule.forRoot({ isGlobal: true })` with validation), not `process.env` scattered across services.
```ts
// cache/cache.module-definition.ts
import { ConfigurableModuleBuilder } from '@nestjs/common';
export interface CacheModuleOptions {
ttlSeconds: number;
}
export const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =
new ConfigurableModuleBuilder<CacheModuleOptions>().setClassMethodName('forRoot').build();
```
## Lazy loading
`LazyModuleLoader` exists to reduce bootstrap time in serverless functions that need only some modules per invocation. Do not use it in long-running servers by default. Lazy-loaded modules do not run lifecycle hooks, and controllers cannot be lazy-loaded.
## Decoupling and testing
- Inject abstractions with custom provider tokens (`{ provide: PAYMENT_GATEWAY, useClass: StripeGateway }`) where you expect to swap implementations; inject concrete classes otherwise.
- Test a module's providers with `Test.createTestingModule`, overriding external dependencies with `.overrideProvider(...)`.
## Verify before finishing
Run these when they are available in the project:
- `npm run build` (Nest compiles with `tsc`; missing exports or imports surface at startup)
- `npm test` and the e2e suite (`npm run test:e2e`), which boot the module graph
- Start the app once and check the log for "Nest can't resolve dependencies" errors
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.