nestjs-backend-patterns
Skill29 starsChanged 2 months agoMITView on GitHub
NestJS backend architecture for multi-tenant SaaS. Use for third-party API providers, Prisma or ZenStack setup, multitenancy, authentication, RBAC or policies, and repositories. Not for retries, events or dynamic modules — use resilient-nestjs-patterns.
- Reads credentials
In this repository25 other files it gives its agents.
- .github/copilot-instructions.mdCopilot instructions
- agent-lanesSkill
- angular-3d-scene-crafterSkill
- angular-frontend-patternsSkill
- angular-gsap-animation-crafterSkill
- ddd-architectureSkill
- execute-phase-gated-taskSkill
- extract-and-relocate-angular-component-featureSkill
- fleet-orchestrationSkill
- humanize-librarySkill
- impeccableSkill
- nestjs-deploymentSkill
- nx-workspace-architectSkill
- orchestrationSkill
- ptah-cli-usageSkill
- resilient-nestjs-patternsSkill
- saas-platform-patternsSkill
- saas-workspace-initializerSkill
- skill-creatorSkill
- technical-content-writerSkill
- tribunalSkill
- typesafe-aiSkill
- ui-ux-designerSkill
- video-showcaseSkill
- webhook-architectureSkill
The file
We split this skill into the rules it gives an agent
1 rule. About 0 are common, 1 is distinctive, and 0 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 16
All third-party integrations follow the same provider pattern:
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
NestJS Backend Architecture Patterns
Patterns for building scalable, maintainable NestJS backends in an Nx monorepo.
Activation scope
This skill activates per-module during Stage B of the SaaS bootstrap. saas-workspace-initializer may scaffold thin tenant/auth primitives in the Stage A foundation, but full provider-pattern integrations, multitenancy enforcement, and Prisma/ZenStack policy work happen in dedicated Stage B sessions driven by individual roadmap items. Pull this skill in when implementing one such item, not to retrofit an entire backend.
Core Principle: Provider Pattern for External Services
All third-party integrations follow the same provider pattern:
// 1. Create a provider factory
export const ThirdPartyClientProvider = {
provide: 'THIRD_PARTY_CLIENT',
useFactory: (configService: ConfigService) => {
return new ThirdPartySDK(configService.get('THIRD_PARTY_API_KEY'));
},
inject: [ConfigService],
};
// 2. Create a service that wraps the client
@Injectable()
export class ThirdPartyService {
constructor(@Inject('THIRD_PARTY_CLIENT') private client: ThirdPartySDK) {}
async doSomething() {
return this.client.operation();
}
}
// 3. Create a module that exports the service
@Module({
imports: [ConfigModule],
providers: [ThirdPartyClientProvider, ThirdPartyService],
exports: [ThirdPartyService],
})
export class ThirdPartyModule {}Quick Reference
| Pattern | Use Case | Reference |
| Provider Pattern | Third-party API integration | third-party-integration.md |
| Multitenancy | Shared schema with tenant isolation | multitenancy.md |
| Prisma + ZenStack | ORM with declarative access control | prisma-zenstack.md |
| RBAC | Role-based authorization | authorization.md |
| JWT Authentication | Stateless auth with Passport | authentication.md |
Third-Party Integration Pattern
Step 1: Provider Factory
// libs/shared/payments/src/lib/payment-client.provider.ts
import { ConfigService } from '@nestjs/config';
export const PaymentClientProvider = {
provide: 'PAYMENT_CLIENT',
useFactory: (config: ConfigService) => {
const provider = config.get('PAYMENT_PROVIDER'); // 'stripe', 'paddle', etc.
const apiKey = config.get('PAYMENT_API_KEY');
// Factory returns appropriate client based on config
switch (provider) {
case 'stripe':
return new StripeClient(apiKey);
case 'paddle':
return new PaddleClient(apiKey);
default:
throw new Error(`Unknown payment provider: ${provider}`);
}
},
inject: [ConfigService],
};Step 2: Abstract Service Interface
// libs/shared/payments/src/lib/payment.interface.ts
export interface PaymentClient {
createCustomer(data: CreateCustomerDto): Promise<Customer>;
createSubscription(data: CreateSubscriptionDto): Promise<Subscription>;
cancelSubscription(id: string): Promise<void>;
handleWebhook(payload: Buffer, signature: string): Promise<WebhookEvent>;
}Step 3: Service Implementation
// libs/shared/payments/src/lib/payment.service.ts
@Injectable()
export class PaymentService {
constructor(@Inject('PAYMENT_CLIENT') private client: PaymentClient) {}
async createCustomer(dto: CreateCustomerDto): Promise<Customer> {
return this.client.createCustomer(dto);
}
async createSubscription(dto: CreateSubscriptionDto): Promise<Subscription> {
return this.client.createSubscription(dto);
}
}Multitenancy Pattern (Shared Schema)
// Context-aware Prisma service using CLS (Continuation Local Storage)
@Injectable()
export class TenantAwarePrismaService {
constructor(
private prisma: PrismaService,
private cls: ClsService,
) {}
get client() {
const tenantId = this.cls.get('tenantId');
if (!tenantId) {
throw new UnauthorizedException('No tenant context');
}
// Return enhanced client with tenant filter
return enhance(this.prisma, { user: { tenantId } });
}
}Module Organization
libs/
├── shared/
│ ├── prisma-client/ # Prisma + ZenStack setup
│ │ ├── prisma.service.ts
│ │ ├── enhanced-prisma.service.ts
│ │ └── prisma-client.module.ts
│ ├── auth/ # Authentication infrastructure
│ │ ├── strategies/
│ │ │ └── jwt.strategy.ts
│ │ ├── guards/
│ │ │ ├── jwt-auth.guard.ts
│ │ │ └── roles.guard.ts
│ │ └── auth.module.ts
│ └── [service-name]/ # Third-party integrations
│ ├── [name]-client.provider.ts
│ ├── [name].service.ts
│ └── [name].module.ts
└── [domain]/
└── feature-api/
├── controllers/
├── dto/
└── [domain].module.tsDecision Matrix
| Need | Pattern | Reference |
| Payment processing | Provider pattern | third-party-integration.md |
| External auth (OAuth) | Provider pattern + Passport | authentication.md |
| Email service | Provider pattern | third-party-integration.md |
| File storage | Provider pattern | third-party-integration.md |
| Tenant isolation | ZenStack policies | multitenancy.md |
| Role-based access | Guards + decorators | authorization.md |
References
Load these for detailed implementation guidance:
- third-party-integration.md - Generic pattern for any external service
- multitenancy.md - Multi-tenant architecture patterns
- prisma-zenstack.md - ORM setup with access policies
- authorization.md - RBAC and permission patterns
- authentication.md - JWT and OAuth patterns
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

