Application Structure

Comprehensive application structure including directory organization, component patterns, and code architecture.

Application Structure

Welcome to the comprehensive application structure documentation. This section covers how the application is organized, structured, and architected for maintainability, scalability, and developer productivity.

Application Structure Overview

The application follows modern Next.js App Router patterns with a feature-based organization strategy, emphasizing clear separation of concerns, reusable components, and maintainable code architecture.

Key Structural Characteristics

  • Feature-Based Organization: Logical grouping by business functionality
  • Layered Architecture: Clear separation between presentation, business, and data layers
  • Component Hierarchy: Atomic design principles for UI components
  • Type Safety: End-to-end TypeScript for structure and reliability
  • Scalable Patterns: Architecture that grows with application needs

Core Structure Components

📁 Directory Structure

Comprehensive directory organization and file structure patterns:

  • Root Level Organization: Project structure and core directories
  • App Router Structure: Next.js App Router file-based routing patterns
  • Feature Organization: Domain-driven directory structures
  • File Naming Conventions: Consistent naming patterns and standards
  • Organization Principles: Scalable structure design principles

🧩 Component Organization

React component architecture and organization strategies:

  • Atomic Design: Component hierarchy from atoms to organisms
  • Component Patterns: Compound components, render props, and HOCs
  • Custom Hooks: Reusable state logic and side effect management
  • Component Documentation: PropTypes, Storybook, and testing patterns
  • Performance Optimization: Memoization and optimization strategies

📋 Code Organization

Code structure patterns and architectural approaches:

  • Clean Architecture: Layered architecture with clear boundaries
  • Service Layer: Business logic organization and patterns
  • Repository Pattern: Data access abstraction and management
  • Module Organization: Feature-based and domain-driven structure
  • Error Handling: Comprehensive error management strategies

Quick Structure Reference

Technology Stack

// Application Structure Technologies
const structureStack = {
  framework: ['Next.js 14', 'App Router', 'React 18'],
  language: ['TypeScript', 'JavaScript'],
  styling: ['Tailwind CSS', 'CSS Modules'],
  stateManagement: ['React Hooks', 'Context API', 'Zustand'],
  testing: ['Jest', 'Testing Library', 'Storybook'],
  tooling: ['ESLint', 'Prettier', 'Husky']
}

Organization Patterns

  • Feature-Based Structure: Group by business functionality
  • Atomic Component Design: Hierarchical component organization
  • Service Layer Pattern: Clean separation of business logic
  • Repository Pattern: Data access abstraction
  • Custom Hooks Pattern: Reusable stateful logic

File Structure Conventions

  • Route Files: page.tsx, layout.tsx, loading.tsx, error.tsx
  • Component Files: PascalCase with descriptive names
  • Utility Files: kebab-case with clear functionality indication
  • Type Files: .types.ts suffix for type definitions
  • Test Files: .test.tsx or .spec.tsx co-located with source

Implementation Examples

Typical Feature Structure

features/
├── products/
│   ├── components/           # Feature-specific components
│   │   ├── ProductCard.tsx
│   │   ├── ProductForm.tsx
│   │   └── ProductList.tsx
│   ├── hooks/               # Custom hooks
│   │   ├── use-products.ts
│   │   └── use-product-form.ts
│   ├── services/            # Business logic
│   │   └── product.service.ts
│   ├── types/               # Type definitions
│   │   └── product.types.ts
│   └── utils/               # Utility functions
│       └── validators.ts

Component Organization Example

// Atomic component structure
components/
├── ui/                      # Atoms
│   ├── Button/
│   ├── Input/
│   └── Badge/
├── forms/                   # Molecules
│   ├── FormField/
│   └── SearchBox/
├── features/                # Organisms
│   ├── ProductForm/
│   └── InventoryTable/
└── layouts/                 # Templates
    ├── AppLayout/
    └── AuthLayout/

Service Layer Example

// Clean service architecture
export class ProductService {
  constructor(
    private productRepository: ProductRepository,
    private inventoryService: InventoryService,
    private auditService: AuditService
  ) {}
  
  async createProduct(data: CreateProductData): Promise<Product> {
    // Business logic validation
    await this.validateProductData(data)
    
    // Create product
    const product = await this.productRepository.create(data)
    
    // Initialize inventory
    await this.inventoryService.initializeProduct(product.id)
    
    // Audit logging
    await this.auditService.log('product_created', { productId: product.id })
    
    return product
  }
}

Structure Benefits

Developer Experience

  • Intuitive Navigation: Logical file and folder organization
  • Clear Patterns: Consistent structure across features
  • Type Safety: TypeScript for better development experience
  • Hot Reloading: Fast development feedback loops

Maintainability

  • Separation of Concerns: Clear boundaries between layers
  • Reusable Components: DRY principles and component reusability
  • Modular Architecture: Independent, testable modules
  • Documentation: Self-documenting code structure

Scalability

  • Feature-Based Growth: Easy addition of new features
  • Component Reusability: Scalable UI component system
  • Service Abstraction: Clean business logic separation
  • Testing Strategy: Comprehensive testing at all levels

Performance

  • Code Splitting: Automatic optimization by Next.js
  • Component Optimization: Efficient re-rendering strategies
  • Bundle Optimization: Tree shaking and dead code elimination
  • Lazy Loading: On-demand component and route loading

Getting Started with Application Structure

For New Developers

  1. Directory Overview: Start with Directory Structure
  2. Component Patterns: Learn Component Organization
  3. Code Architecture: Understand Code Organization
  4. Best Practices: Follow established patterns and conventions

For Frontend Developers

  1. Component System: Master the atomic design component hierarchy
  2. State Management: Learn custom hooks and state patterns
  3. Styling Patterns: Understand CSS organization and Tailwind usage
  4. Testing Strategy: Implement component and integration testing

For Backend Developers

  1. Service Layer: Understand business logic organization
  2. Repository Pattern: Learn data access abstraction
  3. API Integration: Study client-server communication patterns
  4. Error Handling: Implement comprehensive error management

Complementary Architecture Docs

Development Guides


This application structure documentation provides the foundation for organizing scalable, maintainable Next.js applications. Each section builds upon the others to create a comprehensive development architecture. │ │ └── reports/ # Inventory reports │ │ ├── page.tsx │ │ └── [type]/ │ ├── products/ # Product management │ │ ├── page.tsx # Product catalog │ │ ├── add/ # Add new product │ │ │ └── page.tsx │ │ ├── [id]/ # Product details │ │ │ ├── page.tsx │ │ │ ├── edit/ │ │ │ └── variants/ │ │ ├── categories/ # Category management │ │ │ ├── page.tsx │ │ │ └── [id]/ │ │ └── scan/ # Barcode scanning │ │ └── page.tsx │ ├── purchasing/ # Purchase management │ │ ├── orders/ # Purchase orders │ │ │ ├── page.tsx │ │ │ ├── new/ │ │ │ └── [id]/ │ │ ├── suppliers/ # Supplier management │ │ │ ├── page.tsx │ │ │ ├── add/ │ │ │ └── [id]/ │ │ └── receiving/ # Receiving orders │ │ ├── page.tsx │ │ └── [id]/ │ ├── sales/ # Sales management │ │ ├── orders/ # Sales orders │ │ │ ├── page.tsx │ │ │ ├── new/ │ │ │ └── [id]/ │ │ └── customers/ # Customer management │ │ ├── page.tsx │ │ ├── add/ │ │ └── [id]/ │ ├── warehouse/ # Warehouse management │ │ ├── locations/ # Warehouse locations │ │ │ ├── page.tsx │ │ │ └── [id]/ │ │ └── transfers/ # Inter-warehouse transfers │ │ ├── page.tsx │ │ └── new/ │ ├── analytics/ # Reports and analytics │ │ ├── inventory/ # Inventory analytics │ │ │ ├── page.tsx │ │ │ └── [report]/ │ │ ├── sales/ # Sales analytics │ │ │ ├── page.tsx │ │ │ └── [report]/ │ │ └── financial/ # Financial reports │ │ ├── page.tsx │ │ └── [report]/ │ └── admin/ # Administration │ ├── users/ # User management │ │ ├── page.tsx │ │ ├── add/ │ │ └── [id]/ │ └── settings/ # System settings │ ├── page.tsx │ └── [category]/


### API Routes Structure

app/ ├── api/ # API routes │ ├── auth/ # Authentication endpoints │ │ ├── login/ │ │ │ └── route.ts │ │ ├── logout/ │ │ │ └── route.ts │ │ └── callback/ │ │ └── route.ts │ ├── products/ # Product API │ │ ├── route.ts # GET, POST /api/products │ │ ├── [id]/ │ │ │ └── route.ts # GET, PUT, DELETE /api/products/[id] │ │ └── search/ │ │ └── route.ts # GET /api/products/search │ ├── inventory/ # Inventory API │ │ ├── route.ts # GET /api/inventory │ │ ├── movements/ │ │ │ └── route.ts # GET, POST /api/inventory/movements │ │ ├── adjustments/ │ │ │ └── route.ts # POST /api/inventory/adjustments │ │ └── analytics/ │ │ └── route.ts # GET /api/inventory/analytics │ ├── purchase-orders/ # Purchase order API │ │ ├── route.ts │ │ └── [id]/ │ │ ├── route.ts │ │ ├── receive/ │ │ │ └── route.ts │ │ └── status/ │ │ └── route.ts │ ├── sales/ # Sales API │ │ ├── orders/ │ │ │ ├── route.ts │ │ │ └── [id]/ │ │ │ └── route.ts │ │ └── customers/ │ │ ├── route.ts │ │ └── [id]/ │ │ └── route.ts │ ├── suppliers/ # Supplier API │ │ ├── route.ts │ │ └── [id]/ │ │ ├── route.ts │ │ └── performance/ │ │ └── route.ts │ ├── warehouse/ # Warehouse API │ │ ├── route.ts │ │ └── [id]/ │ │ ├── route.ts │ │ └── inventory/ │ │ └── route.ts │ └── analytics/ # Analytics API │ ├── dashboard/ │ │ └── route.ts │ ├── inventory/ │ │ └── route.ts │ └── sales/ │ └── route.ts


### Authentication Pages

app/ ├── auth/ # Authentication pages │ ├── login/ # Login page │ │ └── page.tsx │ ├── sign-up/ # Registration page │ │ └── page.tsx │ ├── callback/ # OAuth callback │ │ └── page.tsx │ ├── error/ # Auth error handling │ │ └── page.tsx │ └── layout.tsx # Auth layout


## Component Organization

### UI Components (shadcn/ui)

components/ ├── ui/ # Base UI components │ ├── button.tsx # Button variations │ ├── card.tsx # Card containers │ ├── dialog.tsx # Modal dialogs │ ├── form.tsx # Form components │ ├── input.tsx # Input fields │ ├── table.tsx # Data tables │ ├── select.tsx # Dropdown selects │ ├── badge.tsx # Status badges │ ├── alert.tsx # Alert messages │ ├── loading.tsx # Loading spinners │ ├── pagination.tsx # Pagination controls │ ├── breadcrumb.tsx # Navigation breadcrumbs │ ├── tabs.tsx # Tab components │ ├── accordion.tsx # Collapsible content │ ├── tooltip.tsx # Tooltip overlays │ ├── dropdown-menu.tsx # Context menus │ ├── sheet.tsx # Slide-out panels │ ├── popover.tsx # Popover content │ ├── calendar.tsx # Date picker │ ├── checkbox.tsx # Checkbox inputs │ ├── radio-group.tsx # Radio button groups │ ├── switch.tsx # Toggle switches │ ├── slider.tsx # Range sliders │ ├── textarea.tsx # Text areas │ ├── progress.tsx # Progress bars │ ├── skeleton.tsx # Loading skeletons │ └── separator.tsx # Visual separators


### Feature-Specific Components

components/ ├── dashboard/ # Dashboard components │ ├── metrics-cards.tsx # KPI metric cards │ ├── inventory-chart.tsx # Inventory level charts │ ├── activity-feed.tsx # Recent activity list │ ├── quick-actions.tsx # Quick action buttons │ ├── low-stock-alerts.tsx # Stock alert notifications │ └── revenue-chart.tsx # Revenue analytics chart ├── inventory/ # Inventory components │ ├── stock-table.tsx # Stock level data table │ ├── movement-form.tsx # Stock movement form │ ├── adjustment-dialog.tsx # Adjustment modal │ ├── low-stock-alerts.tsx # Low stock warnings │ ├── barcode-scanner.tsx # Barcode scanning │ └── location-picker.tsx # Warehouse location selector ├── products/ # Product components │ ├── product-form.tsx # Product creation/editing form │ ├── product-table.tsx # Product catalog table │ ├── category-selector.tsx # Category dropdown │ ├── variant-manager.tsx # Product variant management │ ├── price-calculator.tsx # Pricing calculations │ └── image-uploader.tsx # Product image upload ├── orders/ # Order components │ ├── order-form.tsx # Order creation form │ ├── order-table.tsx # Order listing table │ ├── order-status.tsx # Status indicators │ ├── line-item-editor.tsx # Order line item editing │ └── shipping-calculator.tsx # Shipping cost calculation ├── auth/ # Authentication components │ ├── login-form.tsx # Login form │ ├── sign-up-form.tsx # Registration form │ ├── auth-button.tsx # Auth state button │ ├── role-guard.tsx # Role-based access guard │ ├── password-reset.tsx # Password reset form │ └── user-profile.tsx # User profile management └── layout/ # Layout components ├── sidebar.tsx # Navigation sidebar ├── header.tsx # Page header ├── nav-item.tsx # Navigation item ├── user-menu.tsx # User dropdown menu ├── breadcrumbs.tsx # Navigation breadcrumbs ├── page-header.tsx # Page title and actions └── footer.tsx # Page footer


## Library Organization

### Core Libraries

lib/ ├── supabase/ # Supabase configuration │ ├── client.ts # Client-side Supabase │ ├── server.ts # Server-side Supabase │ ├── middleware.ts # Middleware config │ └── types.ts # Database types ├── services/ # Business logic services │ ├── products.ts # Product service │ ├── inventory.ts # Inventory service │ ├── orders.ts # Order service │ ├── analytics.ts # Analytics service │ ├── auth.ts # Authentication service │ ├── notifications.ts # Notification service │ └── export.ts # Data export service ├── actions/ # Server actions │ ├── products.ts # Product actions │ ├── inventory.ts # Inventory actions │ ├── orders.ts # Order actions │ ├── auth.ts # Auth actions │ └── analytics.ts # Analytics actions ├── validations/ # Zod schemas │ ├── products.ts # Product validation schemas │ ├── inventory.ts # Inventory validation schemas │ ├── orders.ts # Order validation schemas │ ├── auth.ts # Auth validation schemas │ └── common.ts # Common validation schemas ├── utils/ # Utility functions │ ├── dates.ts # Date formatting utilities │ ├── currency.ts # Currency formatting │ ├── formatters.ts # Data formatters │ ├── calculations.ts # Business calculations │ ├── export.ts # Data export utilities │ └── constants.ts # Application constants └── types/ # TypeScript definitions ├── database.ts # Database types ├── api.ts # API types ├── auth.ts # Authentication types ├── inventory.ts # Inventory types ├── orders.ts # Order types └── common.ts # Common types


### Custom Hooks

hooks/ ├── use-current-user.ts # Current user hook ├── use-mobile.tsx # Mobile detection ├── use-inventory.ts # Inventory data hook ├── use-products.ts # Product data hook ├── use-orders.ts # Order data hook ├── use-analytics.ts # Analytics data hook ├── use-realtime.ts # Real-time subscription hook ├── use-local-storage.ts # Local storage hook ├── use-debounce.ts # Debounced value hook ├── use-pagination.ts # Pagination hook ├── use-filters.ts # Data filtering hook ├── use-search.ts # Search functionality hook └── use-notifications.ts # Notification management hook


## File Naming Conventions

### Component Files
- **React Components**: PascalCase (e.g., `ProductForm.tsx`)
- **Page Components**: `page.tsx` (Next.js convention)
- **Layout Components**: `layout.tsx` (Next.js convention)
- **Loading States**: `loading.tsx` (Next.js convention)
- **Error Boundaries**: `error.tsx` (Next.js convention)

### Utility Files
- **Services**: kebab-case (e.g., `product-service.ts`)
- **Utils**: kebab-case (e.g., `date-utils.ts`)
- **Types**: kebab-case (e.g., `api-types.ts`)
- **Constants**: kebab-case (e.g., `app-constants.ts`)

### API Routes
- **Route Handlers**: `route.ts` (Next.js App Router convention)
- **Dynamic Routes**: `[param]/route.ts`
- **Catch-all Routes**: `[...slug]/route.ts`

## Code Organization Patterns

### Barrel Exports
Use index files to create clean import paths:

```typescript
// components/index.ts
export { Button } from './ui/button'
export { Card } from './ui/card'
export { ProductForm } from './products/product-form'
export { InventoryTable } from './inventory/inventory-table'

// Usage
import { Button, Card, ProductForm } from '@/components'

Service Layer Pattern

Organize business logic in dedicated service files:

// lib/services/product-service.ts
export class ProductService {
  static async createProduct(data: CreateProductData) {
    // Business logic for creating products
  }
  
  static async updateProduct(id: string, data: UpdateProductData) {
    // Business logic for updating products
  }
}

Type Organization

Group related types together:

// lib/types/product-types.ts
export interface Product {
  id: string
  name: string
  sku: string
  price: number
}

export interface CreateProductData {
  name: string
  sku: string
  price: number
}

export interface UpdateProductData extends Partial<CreateProductData> {}

This structure provides a clear, scalable foundation for organizing code while maintaining consistency and developer productivity.