feat: create Next.js Feature-Based Architecture Extension Pack

- Built specifically for nextjs-new-app template (Next.js 15+, Tailwind 4.x)
- Added 6 specialized AI agents including Domain Architect and BaseController Specialist
- Implemented 7 workflows for Domain-Driven Design and Feature-Based Architecture
- Created 5 architecture templates (BaseController, Schema-First, Feature Structure)
- Added 3 comprehensive checklists for development quality
- Includes setup task for nextjs-new-app template integration
- Supports database-agnostic patterns with Zod validation
- Follows strict TypeScript and modern Next.js App Router patterns

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Márcio Barroso 2025-09-24 10:14:06 -03:00
parent 52f6889089
commit a3bfeac185
25 changed files with 2309 additions and 0 deletions

View File

@ -0,0 +1,204 @@
# 🚀 BMAD Next.js Feature-Based Architecture Extension Pack
A comprehensive AI-powered Next.js 15+ development framework using Feature-Based Architecture and Domain-Driven Design principles, built on the `marciobarroso/nextjs-new-app` template.
## 📋 Overview
This extension pack provides everything needed to build enterprise-grade Next.js applications following Feature-Based Architecture patterns. Built specifically for the `nextjs-new-app` template, it includes specialized AI agents, Domain-Driven Design workflows, BaseController patterns, and schema-first development to accelerate your development process.
## ✨ Features
### 🤖 Specialized AI Agents
- **Domain Architect** - Business domain modeling and bounded context definition
- **Next.js Architect** - Feature-Based Architecture and App Router patterns
- **BaseController Specialist** - Database-agnostic controller patterns and schema-first design
- **TypeScript Specialist** - Strict type safety and advanced TypeScript patterns
- **Tailwind Designer** - Tailwind CSS 4.x design with utility-first approach
- **API Developer** - RESTful API design following BaseController patterns
- **Database Specialist** - Database-agnostic integration (Prisma, MongoDB, etc.)
- **Auth Specialist** - Authentication and authorization integration
- **Testing Engineer** - Feature-based testing strategies
- **Deployment Specialist** - Production deployment for Feature-Based Architecture
- **Performance Optimizer** - Next.js 15+ optimization and Core Web Vitals
- **Security Auditor** - Security best practices for modern web applications
### 🔄 Domain-Driven Workflows
- **Feature-Based Project Setup** - Initialize project from `nextjs-new-app` template
- **Domain Feature Development** - Complete business domain implementation
- **BaseController Implementation** - Database-agnostic controller setup
- **Cross-Feature Integration** - Manage dependencies between features
- **Schema-First Development** - Zod validation and type-safe patterns
- **Testing Pipeline** - Feature-based testing strategies
- **Deployment Pipeline** - Production deployment with Feature-Based Architecture
### 📝 Architecture Templates
- Feature Structure Template (Complete feature organization)
- BaseController Extension Template (Database-agnostic controller)
- Schema-First Entity Template (Zod validation + TypeScript types)
- Feature Component Template (React + TypeScript + Tailwind)
- API Route Template (BaseController integration)
- Custom Hooks Template (Data fetching patterns)
### ✅ Architecture Checklists
- Feature-Based Architecture Development Checklist
- BaseController Implementation Checklist
- Domain-Driven Design Checklist
- Schema-First Development Checklist
- Cross-Feature Integration Checklist
## 🚀 Quick Start
### Template Base
This extension pack is designed to work with the `nextjs-new-app` template:
```bash
# Clone the base template
git clone https://github.com/marciobarroso/nextjs-new-app.git my-project
cd my-project
# Install dependencies
pnpm install # or npm install
```
### Extension Pack Usage
```bash
# Use BMAD Method with this extension pack
bmad-fba create-feature "user-management"
# Implement domain feature
bmad-fba develop-domain "order-processing"
# Setup BaseController pattern
bmad-fba implement-controller "Product"
```
## 🏗️ Feature-Based Architecture
This extension pack implements Feature-Based Architecture with Domain-Driven Design:
- **Next.js 15+ App Router** - Modern routing with route groups
- **Feature-Based Organization** - `(features)/` directory structure
- **Domain-Driven Design** - Business domain bounded contexts
- **BaseController Pattern** - Database-agnostic CRUD operations
- **Schema-First Development** - Zod validation with TypeScript
- **Server/Client Components** - Optimized rendering patterns
- **Tailwind CSS 4.x** - Modern utility-first styling
- **Database Agnostic** - Support for any ORM/ODM (Prisma, TypeORM, Mongoose)
- **Shared Infrastructure** - Common utilities and patterns
## 📚 Documentation
### Core Concepts
- [Project Structure](docs/project-structure.md)
- [Component Patterns](docs/component-patterns.md)
- [API Design](docs/api-design.md)
- [State Management](docs/state-management.md)
### Guides
- [Getting Started](docs/getting-started.md)
- [Development Workflow](docs/development-workflow.md)
- [Testing Strategy](docs/testing-strategy.md)
- [Deployment Guide](docs/deployment-guide.md)
## 🛠️ Technology Stack
### Core Technologies (from nextjs-new-app template)
- **Next.js 15.5.3** - React framework with App Router
- **React 19.1.0** - Latest React with modern features
- **TypeScript 5** - Strict type safety
- **Tailwind CSS 4.1.13** - Modern utility-first CSS
- **PostCSS 8.5.6** - CSS processing
- **pnpm** - Efficient package management
### Development Tools (pre-configured)
- **ESLint 9** - Code linting with Next.js integration
- **Prettier 3.6.2** - Code formatting with import sorting
- **Husky 9.1.7** - Git hooks for code quality
- **Jest** - Testing framework (configured, ready for implementation)
### Feature-Based Architecture Additions
- **Zod** - Schema validation and type generation
- **BaseController Pattern** - Database-agnostic CRUD operations
- **Domain-Driven Design** - Business domain organization
- **Schema-First Development** - Type-safe data modeling
## 🎯 Best Practices
### Code Quality
- Strict TypeScript configuration
- Comprehensive ESLint rules
- Automatic code formatting with Prettier
- Component-driven development
- API-first design approach
### Performance
- Server Components by default
- Client Components only when needed
- Image optimization with Next.js Image
- Bundle analysis and optimization
- Core Web Vitals monitoring
### Security
- Input validation with Zod
- CSRF protection
- Secure headers middleware
- Environment variable management
- Authentication best practices
## 📦 Project Structure
```
app/
├── (features)/ # Feature modules (Domain-Driven Design)
│ ├── (user-management)/ # Business domain example
│ │ ├── api/ # Backend API layer
│ │ │ └── users/ # Entity-specific routes
│ │ │ ├── [id]/ # Dynamic routes
│ │ │ ├── controller.ts # BaseController extension
│ │ │ ├── route.ts # Collection operations
│ │ │ └── schema.ts # Zod schemas & types
│ │ ├── components/ # Feature-specific UI
│ │ ├── hooks/ # Custom React hooks
│ │ ├── types/ # TypeScript definitions
│ │ └── users/ # Feature pages
│ └── (order-processing)/ # Another business domain
├── shared/ # Shared infrastructure
│ ├── components/ui/ # Reusable UI components
│ ├── core/ # BaseController & patterns
│ ├── lib/ # Utilities
│ └── types/ # Shared types
├── globals.css # Global styles
├── layout.tsx # Root layout
└── page.tsx # Home page
```
## 🤝 Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Ensure all tests pass
6. Submit a pull request
## 📄 License
This extension pack is part of the BMAD Method project and follows the same MIT license.
## 🆘 Support
- [Documentation](docs/)
- [GitHub Issues](https://github.com/marciobarroso/BMAD-METHOD/issues)
- [Discussions](https://github.com/marciobarroso/BMAD-METHOD/discussions)
## 🏷️ Version
**Current Version:** 1.0.0
**Compatibility:**
- Next.js 14+
- Node.js 18+
- TypeScript 5+
---
Built with ❤️ using the BMAD Method framework.

View File

@ -0,0 +1,26 @@
# <!-- Powered by BMAD™ Core -->
bundle:
name: Next.js Feature-Based Architecture Team
icon: ⚛️
description: Complete Feature-Based Architecture team for Next.js 15+ applications with Domain-Driven Design, TypeScript, Tailwind 4.x, and BaseController patterns
agents:
- domain-architect
- nextjs-architect
- base-controller-specialist
- typescript-specialist
- tailwind-designer
- api-developer
- database-specialist
- auth-specialist
- testing-engineer
- deployment-specialist
- performance-optimizer
- security-auditor
workflows:
- feature-based-project-setup
- domain-feature-development
- base-controller-implementation
- cross-feature-integration
- schema-first-development
- testing-pipeline
- deployment-pipeline

View File

@ -0,0 +1,32 @@
# <!-- Powered by BMAD™ Core -->
name: api-developer
avatar: 🔌
personality: API-focused, systematic, and security-conscious
expertise: REST APIs, GraphQL, database integration, and backend services
background: >-
Backend API specialist with extensive experience in Next.js API routes,
database integration, authentication, and modern backend patterns.
Expert in creating scalable, secure, and well-documented APIs.
directive: >-
You are an API Development Specialist focused on creating robust, scalable,
and secure backend services. Your expertise includes:
- Next.js API Routes and Route Handlers
- RESTful API design and best practices
- GraphQL implementation and optimization
- Database integration (PostgreSQL, MongoDB, etc.)
- Authentication and authorization (JWT, OAuth, NextAuth.js)
- API documentation and OpenAPI specifications
- Error handling and validation
- Caching strategies and performance optimization
- Security best practices and OWASP guidelines
Always prioritize security, performance, and maintainability in API design.
Follow REST principles and modern backend patterns.
conversation_starters:
- "Let's design the API structure for this feature"
- "How should we handle authentication in this API?"
- "Help me optimize this database query"
- "What's the best way to validate and handle this API request?"

View File

@ -0,0 +1,33 @@
# <!-- Powered by BMAD™ Core -->
name: base-controller-specialist
avatar: 🏗️
personality: Systematic, pattern-focused, and database-agnostic minded
expertise: BaseController pattern implementation, schema-first design, and database abstraction
background: >-
Expert in implementing BaseController patterns with database-agnostic design.
Specializes in schema-first development with Zod validation, CRUD operations,
and maintaining consistent API patterns across features in Feature-Based Architecture.
directive: >-
You are a BaseController Pattern Specialist focused on creating consistent,
database-agnostic API controllers. Your expertise includes:
- BaseController abstract class implementation
- Schema-first design with Zod validation
- Database-agnostic patterns (Prisma, TypeORM, Mongoose, etc.)
- CRUD operations with consistent error handling
- Search filtering and pagination patterns
- Feature-specific controller inheritance
- Type-safe database operations
- API response standardization
- Error handling and logging patterns
Always prioritize database abstraction, schema validation, type safety,
and consistent patterns across all feature controllers. Follow the established
BaseController pattern from the project architecture.
conversation_starters:
- "Let's implement a BaseController for this entity"
- "How should we structure the schema validation for this feature?"
- "Help me create a database-agnostic controller pattern"
- "What's the best way to handle search filtering in BaseController?"

View File

@ -0,0 +1,34 @@
# <!-- Powered by BMAD™ Core -->
name: domain-architect
avatar: 🎯
personality: Strategic, domain-focused, and boundary-conscious
expertise: Domain-Driven Design, bounded contexts, and feature organization
background: >-
Domain-Driven Design expert with deep knowledge of business domain modeling,
bounded contexts, and feature organization. Specializes in identifying business
domains, defining feature boundaries, and organizing code around business concepts.
directive: >-
You are a Domain-Driven Design Specialist focused on Feature-Based Architecture
organization and business domain modeling. Your expertise includes:
- Business domain identification and modeling
- Bounded context definition and boundaries
- Feature-Based Architecture organization in (features)/ groups
- Domain entity design and relationships
- Ubiquitous language development
- Cross-domain integration patterns
- Business logic encapsulation
- Domain service patterns
- Event-driven architecture for domain events
- Anti-corruption layers for external integrations
Always prioritize business domain clarity, feature independence, and clean
boundaries between different business contexts. Ensure each feature represents
a cohesive business domain with minimal external dependencies.
conversation_starters:
- "Let's identify the business domains for this application"
- "How should we define bounded contexts for these features?"
- "Help me organize these business requirements into feature modules"
- "What's the best way to model this business entity and its relationships?"

View File

@ -0,0 +1,32 @@
# <!-- Powered by BMAD™ Core -->
name: nextjs-architect
avatar: 🏗️
personality: Systematic, detail-oriented architecture specialist
expertise: Next.js application architecture, project structure, and best practices
background: >-
Expert in Next.js application architecture with deep knowledge of app router,
server components, client components, middleware, and performance optimization.
Specializes in scalable project structures and modern React patterns.
directive: >-
You are a Next.js Feature-Based Architecture Specialist focused on Domain-Driven Design
and self-contained feature modules. Your expertise includes:
- Feature-Based Architecture with (features)/ route groups
- Domain-Driven Design principles and bounded contexts
- Next.js 15+ App Router with Server/Client component patterns
- Self-contained feature structure (api/, components/, hooks/, types/)
- BaseController pattern with database-agnostic design
- Schema-first development with Zod validation
- Shared infrastructure patterns in shared/ directory
- Cross-feature integration and dependency management
- TypeScript strict mode and type safety end-to-end
Always recommend Feature-Based organization, minimize cross-feature dependencies,
and ensure each feature represents a clear business domain with consistent patterns.
conversation_starters:
- "Let's design a Feature-Based Architecture for this business domain"
- "How should we structure this feature following Domain-Driven Design?"
- "What's the best way to organize this bounded context in (features)/"
- "Help me implement the BaseController pattern for this entity"

View File

@ -0,0 +1,32 @@
# <!-- Powered by BMAD™ Core -->
name: tailwind-designer
avatar: 🎨
personality: Creative, design-focused, and utility-first minded
expertise: Tailwind CSS, responsive design, and component styling
background: >-
Tailwind CSS expert with deep knowledge of utility-first CSS methodology,
responsive design patterns, and modern UI/UX principles. Specializes in
creating beautiful, consistent, and accessible user interfaces.
directive: >-
You are a Tailwind CSS Design Specialist focused on creating beautiful,
responsive, and accessible user interfaces. Your expertise includes:
- Tailwind CSS configuration and customization
- Utility-first CSS methodology and best practices
- Responsive design patterns and breakpoints
- Component composition and reusability
- Color schemes and design tokens
- Accessibility and WCAG compliance
- Performance optimization for CSS
- Integration with Next.js and React components
Always prioritize clean, maintainable CSS with excellent user experience,
accessibility, and performance. Follow modern design principles and
Tailwind best practices.
conversation_starters:
- "Let's design a responsive component with Tailwind CSS"
- "How can we customize the Tailwind configuration for this project?"
- "Help me create an accessible form design"
- "What's the best approach for this layout in Tailwind?"

View File

@ -0,0 +1,32 @@
# <!-- Powered by BMAD™ Core -->
name: typescript-specialist
avatar: 📘
personality: Precise, type-safety focused, and methodical
expertise: TypeScript configuration, type definitions, and advanced patterns
background: >-
TypeScript expert with extensive knowledge of advanced type systems,
generics, utility types, and integration with React and Next.js.
Specializes in creating type-safe applications with excellent DX.
directive: >-
You are a TypeScript Specialist dedicated to creating type-safe, maintainable code.
Your expertise includes:
- Advanced TypeScript configuration and compiler options
- Complex type definitions and interfaces
- Generic types and utility types
- Type guards and type assertions
- Integration with React, Next.js, and popular libraries
- Error handling and type-safe API responses
- Module declaration and ambient types
- Performance optimization of TypeScript builds
Always prioritize type safety while maintaining code readability and
developer productivity. Recommend strict TypeScript configurations and
modern typing patterns.
conversation_starters:
- "Help me set up TypeScript configuration for this Next.js project"
- "How can we improve type safety in this component?"
- "What's the best way to type this API response?"
- "Let's create type definitions for this data structure"

View File

@ -0,0 +1,150 @@
# BaseController Implementation Checklist
## Abstract Class Setup
- [ ] BaseController abstract class created in `shared/core/`
- [ ] Generic type parameter `<T>` properly defined
- [ ] Database client abstraction implemented
- [ ] Zod schema integration configured
- [ ] Constructor properly initializes dependencies
## CRUD Operations Implementation
- [ ] `getAll` method implemented with pagination
- [ ] `getById` method implemented with proper error handling
- [ ] `create` method implemented with validation
- [ ] `update` method implemented with partial updates
- [ ] `delete` method implemented with proper checks
- [ ] All methods return proper HTTP responses
## Search & Filtering
- [ ] Abstract `buildSearchFilter` method defined
- [ ] Search parameter extraction implemented
- [ ] Database-agnostic filter pattern established
- [ ] Query string parsing handled properly
- [ ] Default search behavior defined
- [ ] Search performance considered
## Validation & Schema Integration
- [ ] Zod schema validation on all inputs
- [ ] Create schema validation implemented
- [ ] Update schema validation implemented
- [ ] Search parameter validation implemented
- [ ] Custom validation rules supported
- [ ] Validation error messages are user-friendly
## Error Handling
- [ ] Consistent error response format
- [ ] HTTP status codes properly used
- [ ] Validation errors properly formatted
- [ ] Database errors caught and handled
- [ ] Logging implemented for debugging
- [ ] Error messages don't expose sensitive data
## Database Abstraction
- [ ] Database client interface defined
- [ ] Connection management abstracted
- [ ] Database-specific operations isolated
- [ ] ORM/ODM integration patterns established
- [ ] Transaction support considered
- [ ] Connection pooling handled
## Response Formatting
- [ ] Consistent API response structure
- [ ] Success responses properly formatted
- [ ] Error responses standardized
- [ ] Pagination metadata included
- [ ] Response types properly typed
- [ ] Content-Type headers set correctly
## Feature Controller Extension
- [ ] Feature controller extends BaseController
- [ ] Entity-specific `buildSearchFilter` implemented
- [ ] Custom business logic methods added
- [ ] Database client properly injected
- [ ] Schema properly passed to parent
- [ ] Controller singleton pattern implemented (if needed)
## Type Safety
- [ ] Generic types properly constrained
- [ ] Entity model interfaces defined
- [ ] API response types defined
- [ ] Database model types defined
- [ ] Method signatures properly typed
- [ ] Return types explicitly defined
## Performance Optimization
- [ ] Database queries optimized
- [ ] Proper indexing strategy planned
- [ ] Pagination limits enforced
- [ ] Query result caching considered
- [ ] N+1 query problems avoided
- [ ] Database connection reuse implemented
## Testing
- [ ] Unit tests for BaseController methods
- [ ] Mock database client created
- [ ] Test data fixtures defined
- [ ] Edge cases covered in tests
- [ ] Error scenarios tested
- [ ] Performance tests implemented
## Documentation
- [ ] BaseController usage documented
- [ ] Extension patterns documented
- [ ] Database integration examples provided
- [ ] API response formats documented
- [ ] Error handling patterns documented
- [ ] Performance considerations documented
## Logging & Monitoring
- [ ] Request/response logging implemented
- [ ] Error logging with stack traces
- [ ] Performance metrics captured
- [ ] Database operation monitoring
- [ ] Health check endpoints created
- [ ] Audit trail for data changes
## Security Considerations
- [ ] Input sanitization implemented
- [ ] SQL injection prevention (for SQL databases)
- [ ] NoSQL injection prevention (for NoSQL databases)
- [ ] Access control integration points
- [ ] Rate limiting consideration
- [ ] Sensitive data handling
## Database-Specific Implementations
### For SQL Databases (Prisma/TypeORM)
- [ ] Proper WHERE clause generation
- [ ] JOIN operations handled
- [ ] Transaction support implemented
- [ ] Migration compatibility ensured
- [ ] Relationship loading optimized
### For MongoDB (Mongoose)
- [ ] Query object generation
- [ ] Aggregation pipeline support
- [ ] Index utilization optimized
- [ ] Document validation aligned
- [ ] Connection string security
### For Serverless Databases
- [ ] Connection pooling optimized
- [ ] Cold start mitigation
- [ ] Query timeout handling
- [ ] Retry logic implemented
- [ ] Cost optimization considered
## Integration Points
- [ ] Authentication middleware integration
- [ ] Authorization checks implemented
- [ ] Audit logging integrated
- [ ] Event system integration (if applicable)
- [ ] Cache layer integration
- [ ] External API integration patterns
## Production Readiness
- [ ] Environment variable configuration
- [ ] Production database connection
- [ ] Error monitoring integration
- [ ] Performance monitoring setup
- [ ] Load testing completed
- [ ] Backup and recovery procedures

View File

@ -0,0 +1,72 @@
# React Component Development Checklist
## Pre-Development
- [ ] Component purpose and requirements clearly defined
- [ ] Component interface (props) designed
- [ ] Accessibility requirements identified
- [ ] Design mockup/wireframe available
## Development
- [ ] TypeScript interface defined for all props
- [ ] Component follows naming conventions (PascalCase)
- [ ] Proper file structure and organization
- [ ] Default props defined where appropriate
- [ ] Error boundaries implemented for critical components
## Styling
- [ ] Tailwind CSS classes used consistently
- [ ] Responsive design implemented
- [ ] Dark mode support (if applicable)
- [ ] Custom CSS kept to minimum
- [ ] CSS class conflicts avoided
## Accessibility (a11y)
- [ ] Semantic HTML elements used
- [ ] ARIA labels added where needed
- [ ] Keyboard navigation supported
- [ ] Focus management implemented
- [ ] Screen reader friendly
- [ ] Color contrast meets WCAG guidelines
## Performance
- [ ] Unnecessary re-renders avoided
- [ ] React.memo used where appropriate
- [ ] Heavy computations memoized with useMemo
- [ ] Event handlers memoized with useCallback
- [ ] Large lists virtualized (if applicable)
## Testing
- [ ] Unit tests written and passing
- [ ] Component renders without crashing
- [ ] Props validation tested
- [ ] User interactions tested
- [ ] Edge cases covered
- [ ] Accessibility testing performed
## Code Quality
- [ ] TypeScript types are strict and accurate
- [ ] ESLint rules pass
- [ ] Prettier formatting applied
- [ ] No console errors or warnings
- [ ] Code is self-documenting
- [ ] Comments added for complex logic
## Integration
- [ ] Component integrates well with parent components
- [ ] State management working correctly
- [ ] API calls handled properly (if applicable)
- [ ] Error states handled gracefully
- [ ] Loading states implemented
## Documentation
- [ ] Component documented with JSDoc comments
- [ ] Props interface documented
- [ ] Usage examples provided
- [ ] Storybook story created (if using Storybook)
## Review
- [ ] Code review completed
- [ ] Design review completed
- [ ] Performance review completed
- [ ] Accessibility review completed
- [ ] Security review completed (if handling sensitive data)

View File

@ -0,0 +1,149 @@
# Feature-Based Architecture Development Checklist
## Domain Analysis & Planning
- [ ] Business domain clearly identified and defined
- [ ] Bounded context boundaries established
- [ ] Domain entities and relationships mapped
- [ ] Feature independence validated (minimal cross-feature dependencies)
- [ ] Ubiquitous language defined for the domain
- [ ] Business requirements thoroughly documented
## Project Structure
- [ ] Feature organized in `(features)/({feature-name})/` route group
- [ ] API layer structured in `api/{entity-name}/` directory
- [ ] Components organized in `components/` directory within feature
- [ ] Custom hooks placed in `hooks/` directory within feature
- [ ] TypeScript types defined in `types/` directory within feature
- [ ] Feature pages organized in appropriate subdirectories
## Schema-First Development
- [ ] Zod schema defined for entity validation
- [ ] TypeScript interfaces derived from Zod schemas
- [ ] Create, Update, and Search schemas properly defined
- [ ] Database model interface created (database-agnostic)
- [ ] API response types properly typed
- [ ] Schema validation covers all business rules
## BaseController Implementation
- [ ] Entity controller extends BaseController abstract class
- [ ] Database-agnostic design maintained
- [ ] `buildSearchFilter` method implemented for entity-specific search
- [ ] CRUD operations properly inherited and customized if needed
- [ ] Error handling follows established patterns
- [ ] Controller uses Zod schema for validation
## API Routes Development
- [ ] Collection routes (`/api/{entity}`) implemented
- [ ] Individual entity routes (`/api/{entity}/[id]`) implemented
- [ ] HTTP methods properly implemented (GET, POST, PUT, DELETE)
- [ ] Error handling with proper HTTP status codes
- [ ] Request/response validation using schemas
- [ ] Database connection properly managed
## Custom Hooks Implementation
- [ ] Data fetching hooks follow naming convention (`use{Entities}`)
- [ ] Mutation hooks follow naming convention (`use{Entity}Mutations`)
- [ ] Single entity hooks follow naming convention (`use{Entity}`)
- [ ] Hooks properly handle loading states
- [ ] Error states handled appropriately
- [ ] Pagination implemented for list operations
- [ ] Search functionality integrated
## React Components
- [ ] Components follow PascalCase naming convention
- [ ] Form components implemented (`{Entity}Form`)
- [ ] List components implemented (`{Entity}List`)
- [ ] Card/detail components implemented (`{Entity}Card`)
- [ ] Search components implemented (`{Entity}Search`)
- [ ] Components are properly typed with TypeScript
- [ ] Tailwind CSS used for styling
- [ ] Components follow accessibility guidelines
## Next.js Pages
- [ ] Feature index page implemented (`page.tsx`)
- [ ] Entity detail pages implemented (`[id]/page.tsx`)
- [ ] Create new entity page implemented (`new/page.tsx`)
- [ ] Edit entity page implemented (`[id]/edit/page.tsx`)
- [ ] Server Components used by default
- [ ] Client Components only used when necessary
- [ ] Proper layouts and navigation implemented
## Type Safety
- [ ] Strict TypeScript configuration enforced
- [ ] No `any` types used
- [ ] End-to-end type safety from database to UI
- [ ] Proper type imports and exports
- [ ] Interface segregation properly implemented
- [ ] Generic types used appropriately
## Code Quality
- [ ] ESLint rules passing without warnings
- [ ] Prettier formatting applied consistently
- [ ] No console statements in production code
- [ ] Import statements properly organized
- [ ] `@/` alias used for internal imports
- [ ] Code follows established conventions
## Testing
- [ ] Unit tests for controller logic
- [ ] API route integration tests
- [ ] React component tests
- [ ] Custom hooks tests
- [ ] Edge cases covered in tests
- [ ] Test data and mocks properly implemented
## Database Integration
- [ ] Database connection abstracted properly
- [ ] ORM/ODM integration follows patterns
- [ ] Migration strategy considered
- [ ] Database queries optimized
- [ ] Indexes planned for search operations
- [ ] Data relationships properly modeled
## Performance Considerations
- [ ] Server Components used for data fetching
- [ ] Client Components minimized
- [ ] Database queries optimized
- [ ] Pagination implemented for large datasets
- [ ] Caching strategy considered
- [ ] Bundle size impact assessed
## Security
- [ ] Input validation on all API endpoints
- [ ] Authentication/authorization considered
- [ ] SQL injection prevention (if using SQL database)
- [ ] XSS prevention in components
- [ ] CSRF protection implemented
- [ ] Error messages don't leak sensitive information
## Documentation
- [ ] Feature purpose and scope documented
- [ ] API endpoints documented
- [ ] Component usage examples provided
- [ ] Business logic explained
- [ ] Integration points documented
- [ ] Database schema documented
## Integration & Dependencies
- [ ] Shared infrastructure properly utilized
- [ ] Cross-feature dependencies minimized
- [ ] Integration points well-defined
- [ ] Shared types and utilities used appropriately
- [ ] Feature can be developed independently
- [ ] Feature can be tested in isolation
## Deployment Readiness
- [ ] Environment variables properly configured
- [ ] Production build successful
- [ ] Database migrations ready (if needed)
- [ ] Performance benchmarks acceptable
- [ ] Error monitoring configured
- [ ] Health checks implemented
## Review & Quality Assurance
- [ ] Code review completed
- [ ] Architecture review completed
- [ ] Business logic verified
- [ ] User experience tested
- [ ] Accessibility tested
- [ ] Cross-browser compatibility verified

View File

@ -0,0 +1,12 @@
# <!-- Powered by BMAD™ Core -->
name: bmad-nextjs-fullstack
version: 1.0.0
short-title: Next.js Feature-Based Architecture Studio
description: >-
Comprehensive AI-powered Next.js 15+ fullstack development framework using Feature-Based
Architecture and Domain-Driven Design. Includes specialized agents for TypeScript,
Tailwind CSS 4.x, schema-first development with Zod, BaseController patterns,
database-agnostic design, and enterprise-grade development workflows following
modern Next.js App Router conventions with Server/Client component patterns.
author: marciobarroso
slashPrefix: bmad-fba

View File

@ -0,0 +1,181 @@
# Create API Endpoint
## Task Overview
Create a new API endpoint in Next.js with proper TypeScript typing, validation, and error handling.
## Prerequisites
- Next.js project with App Router
- TypeScript configured
- Understanding of HTTP methods and status codes
## Steps
### 1. Create API Route File
Create `src/app/api/{endpoint}/route.ts`:
```typescript
import { NextRequest, NextResponse } from 'next/server'
// Define request/response types
interface RequestBody {
// Define your request body structure
}
interface ResponseData {
// Define your response structure
}
export async function GET(request: NextRequest) {
try {
// Handle GET request logic
const data: ResponseData = {
// Your response data
}
return NextResponse.json(data, { status: 200 })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
export async function POST(request: NextRequest) {
try {
const body: RequestBody = await request.json()
// Validate request body
if (!body) {
return NextResponse.json(
{ error: 'Request body is required' },
{ status: 400 }
)
}
// Handle POST request logic
const data: ResponseData = {
// Your response data
}
return NextResponse.json(data, { status: 201 })
} catch (error) {
console.error('API Error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
```
### 2. Add Request Validation (Optional)
Install and use Zod for validation:
```bash
npm install zod
```
```typescript
import { z } from 'zod'
const requestSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
})
export async function POST(request: NextRequest) {
try {
const body = await request.json()
const validatedData = requestSchema.parse(body)
// Use validatedData safely
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: 'Invalid request data', details: error.errors },
{ status: 400 }
)
}
// Handle other errors
}
}
```
### 3. Create API Client Helper
Create `src/lib/api-client.ts`:
```typescript
class ApiError extends Error {
constructor(public status: number, message: string) {
super(message)
this.name = 'ApiError'
}
}
export async function apiCall<T>(
url: string,
options?: RequestInit
): Promise<T> {
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
...options?.headers,
},
...options,
})
if (!response.ok) {
throw new ApiError(response.status, `HTTP error! status: ${response.status}`)
}
return response.json()
}
```
### 4. Use in Components
```typescript
'use client'
import { useState } from 'react'
import { apiCall } from '@/lib/api-client'
export function ExampleComponent() {
const [loading, setLoading] = useState(false)
const [data, setData] = useState(null)
const handleSubmit = async () => {
setLoading(true)
try {
const result = await apiCall('/api/example', {
method: 'POST',
body: JSON.stringify({ /* your data */ }),
})
setData(result)
} catch (error) {
console.error('Error:', error)
} finally {
setLoading(false)
}
}
return (
// Your component JSX
)
}
```
## Validation Checklist
- [ ] API route file created in correct location
- [ ] Proper TypeScript types defined
- [ ] Error handling implemented
- [ ] Request validation added (if needed)
- [ ] API tested with different HTTP methods
- [ ] Client-side integration working
- [ ] Error cases handled gracefully
## Best Practices
- Use proper HTTP status codes
- Implement consistent error response format
- Add request validation for security
- Log errors for debugging
- Consider rate limiting for production
- Document API endpoints

View File

@ -0,0 +1,307 @@
# Setup Project from nextjs-new-app Template
## Task Overview
Initialize a new Feature-Based Architecture project using the pre-configured `nextjs-new-app` template with Next.js 15+, TypeScript, Tailwind CSS 4.x, and development tooling.
## Prerequisites
- Node.js 20.10.0+ installed
- pnpm (recommended) or npm package manager
- Git for version control
- Access to https://github.com/marciobarroso/nextjs-new-app
## Steps
### 1. Clone Template Repository
```bash
# Clone the nextjs-new-app template
git clone https://github.com/marciobarroso/nextjs-new-app.git {project_name}
cd {project_name}
# Remove original git history and initialize new repository
rm -rf .git
git init
git add .
git commit -m "Initial commit from nextjs-new-app template"
```
### 2. Install Dependencies
```bash
# Install using pnpm (recommended by template)
pnpm install
# Alternative: using npm
# npm install
```
### 3. Configure Project Details
Update `package.json`:
```json
{
"name": "{project_name}",
"version": "1.0.0",
"description": "{project_description}",
"author": "{author_name}"
}
```
### 4. Set Up Feature-Based Architecture Structure
```bash
# Create the Feature-Based Architecture directories
mkdir -p app/\(features\)
mkdir -p app/shared/core
mkdir -p app/shared/types
mkdir -p app/shared/lib
# The template already provides:
# - app/shared/components/
# - app/shared/hooks/
# - app/shared/lib/
# - app/shared/locales/
```
### 5. Implement BaseController Foundation
Create `app/shared/core/base-controller.ts`:
```typescript
import { z } from 'zod'
import { NextRequest, NextResponse } from 'next/server'
export abstract class BaseController<T> {
protected dbClient: any
protected schema?: z.ZodSchema
constructor(dbClient: any, schema?: z.ZodSchema) {
this.dbClient = dbClient
this.schema = schema
}
// Standard CRUD operations
async getAll(request: NextRequest): Promise<NextResponse> {
try {
const { searchParams } = new URL(request.url)
const query = searchParams.get('query')
const page = parseInt(searchParams.get('page') || '1')
const limit = parseInt(searchParams.get('limit') || '20')
const filter = this.buildSearchFilter(query)
// Implement database-specific query here
return NextResponse.json({
data: [],
pagination: { page, limit, total: 0, totalPages: 0 },
success: true
})
} catch (error) {
return NextResponse.json(
{ error: 'Failed to fetch records', success: false },
{ status: 500 }
)
}
}
async getById(request: NextRequest, { params }: { params: { id: string } }): Promise<NextResponse> {
try {
// Implement database-specific findById here
return NextResponse.json({ data: null, success: true })
} catch (error) {
return NextResponse.json(
{ error: 'Failed to fetch record', success: false },
{ status: 500 }
)
}
}
async create(request: NextRequest): Promise<NextResponse> {
try {
const body = await request.json()
if (this.schema) {
const validatedData = this.schema.parse(body)
// Implement database-specific create here
}
return NextResponse.json({ data: null, success: true }, { status: 201 })
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: 'Validation failed', details: error.errors, success: false },
{ status: 400 }
)
}
return NextResponse.json(
{ error: 'Failed to create record', success: false },
{ status: 500 }
)
}
}
async update(request: NextRequest, { params }: { params: { id: string } }): Promise<NextResponse> {
try {
const body = await request.json()
if (this.schema) {
const validatedData = this.schema.partial().parse(body)
// Implement database-specific update here
}
return NextResponse.json({ data: null, success: true })
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{ error: 'Validation failed', details: error.errors, success: false },
{ status: 400 }
)
}
return NextResponse.json(
{ error: 'Failed to update record', success: false },
{ status: 500 }
)
}
}
async delete(request: NextRequest, { params }: { params: { id: string } }): Promise<NextResponse> {
try {
// Implement database-specific delete here
return NextResponse.json({ success: true, message: 'Record deleted successfully' })
} catch (error) {
return NextResponse.json(
{ error: 'Failed to delete record', success: false },
{ status: 500 }
)
}
}
// Abstract method for search filtering
protected abstract buildSearchFilter(query: string | null): Record<string, any>
}
```
### 6. Add Zod for Schema Validation
```bash
# Install Zod for schema validation
pnpm add zod
# or npm install zod
```
### 7. Configure Environment Variables
Create `.env.local`:
```env
# Database Configuration (customize based on your choice)
DATABASE_URL="your-database-url"
# Next.js Configuration
NEXT_PUBLIC_APP_NAME="{project_name}"
NEXT_PUBLIC_APP_VERSION="1.0.0"
# Add other environment variables as needed
```
### 8. Update TypeScript Configuration
The template already provides optimal TypeScript configuration, but you can extend `tsconfig.json` if needed:
```json
{
"compilerOptions": {
// Template already includes optimal settings
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
}
}
}
```
### 9. Test the Setup
```bash
# Run development server
pnpm dev
# or npm run dev
# Run linting
pnpm lint
# or npm run lint
# Run formatting
pnpm format
# or npm run format
# Run build test
pnpm build
# or npm run build
```
### 10. Initialize Git Repository
```bash
# Add remote repository (replace with your repository URL)
git remote add origin https://github.com/yourusername/{project_name}.git
# Make initial commit with template
git add .
git commit -m "feat: initialize project from nextjs-new-app template
- Set up Next.js 15+ with TypeScript and Tailwind CSS 4.x
- Implemented Feature-Based Architecture structure
- Added BaseController foundation for database-agnostic patterns
- Configured development tooling (ESLint, Prettier, Husky)
Template: https://github.com/marciobarroso/nextjs-new-app"
# Push to remote repository
git push -u origin main
```
## Validation Checklist
- [ ] Template repository successfully cloned
- [ ] Dependencies installed without errors
- [ ] Development server runs on http://localhost:3000
- [ ] ESLint and Prettier configured and working
- [ ] TypeScript compilation successful
- [ ] Feature-Based Architecture directories created
- [ ] BaseController foundation implemented
- [ ] Zod schema validation set up
- [ ] Environment variables configured
- [ ] Git repository initialized and connected
## Template Features Already Configured
- ✅ Next.js 15.5.3 with App Router
- ✅ React 19.1.0 with latest features
- ✅ TypeScript 5 with strict configuration
- ✅ Tailwind CSS 4.1.13 with PostCSS
- ✅ ESLint 9 with Next.js integration
- ✅ Prettier 3.6.2 with import sorting
- ✅ Husky 9.1.7 for git hooks
- ✅ Jest testing framework (configured)
- ✅ Shared components structure
- ✅ Basic layouts and providers
- ✅ Internationalization setup
## Next Steps After Setup
1. Plan your first business domain feature
2. Implement your chosen database integration (Prisma, TypeORM, Mongoose, etc.)
3. Create your first feature following Feature-Based Architecture
4. Set up authentication system
5. Configure your preferred database
6. Implement testing for your features
7. Set up CI/CD pipeline for deployment
## Database Integration Examples
### For Prisma (PostgreSQL)
```bash
pnpm add prisma @prisma/client
pnpm add -D prisma
npx prisma init
```
### For TypeORM (SQL databases)
```bash
pnpm add typeorm reflect-metadata
pnpm add pg # for PostgreSQL
# or pnpm add mysql2 # for MySQL
```
### For Mongoose (MongoDB)
```bash
pnpm add mongoose
pnpm add -D @types/mongoose
```
The `nextjs-new-app` template provides an excellent foundation for Feature-Based Architecture, and this setup process will get you ready to build scalable, maintainable Next.js applications following Domain-Driven Design principles.

View File

@ -0,0 +1,86 @@
# Setup Next.js Project
## Task Overview
Initialize a new Next.js project with TypeScript, Tailwind CSS, ESLint, and Prettier configuration.
## Prerequisites
- Node.js 18+ installed
- npm or yarn package manager
- Git for version control
## Steps
### 1. Create Next.js Project
```bash
npx create-next-app@latest {project_name} --typescript --tailwind --eslint --app --src-dir --import-alias "@/*"
cd {project_name}
```
### 2. Install Additional Dependencies
```bash
npm install --save-dev prettier prettier-plugin-tailwindcss @types/node
npm install lucide-react clsx tailwind-merge
```
### 3. Configure Prettier
Create `.prettierrc.json`:
```json
{
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 80,
"plugins": ["prettier-plugin-tailwindcss"]
}
```
### 4. Update ESLint Configuration
Extend `.eslintrc.json`:
```json
{
"extends": ["next/core-web-vitals", "prettier"],
"rules": {
"prefer-const": "error",
"no-unused-vars": "error"
}
}
```
### 5. Configure TypeScript
Update `tsconfig.json` for strict mode:
```json
{
"compilerOptions": {
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"exactOptionalPropertyTypes": true
}
}
```
### 6. Set up Scripts
Add to `package.json`:
```json
{
"scripts": {
"format": "prettier --write .",
"format:check": "prettier --check .",
"lint:fix": "eslint . --fix"
}
}
```
## Validation Checklist
- [ ] Next.js project created with TypeScript
- [ ] Tailwind CSS configured and working
- [ ] ESLint and Prettier configured
- [ ] All dependencies installed
- [ ] Scripts working correctly
- [ ] Project builds without errors
## Next Steps
- Set up folder structure
- Configure environment variables
- Create initial components

View File

@ -0,0 +1,153 @@
# <!-- Powered by BMAD™ Core -->
name: API Route Template
description: Template for creating Next.js API routes with TypeScript
version: 1.0.0
template: |
import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
// Request validation schema
const {schemaName}Schema = z.object({
// Define your request body schema here
// Example: name: z.string().min(1)
})
// Response type
interface {ResponseType} {
// Define your response structure
}
export async function GET(request: NextRequest) {
try {
// Extract query parameters if needed
const { searchParams } = new URL(request.url)
const param = searchParams.get('param')
// Your GET logic here
const data: {ResponseType} = {
// Your response data
}
return NextResponse.json(data, { status: 200 })
} catch (error) {
console.error('[{EndpointName}] GET Error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
export async function POST(request: NextRequest) {
try {
const body = await request.json()
// Validate request body
const validatedData = {schemaName}Schema.parse(body)
// Your POST logic here
const result: {ResponseType} = {
// Your response data
}
return NextResponse.json(result, { status: 201 })
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{
error: 'Invalid request data',
details: error.errors
},
{ status: 400 }
)
}
console.error('[{EndpointName}] POST Error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
export async function PUT(request: NextRequest) {
try {
const body = await request.json()
const validatedData = {schemaName}Schema.parse(body)
// Your PUT logic here
const result: {ResponseType} = {
// Your response data
}
return NextResponse.json(result, { status: 200 })
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json(
{
error: 'Invalid request data',
details: error.errors
},
{ status: 400 }
)
}
console.error('[{EndpointName}] PUT Error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
export async function DELETE(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const id = searchParams.get('id')
if (!id) {
return NextResponse.json(
{ error: 'ID parameter is required' },
{ status: 400 }
)
}
// Your DELETE logic here
return NextResponse.json(
{ message: 'Successfully deleted' },
{ status: 200 }
)
} catch (error) {
console.error('[{EndpointName}] DELETE Error:', error)
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
)
}
}
variables:
- name: EndpointName
type: string
description: The name of the API endpoint (PascalCase)
required: true
- name: schemaName
type: string
description: The name for the validation schema (camelCase)
required: true
- name: ResponseType
type: string
description: The TypeScript type name for responses (PascalCase)
required: true
instructions: |
1. Replace {EndpointName} with your endpoint name
2. Replace {schemaName} with your schema variable name
3. Replace {ResponseType} with your response type name
4. Define your Zod validation schema
5. Implement the business logic for each HTTP method
6. Remove unused HTTP methods
7. Add proper error handling and logging
8. Consider authentication and authorization if needed

View File

@ -0,0 +1,93 @@
# <!-- Powered by BMAD™ Core -->
name: BaseController Extension Template
description: Template for extending BaseController in Feature-Based Architecture
version: 1.0.0
template: |
// (features)/({featureName})/api/{entityName}/controller.ts
import { BaseController } from '@/shared/core/base-controller'
import { {EntityName}Schema, {EntityName}Model } from './schema'
import { NextRequest, NextResponse } from 'next/server'
export class {EntityName}Controller extends BaseController<{EntityName}Model> {
constructor(dbClient: any) {
super(dbClient, {EntityName}Schema)
}
/**
* Build search filter for {EntityName} entities
* Implement database-specific search logic here
*/
protected buildSearchFilter(query: string | null): Record<string, any> {
if (!query) return {}
// Example implementations for different databases:
// For Prisma (SQL):
// return {
// OR: [
// { name: { contains: query, mode: 'insensitive' } },
// { description: { contains: query, mode: 'insensitive' } }
// ]
// }
// For Mongoose (MongoDB):
// return {
// $or: [
// { name: new RegExp(query, 'i') },
// { description: new RegExp(query, 'i') }
// ]
// }
// Database-agnostic placeholder:
return { search: query }
}
/**
* Custom business logic methods for {EntityName}
* Add domain-specific operations here
*/
// Example: Custom validation before create
protected async beforeCreate(data: Partial<{EntityName}Model>): Promise<void> {
// Add custom validation logic
}
// Example: Custom processing after create
protected async afterCreate(entity: {EntityName}Model): Promise<void> {
// Add post-creation logic (events, notifications, etc.)
}
}
// Export singleton instance (optional pattern)
let controllerInstance: {EntityName}Controller | null = null
export function get{EntityName}Controller(dbClient: any): {EntityName}Controller {
if (!controllerInstance) {
controllerInstance = new {EntityName}Controller(dbClient)
}
return controllerInstance
}
variables:
- name: featureName
type: string
description: The feature name in kebab-case (e.g., user-management)
required: true
- name: entityName
type: string
description: The entity name in kebab-case (e.g., user, product)
required: true
- name: EntityName
type: string
description: The entity name in PascalCase (e.g., User, Product)
required: true
instructions: |
1. Replace {featureName} with your feature name (kebab-case)
2. Replace {entityName} with your entity name (kebab-case)
3. Replace {EntityName} with your entity name (PascalCase)
4. Implement the buildSearchFilter method based on your database
5. Add custom business logic methods as needed
6. Ensure the schema.ts file exists with {EntityName}Schema and {EntityName}Model
7. Consider adding custom validation and processing hooks

View File

@ -0,0 +1,41 @@
# <!-- Powered by BMAD™ Core -->
name: React Component Template
description: Template for creating TypeScript React components with Tailwind CSS
version: 1.0.0
template: |
import { cn } from '@/lib/utils'
interface {ComponentName}Props {
className?: string
children?: React.ReactNode
// Add your props here
}
export function {ComponentName}({
className,
children,
...props
}: {ComponentName}Props) {
return (
<div className={cn("", className)} {...props}>
{children}
</div>
)
}
{ComponentName}.displayName = "{ComponentName}"
variables:
- name: ComponentName
type: string
description: The name of the React component (PascalCase)
required: true
instructions: |
1. Replace {ComponentName} with your component name in PascalCase
2. Add specific props to the interface
3. Implement component logic and styling
4. Add proper TypeScript types
5. Use Tailwind classes for styling
6. Consider accessibility (a11y) requirements

View File

@ -0,0 +1,174 @@
# <!-- Powered by BMAD™ Core -->
name: Feature Structure Template
description: Template for creating complete Feature-Based Architecture structure
version: 1.0.0
template: |
# Feature Structure for ({featureName})
## Directory Structure
```
app/(features)/({featureName})/
├── api/ # Backend API layer
│ └── {entityName}/
│ ├── [id]/ # Dynamic routes for specific entities
│ │ ├── route.ts # Individual entity operations (GET, PUT, DELETE)
│ │ └── [action]/ # Specific actions (optional)
│ │ └── route.ts
│ ├── controller.ts # Business logic controller extending BaseController
│ ├── route.ts # Collection operations (GET, POST)
│ └── schema.ts # Zod validation & TypeScript types
├── components/ # Feature-specific UI components
│ ├── {entityName}-form.tsx # Create/edit forms
│ ├── {entityName}-list.tsx # List/table components
│ ├── {entityName}-card.tsx # Individual item display
│ └── {entityName}-search.tsx # Search/filter components
├── hooks/ # Custom React hooks
│ ├── use{EntityName}.ts # Single entity operations
│ ├── use{EntityName}Mutations.ts # Create/update/delete mutations
│ └── use{Entities}.ts # List/search operations
├── types/ # TypeScript type definitions
│ └── {entityName}.types.ts # Feature-specific types (extends base schema types)
└── {featurePages}/ # Next.js pages
├── [id]/ # Dynamic pages for specific entities
│ ├── page.tsx # Entity detail view
│ └── edit/ # Edit entity page
│ └── page.tsx
├── new/ # Create new entity pages
│ └── page.tsx
└── page.tsx # Feature listing/index page
```
## File Templates
### API Route (route.ts)
```typescript
import { NextRequest, NextResponse } from 'next/server'
import { get{EntityName}Controller } from './controller'
import { dbConnect } from '@/shared/lib/db-connection'
import { withErrorHandler } from '@/shared/lib/error-handler'
// GET /api/{entityName} - List entities
export const GET = withErrorHandler(async (request: NextRequest) => {
const dbClient = await dbConnect()
const controller = get{EntityName}Controller(dbClient)
return await controller.getAll(request)
})
// POST /api/{entityName} - Create entity
export const POST = withErrorHandler(async (request: NextRequest) => {
const dbClient = await dbConnect()
const controller = get{EntityName}Controller(dbClient)
return await controller.create(request)
})
```
### Feature Hook (use{Entities}.ts)
```typescript
import { useState, useCallback } from 'react'
import { {EntityName}DatabaseModel, {EntityName}Search } from '../api/{entityName}/schema'
import { useAppContext } from '@/shared/contexts/app-context'
export const use{Entities} = () => {
const [entities, setEntities] = useState<{EntityName}DatabaseModel[]>([])
const [pagination, setPagination] = useState({
page: 1,
limit: 20,
total: 0,
totalPages: 0
})
const { isLoading, setIsLoading } = useAppContext()
const fetchEntities = useCallback(async (params: {EntityName}Search = {}) => {
setIsLoading(true)
try {
const searchParams = new URLSearchParams(params as any)
const response = await fetch(`/api/{entityName}?${{searchParams}}`)
const result = await response.json()
if (result.success) {
setEntities(result.data)
setPagination(result.pagination)
}
} catch (error) {
console.error('Error fetching {entities}:', error)
} finally {
setIsLoading(false)
}
}, [setIsLoading])
return {
entities,
pagination,
isLoading,
fetchEntities
}
}
```
### Feature Component ({EntityName}List.tsx)
```typescript
'use client'
import { use{Entities} } from '../hooks/use{Entities}'
import { {EntityName}Card } from './{entityName}-card'
import { useEffect } from 'react'
export function {EntityName}List() {
const { entities, isLoading, fetchEntities } = use{Entities}()
useEffect(() => {
fetchEntities()
}, [fetchEntities])
if (isLoading) {
return <div className="flex justify-center p-8">Loading...</div>
}
return (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{entities.map((entity) => (
<{EntityName}Card key={entity.id} entity={entity} />
))}
</div>
)
}
```
variables:
- name: featureName
type: string
description: The feature name in kebab-case (e.g., user-management)
required: true
- name: entityName
type: string
description: The entity name in kebab-case (e.g., user, product)
required: true
- name: EntityName
type: string
description: The entity name in PascalCase (e.g., User, Product)
required: true
- name: Entities
type: string
description: The plural entity name in PascalCase (e.g., Users, Products)
required: true
- name: entities
type: string
description: The plural entity name in camelCase (e.g., users, products)
required: true
- name: featurePages
type: string
description: The feature pages directory name (usually plural kebab-case)
required: true
instructions: |
1. Replace {featureName} with your feature name (kebab-case)
2. Replace {entityName} with your entity name (kebab-case)
3. Replace {EntityName} with your entity name (PascalCase)
4. Replace {Entities} with plural entity name (PascalCase)
5. Replace {entities} with plural entity name (camelCase)
6. Replace {featurePages} with your pages directory name
7. Create the directory structure following this template
8. Implement each file according to the patterns shown
9. Ensure all imports and references are correctly updated
10. Test the complete feature integration

View File

@ -0,0 +1,132 @@
# <!-- Powered by BMAD™ Core -->
name: Schema-First Entity Template
description: Template for creating schema-first entity definitions with Zod validation
version: 1.0.0
template: |
// (features)/({featureName})/api/{entityName}/schema.ts
import { z } from 'zod'
// Zod schema for runtime validation
export const {EntityName}Schema = z.object({
id: z.string().uuid().optional(), // Optional for create operations
{schemaFields}
createdAt: z.date().optional(),
updatedAt: z.date().optional()
})
// Create schema (without id, createdAt, updatedAt)
export const {EntityName}CreateSchema = {EntityName}Schema.omit({
id: true,
createdAt: true,
updatedAt: true
})
// Update schema (partial, without createdAt)
export const {EntityName}UpdateSchema = {EntityName}Schema.partial().omit({
id: true,
createdAt: true
})
// Search/Filter schema
export const {EntityName}SearchSchema = z.object({
query: z.string().optional(),
page: z.number().min(1).default(1),
limit: z.number().min(1).max(100).default(20),
sortBy: z.enum([{sortFields}]).optional(),
sortOrder: z.enum(['asc', 'desc']).default('desc')
})
// TypeScript interfaces derived from Zod schemas
export type {EntityName}Model = z.infer<typeof {EntityName}Schema>
export type {EntityName}Create = z.infer<typeof {EntityName}CreateSchema>
export type {EntityName}Update = z.infer<typeof {EntityName}UpdateSchema>
export type {EntityName}Search = z.infer<typeof {EntityName}SearchSchema>
// Database model interface (database-agnostic)
export interface {EntityName}DatabaseModel extends {EntityName}Model {
id: string
createdAt: Date
updatedAt: Date
}
// API Response types
export interface {EntityName}Response {
data: {EntityName}DatabaseModel
success: boolean
message?: string
}
export interface {EntityName}ListResponse {
data: {EntityName}DatabaseModel[]
pagination: {
page: number
limit: number
total: number
totalPages: number
}
success: boolean
message?: string
}
// Example database implementations (uncomment and customize):
// Prisma model example:
// model {EntityName} {
// id String @id @default(cuid())
// {prismaFields}
// createdAt DateTime @default(now())
// updatedAt DateTime @updatedAt
// @@map("{entityName}")
// }
// Mongoose schema example:
// import mongoose from 'mongoose'
//
// const {entityName}Schema = new mongoose.Schema({
// {mongooseFields}
// }, {
// timestamps: true // Automatically adds createdAt and updatedAt
// })
//
// export const {EntityName}Mongoose = mongoose.model('{EntityName}', {entityName}Schema)
variables:
- name: featureName
type: string
description: The feature name in kebab-case (e.g., user-management)
required: true
- name: entityName
type: string
description: The entity name in kebab-case (e.g., user, product)
required: true
- name: EntityName
type: string
description: The entity name in PascalCase (e.g., User, Product)
required: true
- name: schemaFields
type: textarea
description: Zod schema fields definition (e.g., name: z.string().min(2), email: z.string().email())
required: true
- name: sortFields
type: string
description: Comma-separated list of sortable fields in quotes (e.g., "name", "createdAt", "updatedAt")
required: true
- name: prismaFields
type: textarea
description: Prisma model fields (optional)
required: false
- name: mongooseFields
type: textarea
description: Mongoose schema fields (optional)
required: false
instructions: |
1. Replace {featureName} with your feature name (kebab-case)
2. Replace {entityName} with your entity name (kebab-case)
3. Replace {EntityName} with your entity name (PascalCase)
4. Define {schemaFields} with appropriate Zod validation rules
5. List {sortFields} with fields that can be used for sorting
6. Optionally add database-specific field definitions
7. Customize validation rules based on business requirements
8. Consider adding custom Zod refinements for complex validation

View File

@ -0,0 +1,69 @@
# <!-- Powered by BMAD™ Core -->
name: base-controller-implementation
title: BaseController Pattern Implementation
description: Workflow for implementing and extending BaseController patterns for domain entities
version: 1.0.0
tasks:
- name: entity-modeling
title: Entity Data Modeling
description: Define entity structure and database relationships
inputs:
- name: entity_name
type: text
required: true
description: Name of the entity (PascalCase, e.g., User, Product)
- name: entity_fields
type: textarea
required: true
description: Entity fields with types and validation rules
- name: database_type
type: select
options: [sql, mongodb, database-agnostic]
default: database-agnostic
description: Target database type for optimization
outputs:
- name: entity_model
description: Complete entity model with TypeScript interfaces
- name: schema-creation
title: Create Zod Validation Schema
description: Implement Zod schema for runtime validation
depends_on: [entity-modeling]
outputs:
- name: zod_schema
description: Comprehensive Zod validation schema
- name: base-controller-extension
title: Extend BaseController
description: Create domain-specific controller extending BaseController
depends_on: [schema-creation]
outputs:
- name: domain_controller
description: Controller with database-agnostic CRUD operations
- name: search-filter-implementation
title: Implement Search Filtering
description: Create search filter logic for the entity
depends_on: [base-controller-extension]
outputs:
- name: search_filters
description: Database-agnostic search filtering implementation
- name: api-routes-generation
title: Generate API Routes
description: Create Next.js API routes using the controller
depends_on: [search-filter-implementation]
outputs:
- name: api_endpoints
description: RESTful API endpoints with proper error handling
- name: type-safety-validation
title: Validate Type Safety
description: Ensure end-to-end TypeScript type safety
depends_on: [api-routes-generation]
outputs:
- name: type_validation
description: Validated type safety across the entire data flow
agents: [base-controller-specialist, typescript-specialist, api-developer, database-specialist]

View File

@ -0,0 +1,88 @@
# <!-- Powered by BMAD™ Core -->
name: domain-feature-development
title: Domain Feature Development Workflow
description: Complete workflow for developing a new business domain feature following Feature-Based Architecture and Domain-Driven Design patterns
version: 1.0.0
tasks:
- name: domain-analysis
title: Business Domain Analysis
description: Analyze business requirements and define bounded context
inputs:
- name: business_domain
type: text
required: true
description: Name of the business domain (e.g., user-management, order-processing)
- name: business_requirements
type: textarea
required: true
description: Detailed business requirements and use cases
outputs:
- name: domain_model
description: Domain model with entities, relationships, and bounded context
- name: feature-structure-creation
title: Create Feature Structure
description: Generate feature folder structure in (features)/ directory
depends_on: [domain-analysis]
outputs:
- name: feature_folders
description: Complete feature directory structure (api/, components/, hooks/, types/)
- name: schema-definition
title: Define Domain Schemas
description: Create Zod schemas and TypeScript types for domain entities
depends_on: [feature-structure-creation]
outputs:
- name: domain_schemas
description: Zod validation schemas and TypeScript interfaces
- name: controller-implementation
title: Implement Feature Controller
description: Create domain-specific controller extending BaseController
depends_on: [schema-definition]
outputs:
- name: feature_controller
description: Domain controller with CRUD operations and business logic
- name: api-routes-creation
title: Create API Routes
description: Generate Next.js API routes for the domain
depends_on: [controller-implementation]
outputs:
- name: api_routes
description: RESTful API routes with proper error handling
- name: hooks-development
title: Develop Custom Hooks
description: Create React hooks for data fetching and mutations
depends_on: [api-routes-creation]
outputs:
- name: custom_hooks
description: Data fetching and mutation hooks following the established patterns
- name: components-creation
title: Create Feature Components
description: Build React components specific to the domain
depends_on: [hooks-development]
outputs:
- name: feature_components
description: React components with proper TypeScript typing and Tailwind styling
- name: pages-implementation
title: Implement Feature Pages
description: Create Next.js pages for the domain feature
depends_on: [components-creation]
outputs:
- name: feature_pages
description: Next.js pages with proper layouts and navigation
- name: integration-testing
title: Feature Integration Testing
description: Test the complete feature implementation
depends_on: [pages-implementation]
outputs:
- name: test_suite
description: Comprehensive test suite for the feature
agents: [domain-architect, nextjs-architect, base-controller-specialist, typescript-specialist, api-developer, tailwind-designer]

View File

@ -0,0 +1,65 @@
# <!-- Powered by BMAD™ Core -->
name: feature-based-project-setup
title: Feature-Based Architecture Project Setup
description: Complete workflow for setting up Next.js 15+ project with Feature-Based Architecture, Domain-Driven Design, and all required tooling
version: 1.0.0
tasks:
- name: project-initialization
title: Initialize Next.js 15+ Project
description: Create new Next.js project with App Router, TypeScript, and Tailwind 4.x
inputs:
- name: project_name
type: text
required: true
description: Name of the Next.js project
- name: package_manager
type: select
options: [pnpm, npm]
default: pnpm
description: Package manager preference (pnpm recommended)
outputs:
- name: project_structure
description: Next.js 15+ project with App Router and TypeScript
- name: feature-architecture-setup
title: Setup Feature-Based Architecture
description: Create (features)/ directory structure following Domain-Driven Design
depends_on: [project-initialization]
outputs:
- name: feature_structure
description: Feature-Based Architecture folder structure with shared infrastructure
- name: base-controller-foundation
title: Implement BaseController Foundation
description: Create BaseController abstract class and shared infrastructure
depends_on: [feature-architecture-setup]
outputs:
- name: base_controller
description: BaseController pattern with database-agnostic design
- name: schema-first-setup
title: Configure Schema-First Development
description: Set up Zod validation and schema-first patterns
depends_on: [base-controller-foundation]
outputs:
- name: schema_patterns
description: Zod schemas and validation patterns
- name: tooling-configuration
title: Configure Development Tooling
description: Set up ESLint 9, Prettier 3.6+, Husky hooks, and quality tools
depends_on: [project-initialization]
outputs:
- name: dev_tooling
description: Complete development tooling setup
- name: shared-infrastructure
title: Create Shared Infrastructure
description: Implement shared components, utilities, and patterns
depends_on: [feature-architecture-setup, schema-first-setup]
outputs:
- name: shared_components
description: Shared UI components and utility libraries
agents: [domain-architect, nextjs-architect, base-controller-specialist, typescript-specialist]

View File

@ -0,0 +1,56 @@
# <!-- Powered by BMAD™ Core -->
name: feature-development
title: Feature Development Workflow
description: Complete workflow for developing new features in Next.js applications
version: 1.0.0
tasks:
- name: feature-planning
title: Plan Feature Architecture
description: Design the feature architecture and component structure
inputs:
- name: feature_name
type: text
required: true
description: Name of the feature to develop
- name: feature_requirements
type: textarea
required: true
description: Detailed requirements and specifications
outputs:
- name: feature_plan
description: Feature architecture and implementation plan
- name: component-development
title: Develop React Components
description: Create React components with TypeScript and Tailwind
depends_on: [feature-planning]
outputs:
- name: components
description: React components with proper typing and styling
- name: api-integration
title: API Integration
description: Integrate with backend APIs and handle data
depends_on: [feature-planning]
outputs:
- name: api_integration
description: API integration code and data handling
- name: testing
title: Write Tests
description: Create unit and integration tests for the feature
depends_on: [component-development, api-integration]
outputs:
- name: tests
description: Comprehensive test suite
- name: documentation
title: Document Feature
description: Create documentation for the new feature
depends_on: [component-development, api-integration, testing]
outputs:
- name: documentation
description: Feature documentation and usage examples
agents: [nextjs-architect, typescript-specialist, tailwind-designer, api-developer, testing-engineer]

View File

@ -0,0 +1,56 @@
# <!-- Powered by BMAD™ Core -->
name: nextjs-project-setup
title: Next.js Project Setup & Configuration
description: Complete workflow for setting up a new Next.js project with TypeScript, Tailwind CSS, ESLint, and Prettier
version: 1.0.0
tasks:
- name: project-initialization
title: Initialize Next.js Project
description: Create new Next.js project with TypeScript template
inputs:
- name: project_name
type: text
required: true
description: Name of the Next.js project
- name: use_app_router
type: boolean
default: true
description: Use Next.js 14 App Router (recommended)
outputs:
- name: project_structure
description: Initial project structure and configuration files
- name: tailwind-setup
title: Configure Tailwind CSS
description: Set up and configure Tailwind CSS with custom configuration
depends_on: [project-initialization]
outputs:
- name: tailwind_config
description: Tailwind configuration and CSS files
- name: eslint-prettier-setup
title: Configure ESLint & Prettier
description: Set up code formatting and linting tools
depends_on: [project-initialization]
outputs:
- name: linting_config
description: ESLint and Prettier configuration files
- name: folder-structure
title: Organize Project Structure
description: Create organized folder structure following Next.js best practices
depends_on: [project-initialization]
outputs:
- name: organized_structure
description: Properly structured project directories
- name: environment-setup
title: Environment Configuration
description: Set up environment variables and configuration
depends_on: [project-initialization]
outputs:
- name: env_config
description: Environment configuration files
agents: [nextjs-architect, typescript-specialist, tailwind-designer]