micro-block-nextjs.md

Micro-block architecture implementation guide for Next.js applications - Updated with middleware location requirements

micro-block-nextjs.mdv1.0.318.2 KB
micro-block-nextjs.md(markdown)
1# Micro-block Architecture - Next.js Implementation
2
3This document provides implementation guidance for creating micro-block architecture projects using Next.js. This implementation is specifically designed for web applications with server-side rendering, API routes, and client-side functionality.
4
5## 🚨 BEFORE YOU START: Required Components
6
7**CRITICAL**: The following components are PROVIDED and must be imported, not recreated:
8
9-**IMPORT REQUIRED**: [`utaba/main/services/micro-block/ServiceRegistry.ts`](utaba/main/services/micro-block/ServiceRegistry.ts) - Singleton service registry with lazy initialization and dependency injection
10-**IMPORT REQUIRED**: [`utaba/main/services/micro-block/CommandRegistry.ts`](utaba/main/services/micro-block/CommandRegistry.ts) - Central registry for discovering and instantiating commands with dynamic loading and metadata-driven orchestration
11-**IMPORT REQUIRED**: [`utaba/main/commands/micro-block/BaseCommand.ts`](utaba/main/commands/micro-block/BaseCommand.ts) - Complete command architecture with OutputCommand and InputOnlyCommand base classes
12-**IMPORT REQUIRED**: [`utaba/main/services/micro-block/BaseService.ts`](utaba/main/services/micro-block/BaseService.ts) - Abstract base class with comprehensive metadata, operation framework, and validation
13-**IMPORT REQUIRED**: [`utaba/main/services/micro-block/LoggerFactory.ts`](utaba/main/services/micro-block/LoggerFactory.ts) - Complete logging system with ILogger interface and ConsoleLogger implementation
14
15**❌ DO NOT IMPLEMENT FROM SCRATCH** - These are battle-tested implementations.
16
17## Instructions for AI Assistants (CRITICAL)
18
19### MANDATORY: Discovery Before Implementation
20
211. **ALWAYS check UCM first**: Before implementing any service/command/component, search `utaba/main/[category]` for existing implementations
222. **Ask the human**: "I found [X] existing implementations in UCM. Should I import these or build from scratch?"
233. **Explicit import decisions**: State clearly what you're importing vs building in your task planning
24
25### Implementation Priority Order
261.**FIRST**: Import existing UCM implementations  
272.**SECOND**: Adapt/configure imported components
283.**LAST**: Build new components (only if nothing exists in UCM)
29
30### Pre-Implementation Checklist (MANDATORY)
31
32**Before starting any implementation task, verify:**
33
34- [ ] **UCM Component Discovery**: Searched `utaba/main/[category]` for existing implementations
35- [ ] **Import vs Build Decision**: Documented what will be imported vs built from scratch  
36- [ ] **Reuse Strategy**: Listed all UCM components that will be reused
37
38**AI Assistant Rule**: You MUST complete this checklist before implementing any service, command, or core component.
39
40## Step 1: Import Core Components (MANDATORY)
41
42Before any project setup, import these essential components and adapt import paths:
43
44```typescript
45// Import the required implementations from your project structure
46import { ServiceRegistry } from '@/core/registry/ServiceRegistry';
47import { CommandRegistry } from '@/core/registry/CommandRegistry';
48import { BaseCommand } from '@/core/interfaces/BaseCommand';
49import { BaseService } from '@/core/interfaces/BaseService';
50import { LoggerFactory } from '@/core/logging/LoggerFactory';
51```
52
53## Example Artifacts
54
55**Important**: Before implementing, review `utaba/main/implementations/micro-block-nextjs/README.md` which contains a curated list of recommended example artifacts and implementation templates. These should be imported and adapted for your specific implementation to ensure consistency with established patterns and best practices.
56
57## Pattern Reference
58
59**Based on:** `utaba/main/patterns/micro-block/micro-block-pattern.md`  
60**UCM Pattern:** Micro-Block Architecture Pattern  
61
62## Folder Structure
63
64The micro-block architecture follows a specific folder organization pattern. Here are the key directories and their purposes:
65
66| Folder Path | Description |
67|-------------|-------------|
68| `src/app/` | Next.js App Router directory containing pages, layouts, and API routes for the web application |
69| `src/commands/` | Command implementations organized by domain (e.g., user, artifact, auth) following the Command pattern |
70| `src/services/` | Service layer implementations providing business logic and external integrations |
71| `src/core/` | Core micro-block architecture components including base classes, registries, and logging |
72| `src/core/interfaces/` | Base interfaces and abstract classes (BaseCommand, BaseService, CommandMetadata) |
73| `src/core/registry/` | Service and Command registries for dependency injection and component discovery |
74| `src/core/logging/` | Logging infrastructure including LoggerFactory and logger interfaces |
75| `src/config/` | Application configuration system and environment-specific settings |
76| `src/components/` | Reusable React components and UI elements |
77| `src/lib/` | Utility libraries and helper functions |
78| `src/types/` | TypeScript type definitions and interfaces |
79| `src/repositories/` | Data access layer providing abstraction over data storage |
80| `src/test-utils/` | Testing utilities, mocks, and setup helpers |
81
82## Prerequisites
83
84- Node.js 18.0.0 or higher
85- Next.js 15.0.0 or higher
86- TypeScript 5.0.0 or higher
87- Understanding of Next.js App Router and server/client components
88
89## Important: Next.js Middleware Location
90
91**CRITICAL**: When using a `src` folder structure, the `middleware.ts` file must be placed in the `src` directory (`src/middleware.ts`), NOT in the project root. This is a Next.js requirement that prevents middleware from executing if incorrectly placed.
92
93## Project Setup
94
95### 1. Initialize Next.js Project
96
97```bash
98# Create Next.js project with TypeScript
99npx create-next-app@latest my-microblock-nextjs --typescript --app --eslint --tailwind --src-dir
100
101cd my-microblock-nextjs
102```
103
104### 2. Install Additional Dependencies
105
106```bash
107# Core dependencies for micro-block architecture
108npm install bcryptjs 
109
110# Development dependencies
111npm install --save-dev @types/bcryptjs vitest @vitest/ui eslint-config-next
112
113# Optional: Authentication (NextAuth.js)
114npm install next-auth
115```
116
117### 3. Configure Next.js
118
119Update `next.config.mjs`:
120
121```javascript
122/** @type {import('next').NextConfig} */
123const nextConfig = {
124  webpack: (config, { isServer }) => {
125    // Handle Node.js modules for client-side builds
126    if (!isServer) {
127      config.resolve.fallback = {
128        ...config.resolve.fallback,
129        fs: false, net: false, tls: false, crypto: false,
130        stream: false, url: false, zlib: false,
131        http: false, https: false, os: false, path: false,
132      };
133    }
134    return config;
135  },
136  serverExternalPackages: [],
137};
138
139export default nextConfig;
140```
141
142### 4. Configure TypeScript
143
144Update `tsconfig.json`:
145
146```json
147{
148  "compilerOptions": {
149    "target": "ES2017",
150    "lib": ["dom", "dom.iterable", "esnext"],
151    "strict": true,
152    "module": "esnext",
153    "moduleResolution": "bundler",
154    "jsx": "preserve",
155    "paths": {
156      "@/*": ["./src/*"]
157    }
158  }
159}
160```
161
162### 5. Update package.json Scripts
163
164```json
165{
166  "scripts": {
167    "dev": "next dev",
168    "build": "next build",
169    "start": "next start",
170    "lint": "next lint",
171    "test": "vitest",
172    "typecheck": "tsc --noEmit"
173  }
174}
175```
176
177## Core Architecture Implementation
178
179### 1. Configuration System
180
181Create `src/config.ts` with environment-based configuration:
182
183```typescript
184export interface AppConfig {
185  env: 'development' | 'production' | 'test';
186  baseUrl: string;
187  database: {
188    connectionString: string;
189    options: {
190      encrypt: boolean;
191      trustServerCertificate: boolean;
192      connectionTimeout: number;
193      requestTimeout: number;
194    };
195  };
196  cache: {
197    provider: 'memory';
198    memory: {
199      maxSize: number;
200      defaultTTL: number;
201      cleanupInterval: number;
202    };
203  };
204  // ... other service configurations
205}
206```
207
208### 2. Import and Adapt Base Interfaces
209
210**IMPORTANT**: Instead of creating these from scratch, import and adapt from UCM:
211
212```typescript
213// Import from your project structure
214import { BaseCommand, CommandMetadata } from '@/core/interfaces/BaseCommand';
215import { BaseService, ServiceMetadata } from '@/core/interfaces/BaseService';
216import { ILogger, ICommandLogger } from '@/core/logging/ILogger';
217```
218
219### 3. Service Registry Integration
220
221**IMPORTANT**: Import the existing ServiceRegistry, don't recreate:
222
223```typescript
224import { ServiceRegistry } from '@/core/registry/ServiceRegistry';
225
226// Usage in your application
227const serviceRegistry = ServiceRegistry.getInstance();
228serviceRegistry.configure(appConfig);
229```
230
231### 4. Command Registry Integration
232
233**IMPORTANT**: The CommandRegistry is automatically provided by ServiceRegistry:
234
235```typescript
236// Access through ServiceRegistry - do not create separately
237const serviceRegistry = ServiceRegistry.getInstance();
238const commandRegistry = serviceRegistry.getCommandRegistry();
239
240// Use the registry
241const command = await commandRegistry.get<MyCommand>(MyCommand, input, logger);
242const result = await command.execute();
243```
244
245## Service Architecture Requirements
246
247### 1. Service Portability
248
249**CRITICAL**: Services must be portable - Services should not depend on project-specific configuration classes. All dependencies must be injected through constructor parameters.
250
251### 2. Service Configuration Pattern
252
253Services should follow this pattern for maximum portability:
254
255```typescript
256// Service-specific configuration interface
257export interface CacheServiceConfig {
258  maxMemoryMB: number;
259  defaultTtlSeconds: number;
260  evictionPolicy: 'LRU' | 'LFU' | 'FIFO';
261  enableMetrics: boolean;
262}
263
264// Service interface
265export interface ICacheService extends BaseService {
266  get<T>(key: string): T | null;
267  set<T>(key: string, value: T, ttlSeconds?: number): void;
268  delete(key: string): boolean;
269  flush(): void;
270}
271
272// Portable service implementation
273export class MemoryCacheService extends BaseService implements ICacheService {
274  constructor(
275    private config: CacheServiceConfig,
276    private logger: ILogger,
277    private metricsService?: IMetricsService
278  ) {
279    super();
280  }
281  
282  // Implementation uses this.config, not project-specific configuration
283}
284```
285
286### 3. BaseService Usage
287
288**IMPORTANT**: Import BaseService from UCM, extend it for all your services:
289
290```typescript
291import { BaseService } from '@/core/interfaces/BaseService';
292
293export class YourCustomService extends BaseService {
294  constructor(
295    private config: YourServiceConfig,
296    private logger: ILogger
297  ) {
298    super();
299  }
300  
301  // Your service implementation
302}
303```
304
305## Service Implementations
306
307### 1. Cache Service
308
309**Reference Implementations:** See `utaba/main/services/cache/` for service examples
310
311Cache implementation with:
312- TTL support
313- Size limits
314- Automatic cleanup
315- Singleton pattern
316
317### 2. Email Service
318
319**Reference Implementation:** See `utaba/main/services/communication`
320- Template-based emails
321- Verification emails
322- Configuration-driven setup
323
324## Command Implementations
325
326### User Commands
327
328**IMPORTANT**: Import BaseCommand from UCM and extend it:
329
330```typescript
331import { BaseCommand, CommandMetadata } from '@/core/interfaces/BaseCommand';
332
333export class YourCommand extends BaseCommand {
334  static readonly metadata: CommandMetadata = {
335    name: 'YourCommand',
336    description: 'Your command description',
337    category: 'your-category',
338    inputType: 'YourCommandInput',
339    outputType: 'YourCommandOutput',
340    errorType: 'YourCommandError',
341    version: '1.0.0',
342    contractVersion: '1.0',
343    dataFlow: {
344      inputs: ['input-type'],
345      outputs: ['output-type'],
346      sideEffects: ['side-effect-description']
347    },
348    performance: {
349      expectedDuration: '1000ms',
350      scaling: 'O(1)'
351    },
352    dependencies: {
353      services: ['IYourService'],
354      commands: []
355    }
356  };
357
358  constructor(
359    input?: YourCommandInput,
360    logger?: ICommandLogger,
361    services?: Record<string, any>,
362    commands?: Record<string, BaseCommand>
363  ) {
364    super();
365    // Your constructor logic
366  }
367
368  validate(): void {
369    // Input validation
370  }
371
372  async execute(): Promise<YourCommandOutput> {
373    // Your command logic
374  }
375}
376```
377
378## Architecture Principles
379
380### Lightweight Implementation Pattern
381
382**CRITICAL**: Both API Routes and Server-Side React Components are intended to be lightweight and slim implementations where the business logic is contained in Services and Commands. These components should act as thin orchestration layers that:
383
384- Accept input data
385- Delegate business logic to Commands via CommandRegistry
386- Handle response formatting, error handling, and UI rendering
387- Avoid containing domain logic or business rules
388
389**This applies to:**
390- API route handlers (`app/api/*/route.ts`)
391- Server Components (`app/*/page.tsx`)
392- Server Actions
393- Middleware functions
394
395### Implementation Guidelines
396
397- **DO**: Use CommandRegistry to execute business logic
398- **DO**: Keep components focused on presentation and orchestration
399- **DON'T**: Implement business rules directly in routes or components
400- **DON'T**: Perform complex data transformations in presentation layers
401
402## API Routes Implementation
403
404### 1. User Registration API
405
406Create `app/api/auth/register/route.ts`:
407
408```typescript
409import { ServiceRegistry } from '@/core/registry/ServiceRegistry';
410
411export async function POST(request: NextRequest) {
412  const serviceRegistry = ServiceRegistry.getInstance();
413  const commandRegistry = serviceRegistry.getCommandRegistry();
414  const logger = serviceRegistry.getLogger('RegisterAPI');
415
416  const createUserCommand = await commandRegistry.get<CreateUserCommand>(
417    CreateUserCommand, 
418    { email, password, name },
419    logger
420  );
421  const userResult = await createUserCommand.execute();
422
423  return NextResponse.json({
424    success: true,
425    message: 'Account created successfully.',
426    requiresVerification: userResult.requiresVerification
427  });
428}
429```
430
431### 2. Authentication with NextAuth.js
432
433Integration pattern using commands for authentication:
434
435```typescript
436// src/lib/auth.ts
437import { ServiceRegistry } from '@/core/registry/ServiceRegistry';
438
439export const authConfig: NextAuthConfig = {
440  providers: [
441    Credentials({
442      async authorize(credentials) {
443        const serviceRegistry = ServiceRegistry.getInstance();
444        const commandRegistry = serviceRegistry.getCommandRegistry();
445        
446        const loginCommand = await commandRegistry.get<LoginUserCommand>(
447          LoginUserCommand,
448          { email: credentials.email, password: credentials.password }
449        );
450        const loginResult = await loginCommand.execute();
451        
452        return loginResult.success ? loginResult.user : null;
453      }
454    })
455  ]
456};
457```
458
459## Testing Implementation
460
461### 1. Test Setup
462
463Create test utilities in `src/test-utils/`:
464- Mock service creation
465- Configuration helpers
466- Async expectation utilities
467
468### 2. Command Tests
469
470Pattern:
471```typescript
472describe('SetCacheCommand', () => {
473  let mockCacheService: ICacheService;
474  let command: SetCacheCommand;
475
476  beforeEach(() => {
477    mockCacheService = createMockService<ICacheService>({
478      set: vi.fn(),
479      get: vi.fn()
480    });
481
482    command = new SetCacheCommand(
483      undefined,
484      undefined,
485      { 'ICacheService': mockCacheService }
486    );
487  });
488
489  it('should set cache value successfully', async () => {
490    command.setInput({ key: 'test', value: 'value' });
491    await command.execute();
492    expect(mockCacheService.set).toHaveBeenCalledWith('test', 'value', undefined);
493  });
494});
495```
496
497## Environment Configuration
498
499### 1. Environment Variables
500
501Create `.env.local`:
502
503```bash
504# Database
505DATABASE_CONNECTION_STRING=Server=localhost;Database=MyApp;User Id=sa;Password=YourPassword;
506
507# Authentication
508NEXTAUTH_SECRET=your-super-secret-key-here
509NEXTAUTH_URL=http://localhost:3000
510
511# Email
512EMAILPROVIDER_API_KEY=your-api-key
513FROM_EMAIL=noreply@yourapp.com
514```
515
516### 2. Deployment
517
518Standard Next.js deployment with Docker support. Configure environment variables and ensure database connectivity.
519
520## Best Practices Summary
521
522### 1. Command Design
523
524- **Import Base Classes**: Always import BaseCommand from UCM
525- **Static Metadata**: Always provide static metadata accessible before instantiation
526- **Self-Contained**: Keep all command-related types in the same file
527- **Interface Dependencies**: Use service interfaces, not concrete implementations
528- **Contract Naming**: Use domain-focused names, not platform-specific ones
529- **Error Handling**: Extend BaseError for all command-specific errors
530
531### 2. Next.js Specific
532
533- **Server/Client Separation**: Keep server-only code in API routes and server components
534- **ServiceRegistry Access**: Use ServiceRegistry.getInstance() for API routes and server actions
535- **Build Optimization**: Configure webpack to exclude server-only modules from client bundle
536
537### 3. Micro-block Architecture
538
539- **Import UCM Components**: Always import ServiceRegistry, CommandRegistry, BaseCommand, BaseService
540- **Singleton ServiceRegistry**: All requests share the same ServiceRegistry instance
541- **Lazy Command Loading**: Commands are loaded on-demand with automatic service injection
542- **Error Handling**: Proper error contracts and recovery mechanisms
543- **Testing**: Mock services through ServiceRegistry for clean testing
544- **Service Portability**: Services must not depend on project-specific configuration classes
545- **Version Compatibility**: Track both service and contract versions
546
547### 4. Production Considerations
548
549- **Database Connections**: Use connection pooling and proper connection management
550- **Security**: Validate all inputs and sanitize outputs
551- **Monitoring**: Log command execution and performance metrics
552
553## Key Implementation Benefits
554
555### 1. ServiceRegistry Pattern
556- **Singleton Design**: One ServiceRegistry instance manages all services
557- **Lazy Initialization**: Services are created only when first requested
558- **Factory Pattern**: Services are registered as factory functions
559- **NextJS Optimized**: Works well with NextJS's request-based architecture
560
561### 2. CommandRegistry Integration  
562- **Lazy Loading**: Commands are dynamically imported when first requested
563- **Automatic Service Injection**: Commands receive resolved dependencies automatically
564- **No Upfront Registration**: Commands don't need to be registered at startup
565- **Simplified API**: Use `registry.get<CommandClass>(CommandClass, input)` for instant command execution
566
567This Next.js implementation provides a complete foundation for building scalable web applications using the micro-block architecture pattern with full AI-collaborative capabilities.

Metadata

Path
utaba/main/implementations/micro-block-nextjs/micro-block-nextjs.md
Namespace
utaba/main/implementations/micro-block-nextjs
Author
utaba
Category
implementations
Technology
nextjs
Contract Version
1.0.3
MIME Type
text/markdown
Published
28-Jul-2025
Last Updated
28-Jul-2025