Doramagic Project Pack · Human Manual

nocobase

Related topics: System Architecture, Plugin System, AI Integration

Overview

Related topics: System Architecture, Plugin System, AI Integration

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Components

Continue reading this section for the full explanation and source context.

Section Schema Component Architecture

Continue reading this section for the full explanation and source context.

Section Schema Initializer

Continue reading this section for the full explanation and source context.

Related topics: System Architecture, Plugin System, AI Integration

Overview

NocoBase is an open-source NoCode/LowCode platform that enables users to build scalable business applications through a visual interface without writing code. It provides a comprehensive system for creating data models, designing user interfaces, configuring business workflows, and extending functionality through a plugin-based architecture.

Architecture Overview

NocoBase follows a modern full-stack architecture with clear separation between client and server components. The platform is built on a plugin-based architecture that allows for flexible extension and customization.

graph TD
    Client["Client (React)"]
    Server["Server (Node.js)"]
    Database["Database"]
    Client --> Server
    Server --> Database
    
    subgraph Client
        UI["UI Components"]
        Schema["Schema System"]
        Variables["Variable System"]
        PM["Plugin Manager"]
    end
    
    subgraph Server
        API["API Layer"]
        FlowEngine["Flow Engine"]
        Plugins["Plugin System"]
    end
    
    subgraph Plugins
        Mobile["Mobile Plugin"]
        AI["AI Plugin"]
        ThemeEditor["Theme Editor Plugin"]
    end

Core Components

ComponentDescriptionLocation
Schema SystemDeclarative UI and data structure definitionpackages/core/client/src/schema-component/
Flow EngineBusiness workflow execution enginepackages/core/flow-engine/
Plugin ManagerDynamic plugin loading and managementpackages/core/client/src/pm/
Variable SystemRuntime variable resolution and contextpackages/core/client/src/variables/
Schema InitializerVisual block insertion and configurationpackages/core/client/src/schema-initializer/
Schema SettingsConfiguration panel for schema blockspackages/core/client/src/schema-settings/

Sources: packages/core/client/src/schema-component/index.md:1

Data Model Architecture

NocoBase uses a schema-based approach for defining data models and user interfaces. Collections represent database tables, and fields define the structure of data entries.

graph LR
    Collection["Collection<br/>(Data Model)"]
    Field["Field<br/>(Column Definition)"]
    Association["Association<br/>(Relationship)"]
    Schema["Schema<br/>(UI Configuration)"]
    
    Collection --> Field
    Collection --> Association
    Schema --> Collection

The system supports multiple data types and associations, enabling complex business data modeling scenarios.

Sources: packages/core/client/src/schema-component/antd/association-select/index.md:1

User Interface System

Schema Component Architecture

The UI in NocoBase is built using a Schema-based Component System. Each UI element is defined through a schema configuration that describes its type, properties, and behavior.

#### Built-in Components

NocoBase provides several built-in components ready for use:

ComponentPurposeLocation
GeneralSchemaDesignerMain schema designer wrapperpackages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx
LinkageFilterFrontend linkage rules and condition configurationpackages/core/client/src/schema-component/antd/linkageFilter/index.md
AssociationSelectData selection linked to collections and fieldspackages/core/client/src/schema-component/antd/association-select/index.md

#### Schema Designer Features

The schema designer provides visual editing capabilities for:

  • Drag and Drop: Rearrange schema blocks within the interface
  • Designable Toggle: Switch between view and edit modes
  • Initializer Integration: Insert new schema blocks dynamically
  • Settings Panel: Configure properties of selected blocks
graph TD
    User["User"] --> Designer["Schema Designer"]
    Designer --> Drag["Drag & Drop"]
    Designer --> Initializer["Schema Initializer"]
    Designer --> Settings["Schema Settings"]
    
    Drag --> Block1["Block 1"]
    Drag --> Block2["Block 2"]
    Initializer --> Block3["New Block"]
    Settings --> Config["Configuration"]

Sources: packages/core/client/src/schema-component/index.md:1

Schema Initializer

The Schema Initializer enables dynamic insertion of schema blocks into the design canvas. It supports:

  • Built-in Types: Pre-configured component templates
  • Dynamic Visibility: Show/hide items based on conditions
  • Dynamic Children: Load child items on demand
  • Insert Schema: Insert complete schema structures including actions and form items

Sources: packages/core/client/src/schema-initializer/index.md:1

Variable System

Variables provide dynamic data context for formulas, conditions, and display values throughout the application. NocoBase includes a comprehensive built-in variable system.

Built-in Variables

VariableDescriptionType
$dateCurrent date (deprecated, use $nDate)DateTime
$nDateCurrent date in ISO formatDateTime
$nExactDateExact current datetimeDateTime
$systemSystem context with now() function (deprecated)Object
$nRoleCurrent user's role informationObject
$nUserCurrent authenticated user detailsObject
currentTimeCurrent timestamp (deprecated)String
URL ParametersQuery string variablesVarious

Variable Resolution Flow

graph LR
    Request["Request Context"]
    Resolver["Variable Resolver"]
    Context["Context Variables"]
    Output["Resolved Values"]
    
    Request --> Resolver
    Context --> Resolver
    Resolver --> Output

Variables are evaluated at runtime and support context-dependent values from:

  • Current user session
  • Current role permissions
  • URL query parameters
  • Environment variables
  • Date/time calculations

Sources: packages/core/client/src/variables/hooks/useBuiltinVariables.ts:1

Plugin System

NocoBase adopts a plugin-first architecture. All features are implemented as plugins that can be dynamically loaded, enabled, disabled, and configured.

Plugin Manager

The Plugin Manager (pm) handles plugin lifecycle operations:

OperationDescription
InstallAdd new plugin to the system
UninstallRemove plugin from the system
EnableActivate plugin functionality
DisableDeactivate plugin without removal
ConfigureManage plugin-specific settings
graph TD
    PM["Plugin Manager"]
    Store["Plugin Store"]
    Loader["Plugin Loader"]
    Registry["Plugin Registry"]
    
    PM --> Store
    PM --> Loader
    PM --> Registry
    Loader --> Plugin["Plugin Instance"]
    Registry --> Plugin

Plugin Detail View

Each plugin displays comprehensive information:

  • Package Name: Unique plugin identifier
  • Version: Semantic version number
  • Description: Plugin functionality summary
  • Homepage: Documentation or project URL
  • Author: Plugin maintainer information
  • License: Legal usage terms
  • Dependencies: Compatibility check with core system

Sources: packages/core/client/src/pm/PluginDetail.tsx:1

Available Plugin Categories

CategoryExamplesPurpose
Mobile@nocobase/plugin-mobileMobile-specific UI and navigation
AI@nocobase/plugin-aiAI-powered features and assistants
Theme@nocobase/plugin-theme-editorVisual theme customization
WorkflowFlow EngineBusiness process automation

Mobile Support

The Mobile plugin provides responsive interfaces and navigation optimized for mobile devices.

Desktop Mode

When accessing mobile pages from a desktop browser, the DesktopMode component renders a responsive wrapper:

<DesktopMode>
  <Mobile />
</DesktopMode>

Page Types

Page TypeDescription
Home PageDefault landing page; redirects to first route if not configured
NotFound Page404 error page for unmatched routes
Custom PagesUser-defined pages with custom components

#### Home Page Modes

  • Basic: Default empty home page
  • Custom Home: User-defined home page component
  • No Routes: Configuration without any routes

Sources: packages/plugins/@nocobase/plugin-mobile/src/client/pages/index.md:1

Mobile Navigation

The MobileTabBar component provides tab-based navigation with Bar.Item elements:

graph LR
    TabBar["MobileTabBar"]
    BarItem["Bar.Item"]
    Link["Link Component"]
    
    TabBar --> BarItem
    BarItem --> Link
    Link --> Route["Route Path"]

#### Link Types

TypeDescription
Inner LinkNavigate to internal application routes
Outer PageLink to external URLs
SelectedDisplay currently active/selected state

Sources: packages/plugins/@nocobase/plugin-mobile/src/client/mobile-layout/index.md:1

Workflow Engine

The Flow Engine (flow-engine) provides a visual workflow execution environment for business process automation.

Flow Settings

Flows can be configured with custom interfaces and behaviors:

SettingDescription
titleDisplay name for the flow
descriptionHuman-readable flow description
footerCustomizable footer with buttons
onCancelCallback when cancel is triggered
onSavedCallback when configuration is saved

#### Footer Configuration Options

  • Default: Use system-provided buttons
  • Wrap: Add custom content around origin buttons
  • Functional: Completely replace with custom composition
  • Hidden: Set to null to hide footer entirely
// Wrap existing buttons
footer: (originNode, { OkBtn, CancelBtn }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
    <span>Additional info</span>
    {originNode}
  </div>
)

// Hide footer
footer: null

Sources: packages/core/flow-engine/src/flowSettings.ts:1

AI Integration

The AI plugin (@nocobase/plugin-ai) extends NocoBase with artificial intelligence capabilities.

Chat Messages Store

AI features utilize a state management system for chat interactions:

graph TD
    ChatStore["ChatMessages Store"]
    Messages["messages[]"]
    Attachments["attachments[]"]
    Context["contextItems[]"]
    System["systemMessage"]
    
    ChatStore --> Messages
    ChatStore --> Attachments
    ChatStore --> Context
    ChatStore --> System

#### Store Actions

ActionPurpose
setMessagesReplace all messages
addMessageAppend single message
addMessagesAppend multiple messages
updateLastMessageModify most recent message
removeMessageDelete message by key
setAttachmentsUpdate file attachments
addContextItemsAdd context items with deduplication
setSystemMessageUpdate system prompt

#### Datasource Management

AI features support multiple data sources with configuration:

  • Collection: Target collection reference
  • Limit: Maximum records to retrieve
  • Description: Data source purpose documentation

Sources: packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/chatbox/stores/chat-messages.ts:1

Documentation Tools

The AI plugin includes tools for reading and navigating documentation:

graph LR
    Input["Module Key Input"]
    Parser["Path Parser"]
    Resolver["Path Resolver"]
    Output["File/Directory Content"]
    
    Input --> Parser
    Parser --> Resolver
    Resolver --> Output

Key functions:

  • normalizeModuleKey: Validates and normalizes module identifiers
  • resolveDocPath: Maps module keys to absolute file paths
  • Documentation entries include both files and subdirectories with hierarchical structure

Sources: packages/plugins/@nocobase/plugin-ai/src/server/tools/docs.ts:1

Frontend Utilities

CSS Module Resolution

Utility functions support frontend asset handling:

FunctionPurpose
isCssFile(url)Determines if a URL points to a CSS file

The function handles:

isCssFile('style.css')        // true
isCssFile('style.css?v=123')   // true
isCssFile('style.css#section') // true
isCssFile('script.js')         // false

Sources: packages/core/flow-engine/src/utils/resolveModuleUrl.ts:1

Technology Stack

LayerTechnologyPurpose
Frontend FrameworkReactUI component rendering
State ManagementZustandLightweight state management
UI LibraryAnt DesignPre-built component library
Backend RuntimeNode.jsServer-side execution
DatabaseMultiple (via ORM)Data persistence
Package ManagerMonorepo (npm workspaces)Code organization

Key Design Principles

  1. Schema-Driven: All configurations are declarative schema definitions
  2. Plugin-First: Every feature is a plugin with isolated scope
  3. Visual Configuration: No-code interfaces for common operations
  4. Code Extension: Low-code escape hatch for custom requirements
  5. Dynamic Loading: Runtime plugin activation without full reload

Documentation Structure

The NocoBase documentation is organized as follows:

docs/
├── README.md                 # Documentation index
├── docs/
│   └── en/                   # English documentation
│       └── index.md          # Entry point
├── packages/
│   └── plugins/              # Plugin-specific docs
└── README.md                 # Root documentation

Sources: docs/README.md:1

Getting Started

To begin working with NocoBase:

  1. Understand the Architecture: Familiarize yourself with the plugin-based structure
  2. Define Data Models: Create collections and configure fields in the admin interface
  3. Design UI Schemas: Use the schema designer to build application interfaces
  4. Configure Workflows: Set up automation using the flow engine
  5. Extend with Plugins: Add custom functionality through the plugin system

Sources: packages/core/client/src/schema-component/index.md:1

System Architecture

Related topics: Overview, Plugin System, Deployment

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Data Model-Driven Approach

Continue reading this section for the full explanation and source context.

Section Plugin-Based Extensibility

Continue reading this section for the full explanation and source context.

Section Plugin Categories

Continue reading this section for the full explanation and source context.

Related topics: Overview, Plugin System, Deployment

System Architecture

Overview

NocoBase is an open-source AI + no-code platform designed for building business systems rapidly. The platform adopts a data model-driven architecture that separates data structure from user interface, enabling unlimited possibilities for application development. Sources: README.md:1

The architecture is built with plugin-first extensibility at its core, allowing developers and AI agents to extend functionality without modifying the core codebase. This design philosophy enables organizations to adapt quickly to changing business requirements while maintaining system stability and performance. Sources: packages/plugins/@nocobase/plugin-data-source-main/README.md:1

Core Architectural Principles

Data Model-Driven Approach

Unlike traditional form or table-driven platforms, NocoBase implements a data model-driven approach that decouples UI and data structure completely. This architectural decision provides several key advantages:

CharacteristicTraditional PlatformsNocoBase Architecture
UI-Data CouplingTightly coupledFully decoupled
Interface FlexibilityLimited to table/form viewsUnlimited block types
Data Source SupportMain database onlyMain DB, external DBs, third-party APIs
Multiple ViewsOne view per entityMultiple blocks for same table/record

Sources: packages/plugins/@nocobase/plugin-form-drafts/README.md:1-15

Plugin-Based Extensibility

The entire NocoBase system is constructed as a collection of plugins. This modular architecture allows:

  • Selective Feature Loading: Only required plugins are loaded, reducing footprint
  • Independent Updates: Plugins can be updated without affecting core functionality
  • Hot Module Replacement: Plugins can be enabled/disabled at runtime
  • AI Integration: AI employees can programmatically interact with any plugin
    A[NocoBase Core] --> B[Plugin System]
    B --> C[Data Source Plugins]
    B --> D[UI Block Plugins]
    B --> E[Workflow Plugins]
    B --> F[AI Agent Plugins]
    C --> G[Main Database]
    C --> H[External Databases]
    C --> I[Third-party APIs]

Sources: packages/plugins/@nocobase/plugin-data-source-main/README.md:1-10

System Components

Plugin Categories

NocoBase organizes its functionality into distinct plugin categories based on responsibility:

CategoryPurposeExample Plugins
Data ManagementHandle data operations and storageplugin-data-source-main
User InterfaceProvide UI components and blocksplugin-mobile, plugin-block-workbench
Workflow AutomationManage business processesplugin-workflow-manual, plugin-workflow-notification
System UtilitiesCore system featuresplugin-audit-logs, plugin-verification
AI IntegrationEnable AI capabilitiesplugin-ai

Database Layer

The database layer in NocoBase supports multiple data source types through a unified abstraction:

  • Main Database: Primary storage engine (configurable type)
  • External Databases: Direct connections to external SQL databases
  • Third-party APIs: REST/GraphQL API integrations as data sources

Sources: packages/plugins/@nocobase/plugin-data-source-main/README.md:1-12

    A[Application Layer] --> B[Data Source Abstraction]
    B --> C[Main Database Engine]
    B --> D[External DB Connectors]
    B --> E[API Connectors]
    C --> F[SQL Translation Layer]
    D --> F
    E --> F
    F --> G[Query Optimization]

User Interface Architecture

NocoBase provides a flexible UI system that supports both desktop and mobile clients:

#### Desktop Client

The desktop client (packages/core/client) implements a schema-driven UI system where:

  • Components are defined as schemas
  • UI blocks are composed declaratively
  • Schema settings control component behavior

Sources: packages/plugins/@nocobase/plugin-mobile/README.md:1-8

#### Mobile Client

The mobile plugin provides:

  • Mobile-optimized page layouts
  • Responsive design support
  • Native-like navigation patterns
  • Mobile-specific UI components
    A[Client Request] --> B{Router}
    B -->|Desktop| C[Desktop UI Renderer]
    B -->|Mobile| D[Mobile UI Renderer]
    C --> E[Schema Component Tree]
    D --> F[Mobile Page Layouts]
    E --> G[Block Designer]
    F --> G

Sources: packages/plugins/@nocobase/plugin-mobile/README.md:1-15

Workflow System Architecture

Plugin-Based Workflows

NocoBase implements workflows as plugins, enabling:

  • Manual Triggers: User-initiated workflow execution
  • Automated Triggers: Event-based workflow activation
  • Notification System: Multi-channel alert delivery
  • Dynamic Calculation: Runtime computation within workflows

Sources: packages/plugins/@nocobase/plugin-workflow-manual/README.md:1-10

Workflow Components

ComponentFunctionPlugin
TriggerInitiates workflow executionplugin-workflow-manual
ActionsPerform operationsCore system
ConditionsControl flow logicCore system
NotificationsSend alertsplugin-workflow-notification
CalculationsCompute valuesplugin-workflow-dynamic-calculation
    A[Workflow Start] --> B{Trigger Type}
    B -->|Manual| C[User Action]
    B -->|Automated| D[Event Listener]
    C --> E[Condition Evaluation]
    D --> E
    E -->|True| F[Execute Actions]
    E -->|False| G[Skip Workflow]
    F --> H{Notification?}
    H -->|Yes| I[Send Notification]
    H -->|No| J[Continue Actions]
    I --> K[Workflow Complete]
    J --> K
    G --> K

Audit and Logging Architecture

The audit logs plugin (plugin-audit-logs) captures comprehensive system activity:

  • Data Changes: All database modifications
  • User Actions: User interactions with the system
  • System Events: Server-side operations
  • Access Patterns: Authentication and authorization events

Sources: packages/plugins/@nocobase/plugin-audit-logs/README.md:1-12

AI Integration Architecture

NocoBase integrates AI capabilities through a dedicated AI plugin system:

AI Employee System

Unlike standalone AI implementations, NocoBase allows embedding AI capabilities seamlessly into:

  • Interfaces: AI-powered form components and data displays
  • Workflows: AI-driven decision making and automation
  • Business Logic: Custom AI agents for domain-specific tasks
  • Data Operations: Intelligent data processing and analysis
    A[AI Plugin System] --> B[AI Employees]
    A --> C[Prompt Templates]
    A --> D[Model Adapters]
    B --> E[Business Interfaces]
    B --> F[Workflow Integration]
    B --> G[Data Processing]
    C --> H[System Context]
    D --> I[LLM Providers]
    E --> J[User Interface]
    F --> K[Automation Engine]
    G --> L[Data Layer]

Sources: packages/plugins/@nocobase/plugin-data-source-main/README.md:1-8

Extensibility Patterns

Plugin Development

Developers can extend NocoBase by creating custom plugins:

  1. Plugin Structure: Each plugin is a self-contained module
  2. Dependency Management: Plugins can depend on other plugins
  3. Lifecycle Hooks: Initialization, activation, and deactivation
  4. Schema Extension: Custom schema types and components
    A[Custom Plugin] --> B[Plugin Manifest]
    A --> C[Server Code]
    A --> D[Client Code]
    A --> E[Resources]
    B --> F[Plugin Metadata]
    B --> G[Dependencies]
    C --> H[Database Models]
    C --> I[API Routes]
    C --> J[Services]
    D --> K[UI Components]
    D --> L[Schema Definitions]
    D --> M[State Management]

Schema-Driven UI

The schema system allows declarative UI definition:

Schema TypePurposeExtensibility
FieldData display/inputCustom field types
BlockLayout containersCustom block types
ActionUser interactionsCustom action handlers
SelectorData filteringCustom filter types

System Requirements and Deployment

Database Support

NocoBase supports multiple database engines:

DatabaseStatusNotes
PostgreSQLFull SupportRecommended for production
MySQLFull SupportWide compatibility
SQLiteDevelopment OnlyLimited concurrent access
OthersVia External DB PluginAPI-based connectivity

Runtime Requirements

  • Node.js: v18+ required
  • Package Manager: npm or yarn
  • Memory: Minimum 2GB RAM for development
  • Storage: Varies by database and data volume

Architectural Benefits

Scalability

  • Horizontal Scaling: Stateless server design enables load balancing
  • Vertical Scaling: Efficient resource utilization supports larger deployments
  • Plugin Isolation: Prevents resource contention between features

Maintainability

  • Modular Design: Each plugin can be developed and tested independently
  • Clear Boundaries: Well-defined interfaces between components
  • Version Management: Plugins maintain their own version history

Flexibility

  • Multiple Data Sources: Connect to various databases and APIs
  • Custom UI: Schema-driven interface allows infinite combinations
  • AI Integration: Built-in support for AI-augmented functionality

Summary

NocoBase's system architecture is designed around three fundamental principles:

  1. Data Model Centrality: The data model drives all application behavior, not forms or tables
  2. Plugin-Based Extensibility: Every feature is a plugin that can be added, removed, or customized
  3. AI Integration: AI capabilities are first-class citizens integrated throughout the system

This architecture enables organizations to build sophisticated business applications rapidly while maintaining the flexibility to adapt to changing requirements. The separation of concerns between data, logic, and presentation layers ensures that changes in one area do not cascade into others, resulting in a maintainable and scalable system.

Sources: packages/plugins/@nocobase/plugin-form-drafts/README.md:1-15

Deployment

Related topics: Cluster Mode, System Architecture

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Docker Deployment (Recommended)

Continue reading this section for the full explanation and source context.

Section Database Support

Continue reading this section for the full explanation and source context.

Section Docker Architecture

Continue reading this section for the full explanation and source context.

Related topics: Cluster Mode, System Architecture

Deployment

NocoBase provides flexible deployment options to accommodate various infrastructure requirements and operational preferences. The platform supports containerized deployment via Docker, traditional server deployment, and development-focused installations.

Overview

NocoBase is designed as a headless CMS with an API-first architecture. The application server exposes REST and GraphQL APIs, while the admin client is a separate SPA (Single Page Application). This separation allows for flexible deployment strategies where the server and client can be scaled independently.

Deployment Methods

Docker deployment is the recommended approach for production environments. It provides the easiest setup with no-code requirements and simplified maintenance through image updates.

Minimal Quick Start:

npm install -g @nocobase/cli@beta
mkdir my-nocobase && cd my-nocobase
nb init --ui

Sources: README.md:8-13

Database Support

NocoBase supports multiple database backends. Each database type has a dedicated Docker Compose configuration:

DatabaseConfiguration FileUse Case
PostgreSQLdocker/app-postgres/docker-compose.ymlProduction, enterprise scale
MySQLdocker/app-mysql/docker-compose.ymlProduction, wide compatibility
MariaDBdocker/app-mariadb/docker-compose.ymlProduction, MySQL fork
SQLitedocker/app-sqlite/docker-compose.ymlDevelopment, small deployments

Sources: docker/app-postgres/docker-compose.yml, docker/app-mysql/docker-compose.yml

Docker Architecture

graph TD
    A[Client Browser] -->|HTTPS| B[NocoBase Application]
    B -->|API Requests| C[API Server :13000]
    B -->|Static Assets| D[Admin SPA :13000]
    C --> E[(PostgreSQL<br/>MySQL<br/>MariaDB)]
    C --> F[(SQLite)]
    E --> G[Uploaded Files<br/>/uploads]
    F --> G

Docker Configuration

Main Dockerfile

The primary Dockerfile (docker/nocobase/Dockerfile) builds the NocoBase application image. It uses a multi-stage build process to:

  1. Install dependencies
  2. Build the application
  3. Create an optimized production image

Environment Variables

Key environment variables for Docker deployment:

VariableDescriptionDefault
APP_KEYApplication encryption keyGenerated on first run
DB_DIALECTDatabase type (postgres, mysql, sqlite)postgres
DB_HOSTDatabase hostdb
DB_PORTDatabase port5432 / 3306
DB_DATABASEDatabase namenocobase
DB_USERDatabase usernamenocobase
DB_PASSWORDDatabase passwordnocobase
API_PORTAPI server port13000

Docker Compose Services

Typical Docker Compose configuration includes:

services:
  app:
    image: nocobase/app:latest
    ports:
      - "13000:13000"
    environment:
      - DB_DIALECT=postgres
      - DB_HOST=db
      - DB_PORT=5432
    volumes:
      - ./uploads:/app/uploads
    depends_on:
      - db

  db:
    image: postgres:15
    environment:
      - POSTGRES_DB=nocobase
      - POSTGRES_USER=nocobase
      - POSTGRES_PASSWORD=nocobase
    volumes:
      - db_data:/var/lib/postgresql/data

volumes:
  db_data:

Production Deployment

Prerequisites

For production deployments, ensure:

  1. Reverse Proxy: Configure nginx or similar for SSL termination
  2. Database: Use PostgreSQL or MySQL for production workloads
  3. Storage: Configure persistent storage for uploaded files
  4. Environment: Set secure APP_KEY in production

Deployment Checklist

ItemPriorityDescription
SSL CertificateRequiredEnable HTTPS for production
Database BackupRequiredConfigure automated backups
APP_KEY ConfigurationRequiredUse unique, secure key
Environment VariablesRequiredSet production values
Upload StorageRequiredConfigure persistent storage
MonitoringRecommendedSet up application monitoring
Log ManagementRecommendedConfigure centralized logging

Sources: docs/docs/en/get-started/deployment/production.md

Production Reverse Proxy Configuration

server {
    listen 80;
    server_name your-domain.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name your-domain.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    client_max_body_size 100M;

    location / {
        proxy_pass http://localhost:13000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_cache_bypass $http_upgrade;
    }

    location /uploads/ {
        alias /path/to/uploads/;
        expires 7d;
        add_header Cache-Control "public, immutable";
    }
}

Installation Methods Comparison

MethodBest ForCode WritingUpgrade ProcessDevelopment
DockerProduction, no-codeNoPull image, restartLimited
create-nocobase-appBusiness projectsYes (low-code)Rebuild projectFull
Git CloneContributing, latestYesGit pullFull

Sources: README.md:18-33

Upgrading

Docker Upgrades

For Docker deployments, upgrading involves:

# Pull latest image
docker pull nocobase/app:latest

# Restart container
docker-compose down
docker-compose up -d

Database Migration

NocoBase automatically runs database migrations on startup. Ensure:

  1. Database backup before upgrade
  2. Sufficient downtime window for migration
  3. Rollback plan if migration fails

File Structure Reference

├── docker-compose.yml          # Main compose file
├── Dockerfile                  # Legacy Dockerfile
├── docker/
│   ├── nocobase/
│   │   └── Dockerfile         # Modern app Dockerfile
│   ├── app-postgres/
│   │   └── docker-compose.yml
│   ├── app-mysql/
│   │   └── docker-compose.yml
│   ├── app-mariadb/
│   │   └── docker-compose.yml
│   └── app-sqlite/
│       └── docker-compose.yml
└── uploads/                   # User uploads directory

Troubleshooting

Common Issues

IssueSolution
Container won't startCheck environment variables and volume permissions
Database connection failedVerify DB_HOST, DB_PORT, and credentials
File upload failsCheck uploads directory permissions and size limits
Slow performanceIncrease memory limits, enable caching

Health Check

NocoBase provides health check endpoint at the root path:

curl http://localhost:13000/

A successful response indicates the application is running correctly.

Next Steps

Sources: README.md:8-13

Plugin System

Related topics: Plugin Development, Data Modeling, Workflow Engine

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Components

Continue reading this section for the full explanation and source context.

Section Plugin Detail Display

Continue reading this section for the full explanation and source context.

Section Dependencies Compatibility Check

Continue reading this section for the full explanation and source context.

Related topics: Plugin Development, Data Modeling, Workflow Engine

Plugin System

Overview

NocoBase implements a modular plugin-based architecture that enables developers to extend core functionality without modifying the framework's source code. Plugins in NocoBase are self-contained packages that can add new features, customize existing behavior, and integrate with external services.

The plugin system provides a unified mechanism for both server-side and client-side extensions, allowing developers to hook into application lifecycle events, register custom components, define database schemas, and expose APIs.

Architecture

    subgraph Core["NocoBase Core"]
        PM[Plugin Manager]
        ER[Event Router]
        SM[Schema Manager]
    end
    
    subgraph PluginTypes["Plugin Types"]
        SP[Server Plugin]
        CP[Client Plugin]
        FP[Full-Stack Plugin]
    end
    
    subgraph Lifecycle["Lifecycle Phases"]
        LOAD[Load]
        BOOT[Boot]
        MOUNT[Mount]
        ACTIVE[Active]
    end
    
    PM -->|manages| SP
    PM -->|manages| CP
    PM -->|manages| FP
    SP --> LOAD
    CP --> LOAD
    FP --> LOAD
    LOAD --> BOOT
    BOOT --> MOUNT
    MOUNT --> ACTIVE

Plugin Manager

The Plugin Manager (PluginManagerLink.tsx) handles the registration and lifecycle of all plugins within the application.

Core Components

ComponentFilePurpose
PluginDetailpackages/core/client/src/pm/PluginDetail.tsxDisplays plugin metadata and dependency information
PluginManagerLinkpackages/core/client/src/pm/PluginManagerLink.tsxProvides UI navigation to plugin settings
SchemaToolbarpackages/core/client/src/schema-settings/GeneralSchemaDesigner.tsxEnables schema-based plugin configuration

Plugin Detail Display

The PluginDetail component renders comprehensive information about installed plugins:

<Typography.Title level={3}>{plugin.packageName}</Typography.Title>
<Space split={<span>&nbsp;•&nbsp;</span>}>
  <span>{plugin.version}</span>
</Space>
<Tabs
  style={{ minHeight: '50vh' }}
  items={tabItems}
  defaultActiveKey={!plugin.isCompatible ? 'dependencies' : undefined}
/>

Sources: packages/core/client/src/pm/PluginDetail.tsx

Dependencies Compatibility Check

Plugins validate their dependencies through the compatibility checking system:

{data?.data?.depsCompatible === false ? (
  <Typography.Text type="danger">
    {t('`dist/externalVersion.js` not found or failed to `require`. Please rebuild this plugin.')}
  </Typography.Text>
) : (
  <>
    {!data?.data?.['isCompatible'] && (
      <Alert
        showIcon
        type={'error'}
        message={t('Plugin dependencies check failed, you should change the dependent version to meet the version requirements.')}
      />
    )}
    <Table
      style={{ marginTop: theme.margin }}
      rowKey={'name'}
      pagination={false}
      columns={dependenciesCompatibleTableColumns}
      dataSource={data?.data?.depsCompatible}
    />
  </>
)}

Sources: packages/core/client/src/pm/PluginDetail.tsx

Plugin Settings Management

Settings Menu Integration

The PluginManagerLink component integrates with the application settings menu:

const settingItems = useMemo(() => {
  const pinnedSettings = app.pluginSettingsManager
    .getPinnedSettings()
    .filter((setting) => setting.snippet !== false)
    .map((setting) => {
      return {
        key: setting.name,
        icon: setting.icon,
        label: setting.link ? (
          <div onClick={() => window.open(setting.link)}>{compile(setting.title)}</div>
        ) : (
          <Link to={setting.path}>{compile(setting.title)}</Link>
        ),
      };
    });
  // ...
}, [app, t]);

Sources: packages/core/client/src/pm/PluginManagerLink.tsx

Mobile Layout Handling

Settings are hidden in mobile layouts:

const { isMobileLayout } = useMobileLayout();

if (isMobileLayout) {
  return null;
}

Sources: packages/core/client/src/pm/PluginManagerLink.tsx

Schema-Based Plugin Extensions

Schema Designer Integration

Plugins can extend the schema designer through the GeneralSchemaDesigner component:

<div className={'general-schema-designer-icons'}>
  <Space size={3} align={'center'}>
    {draggable && (
      <DragHandler>
        <DragOutlined role="button" aria-label={getAriaLabel('drag-handler')} />
      </DragHandler>
    )}
    {!disableInitializer &&
      (ctx?.InitializerComponent ? (
        <ctx.InitializerComponent {...initializerProps} />
      ) : (
        ctx?.renderSchemaInitializer?.(initializerProps)
      ))}
    {schemaSettingsExists ? (
      schemaSettingsRender(contextValue)
    ) : (
      <SchemaSettingsDropdown
        title={
          <MenuOutlined
            role="button"
            aria-label={getAriaLabel('schema-settings')}
            style={{ cursor: 'pointer', fontSize: 12 }}
          />
        }
        {...schemaSettingsProps}
      >
        {props.children}
      </SchemaSettingsDropdown>
    )}
  </Space>
</div>

Sources: packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx

Toolbar Components

The schema toolbar provides a unified interface for plugin-defined tools:

<div className={classNames('toolbar-icons', spaceWrapperClassName)} style={spaceWrapperStyle}>
  <Space size={3} align={'center'} className={spaceClassName} style={spaceStyle}>
    {dragElement}
    <RefreshComponentProvider refresh={refresh}>{initializerElement}</RefreshComponentProvider>
    {settingsElement}
  </Space>
</div>

Sources: packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx

Plugin Lifecycle

    A[Install] --> B[Load]
    B --> C[Configure]
    C --> D[Enable]
    D --> E[Boot]
    E --> F[Mount]
    F --> G[Disable]
    G --> H[Uninstall]

Flow Settings Integration

The flow engine demonstrates plugin extensibility through settings:

export class FlowSettings {
  public components: Record<string, any> = {};
  public scopes: Record<string, any> = {};
  private antdComponentsLoaded = false;
  public enabled: boolean;
  #forceEnabled = false; // Force enable state
}

Sources: packages/core/flow-engine/src/flowSettings.ts

Plugins can customize modal dialogs through the footer API:

footer?:
  | React.ReactNode
  | ((originNode: React.ReactNode, extra: { OkBtn: React.FC; CancelBtn: React.FC }) => React.ReactNode)
  | null;

Sources: packages/core/flow-engine/src/flowSettings.ts

Client-Side Plugin Components

Page Components

Mobile plugins extend the application through page components:

Page TypeDescription
Home PageDefault landing page with routing support
NotFound Page404 error handling
Desktop ModeDesktop layout wrapper for mobile content
<DesktopMode>
  <Mobile />
</DesktopMode>

Sources: packages/plugins/@nocobase/plugin-mobile/src/client/desktop-mode/index.md

Schema Initializer Extensions

Plugins extend schema initialization through:

### Insert schema
#### Basic
<code src="./demos/insert-schema-basic.tsx"></code>
#### Action
<code src="./demos/insert-schema-action.tsx"></code>
#### FormItem
<code src="./demos/insert-schema-form-item.tsx"></code>

Sources: packages/core/client/src/schema-initializer/index.md

Error Handling

Error Fallback Component

Plugins integrate with the error handling system through the ErrorFallback component:

<ErrorFallback
  error={error}
  info={info}
>
  <Result
    status="error"
    title={t('Render Failed')}
    subTitle={subTitle}
    extra={[
      <Button type="primary" key="feedback" href="https://github.com/nocobase/nocobase/issues" target="_blank">
        {t('Feedback')}
      </Button>,
      <Button key="log" loading={loading} onClick={download}>
        {t('Download logs')}
      </Button>,
    ]}
  />
</ErrorFallback>

Sources: packages/core/client/src/schema-component/antd/error-fallback/ErrorFallback.tsx

Plugin Package Structure

Directory/FilePurpose
src/server/Server-side plugin logic
src/client/Client-side React components
src/locale/Internationalization files
dist/Compiled distribution files
dist/externalVersion.jsVersion compatibility manifest

Built-in Variables System

Plugins can access built-in variables for dynamic content:

VariableContextDescription
$datedatetimeCtxCurrent date (deprecated)
$nExactDateexactDateTimeCtxPrecise timestamp
$nDatedatetimeCtxCurrent date
$systemnowSystem time (deprecated)
currentTime() => dayjsLegacy time variable

Sources: packages/core/client/src/variables/hooks/useBuiltinVariables.ts

Sources: packages/core/client/src/pm/PluginDetail.tsx

Data Modeling

Related topics: Plugin System, Interface Builder, Authentication and Permissions

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Database System

Continue reading this section for the full explanation and source context.

Section Dialect Support

Continue reading this section for the full explanation and source context.

Section Collection Management

Continue reading this section for the full explanation and source context.

Related topics: Plugin System, Interface Builder, Authentication and Permissions

Data Modeling

Overview

Data Modeling in NocoBase represents the foundational system for defining, organizing, and managing data structures within the application. It provides a comprehensive framework that enables users to create collections, define fields, establish relationships, and configure data sources through both programmatic APIs and user interfaces.

The data modeling system serves as the core abstraction layer that bridges the gap between application-level schema definitions and the underlying database infrastructure. It supports multiple database dialects and provides consistent data management capabilities across different storage backends.

Architecture

Core Database System

The Database class in NocoBase acts as the central orchestrator for all data modeling operations. It maintains several internal maps and registries that track collections, fields, models, and their relationships.

graph TD
    A[Database] --> B[Collections Map]
    A --> C[Repositories Map]
    A --> D[Operators Map]
    A --> E[Model-Collection Maps]
    A --> F[Query Interface]
    A --> G[Dialect Layer]
    B --> H[Collection Metadata]
    E --> I[Model-Collection Binding]
    E --> J[Model Name Mapping]
    E --> K[Table Name Mapping]

The database system initializes with the following key components:

ComponentTypePurpose
collectionsMap<string, Collection>Stores all registered collections by name
collectionsSortMap<string, number>Manages collection ordering/priority
repositoriesMap<string, RepositoryType>Caches repository instances
modelCollectionMap<ModelStatic, Collection>Binds model classes to collections
modelNameCollectionMapMap<string, Collection>Lookup by model name
tableNameCollectionMapMap<string, Collection>Lookup by table name
pendingFieldsMap<string, RelationField[]>Handles deferred field relations
interfaceManagerInterfaceManagerManages field type interfaces

Sources: packages/core/database/src/database.ts:26-45

Dialect Support

The database layer implements a dialect pattern through BaseDialect to support multiple database engines. The dialect system is registered statically and enables the framework to generate appropriate SQL syntax for different database backends.

graph LR
    A[Database] --> B[Dialect Abstraction]
    B --> C[PostgreSQL]
    B --> D[MySQL]
    B --> E[SQLite]
    B --> F[Other Engines]
    
    G[SQL Identifier Quoting] --> C
    G --> D
    G --> E
    G --> F

Sources: packages/core/database/src/database.ts:47-59

Collections

Collections are the primary units of data organization in NocoBase. They represent database tables and serve as containers for fields and their associated metadata.

Collection Management

The system provides multiple mechanisms for retrieving collections:

MethodDescription
getCollection(name)Retrieve collection by exact name
getRepository(name)Get repository instance for collection
getModel(name)Access the ORM model
tableNameCollectionMapLookup by database table name

The collection system supports template-based creation through the SchemaTemplateManagerProvider, which enables reusable collection schemas:

getTemplatesByCollection: useCallback(
  (dataSource: string, collectionName: string) => {
    const parentCollections = getInheritCollections(collectionName, dataSource);
    const totalCollections = parentCollections.concat([collectionName]);
    const items = templates?.filter?.(
      (template) =>
        (template.dataSourceKey || DEFAULT_DATA_SOURCE_KEY) === dataSource &&
        totalCollections.includes(template.collectionName),
    );
    return items || [];
  },
  [getInheritCollections, templates],
),

Sources: packages/core/client/src/schema-templates/SchemaTemplateManagerProvider.tsx:45-60

Collection Inheritance

Collections support inheritance through the InheritanceMap, allowing child collections to derive schema from parent collections. This enables hierarchical data modeling where common fields are defined once and inherited by specialized collections.

Fields

Fields define the structure and behavior of data within collections. Each field has a type, validation rules, and UI configurations.

Field Types

The system includes built-in field types and supports custom interface extensions:

CategoryDescription
Built-in TypesStandard field types provided by NocoBase
Custom InterfacesExtensible field type system
Relation FieldsReferences to other collections
Virtual FieldsComputed or derived fields

Fields can be configured with dynamic visibility and child elements:

// Dynamic visible & children
// Supports conditional display and dynamic loading of child fields

Sources: packages/core/client/src/schema-settings/index.md:15-17

Field Configuration

Fields support various configuration options including:

  • Display names and descriptions
  • Default values
  • Validation rules
  • UI components and templates
  • Access control permissions

Schema System

The schema system provides a declarative way to define UI and data structures. It integrates with collections to render appropriate interface components.

Schema Designer

The GeneralSchemaDesigner component provides the visual interface for editing schema configurations:

graph TD
    A[GeneralSchemaDesigner] --> B[Title Bar]
    A --> C[Drag Handler]
    A --> D[Initializer Component]
    A --> E[Schema Settings Dropdown]
    
    B --> F[Data Source Display]
    B --> G[Template Reference]
    
    D --> H[Dynamic Initializer]
    
    E --> I[Custom Settings Menu]

Sources: packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx:1-50

Schema Templates

Schema templates enable reusable component configurations:

MethodPurpose
getTemplateBySchemaIdFind template by schema UID
getTemplateByIdFind template by key
getTemplatesByComponentNameFilter by component type
getTemplatesByCollectionFilter by collection with inheritance

Sources: packages/core/client/src/schema-templates/SchemaTemplateManagerProvider.tsx:32-44

Data Sources

The system supports multiple data sources, allowing connections to different databases within a single application.

Data Source Manager

Data sources are managed through a dedicated configuration system that handles:

  • Connection configuration
  • Dialect-specific settings
  • SQL identifier quoting rules
  • Cross-database relationships

The quoting rules vary by database type and must be respected when generating SQL:

Quote SQL identifiers according to each data source's database type specified in <data_sources>.
- Convert camelCase names to snake_case for databases that use underscore naming

Sources: packages/plugins/@nocobase/plugin-ai/src/server/ai-employees/prompts.ts:15-20

Table Components

The system provides multiple table rendering modes for different use cases:

ModeUse Case
Table.VoidRead-only display without interaction
Table.RowSelectionSelectable rows for batch operations
Table.ArrayEditable array-based table

Sources: packages/core/client/src/schema-component/antd/table/index.md:1-14

Table Examples

The table component supports various configurations:

  • Basic void table display
  • Row selection with checkboxes
  • Array-based inline editing
  • Integrated action buttons

Workflow Integration

Data modeling integrates with the workflow engine through the FlowSettings system, which provides:

  • Custom variable definitions
  • Linkage rules configuration
  • Condition evaluation based on field values
  • Action triggers tied to data changes

The linkage rules system allows conditional logic based on collection fields:

// Condition evaluation structure
{
  condition: FilterGroup,
  actions: Action[]
}

Sources: packages/core/client/src/flow/actions/linkageRules.tsx:60-80

API Reference

Database Initialization

const database = new Database({
  dialect: 'postgres',
  // ... connection options
});

Collection Definition

database.collection({
  name: 'users',
  fields: [
    { type: 'string', name: 'name' },
    { type: 'hasMany', name: 'posts' },
  ],
});

Query Operations

MethodDescription
db.getCollection(name)Get collection instance
collection.repositoryAccess CRUD operations
collection.modelAccess ORM model

Summary

The Data Modeling system in NocoBase provides a comprehensive solution for defining and managing application data structures. It combines:

  1. Collection Management: Organize data into logical groupings
  2. Field Definition: Configure data attributes with types and validation
  3. Schema Templates: Enable reusable configurations
  4. Multi-Datasource Support: Connect to various database backends
  5. UI Integration: Seamless rendering through schema components
  6. Workflow Connection: Trigger actions based on data conditions

The architecture emphasizes extensibility through plugins, custom field interfaces, and dialect-specific optimizations.

Sources: packages/core/database/src/database.ts:26-45

Interface Builder

Related topics: Data Modeling, Workflow Engine, Plugin Development

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Concepts

Continue reading this section for the full explanation and source context.

Section Architecture Overview

Continue reading this section for the full explanation and source context.

Section Schema Properties

Continue reading this section for the full explanation and source context.

Related topics: Data Modeling, Workflow Engine, Plugin Development

Interface Builder

Overview

The Interface Builder is NocoBase's core visual configuration system that enables users to create and customize application interfaces through a schema-driven approach. It provides a declarative way to define UI components, their behaviors, and data relationships without requiring code modifications.

Core Concepts

The Interface Builder operates on a schema-based architecture where every UI element is defined through JSON schemas that describe:

  • Component type and properties
  • Data binding and field mappings
  • Action handlers and event callbacks
  • Styling and layout configurations
  • Conditional visibility rules

Architecture Overview

graph TD
    A[Interface Builder] --> B[Schema Settings]
    A --> C[Schema Initializers]
    A --> D[Schema Components]
    A --> E[Variables System]
    
    B --> B1[Built-in Types]
    B --> B2[Designer Context]
    
    C --> C1[Block Initializers]
    C --> C2[Field Initializers]
    C --> C3[Action Initializers]
    
    D --> D1[Form Components]
    D --> D2[Display Components]
    D --> D3[Action Components]
    
    E --> E1[System Variables]
    E --> E2[Custom Variables]
    E --> E3[Flow Variables]

Schema System

The schema system is the foundation of the Interface Builder. Schemas define the structure, behavior, and appearance of interface elements.

Schema Properties

PropertyTypeDescription
x-componentstringThe component to render
x-component-propsobjectComponent-specific props
x-decoratorstringWrapper component (e.g., FormItem)
x-decorator-propsobjectDecorator component props
x-designablebooleanEnable visual editing
x-hiddenbooleanHide the element
x-visibleexpressionConditional visibility

Basic Schema Example

{
  type: 'string',
  'x-component': 'Markdown',
  'x-decorator': 'FormItem',
  'x-component-props': {
    mode: 'sv',
    height: '82vh'
  }
}

Sources: packages/core/client/src/flow/flows/editMarkdownFlow.tsx

Schema Settings

Schema Settings provide configuration panels for customizing schema properties in design mode. They appear when users click the settings icon on schema elements.

Built-in Schema Settings

The system includes several built-in schema settings components:

ComponentPurpose
GeneralSchemaDesignerGeneral schema configuration
SchemaSettingsBase settings collection
SchemaSettingsDropdownDropdown menu for settings
SchemaToolbarToolbar for schema operations

Designer Toolbar

The schema designer toolbar provides quick access to common operations:

<SchemaToolbar 
  title="Block Title"
  showDataSource={true}
  draggable={true}
  designable={true}
/>

Sources: packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx

Toolbar Components

ComponentFunction
DragHandlerDrag handle for reordering
InitializerComponentInsert new elements
SchemaSettingsDropdownOpen settings panel

Toolbar Title Display

The toolbar displays hierarchical information when configured:

<span key={titleArr[0]} className={'toolbar-title-tag'}>
  {dataSource ? `${compile(dataSource?.displayName)} > ${titleArr[0]}` : titleArr[0]}
</span>

Schema Initializers

Schema Initializers define where and what elements can be inserted into the interface. They provide the "Add" functionality within design mode.

Initializer Types

#### Block Initializers

Block initializers add container-level components like tables, forms, and grids.

{
  type: 'array',
  title: '{{t("Blocks")}}',
  name: 'blockInitializers',
  children: [
    // Table block
    {
      title: '{{t("Table")}}',
      name: 'tableSelector',
      Component: TableSelectorInitializer
    },
    // Form block
    {
      title: '{{t("Form")}}',
      name: 'formItemInitializers',
      Component: FormItemInitializers
    }
  ]
}

#### Field Initializers

Field initializers add data fields to forms and tables.

{
  type: 'array',
  title: '{{t("Fields")}}',
  name: 'fieldInitializers',
  children: [
    {
      title: '{{t("Text")}}',
      name: 'text',
      Component: DateFormatInitializer
    }
  ]
}

Dynamic Visibility

Initializers can dynamically show or hide items based on context:

{
  'x-visible': '{{curdModel === "list"}}',
  children: [
    // Dynamic children
  ]
}

Schema Components

NocoBase provides a rich library of schema components for building interfaces.

Form Components

#### Markdown

A rich text editor supporting Markdown syntax.

interface MarkdownProps extends TextAreaProps {
  value?: string;
  onChange?: (value: string) => void;
  mode?: 'sv' | 'wysiwyg';
}
PropTypeDefaultDescription
mode`'sv' \'wysiwyg'`'sv'Editor mode
height`string \number`200Editor height
valuestring-Markdown content
onChangefunction-Change handler

Sources: packages/core/client/src/schema-component/antd/markdown/index.md

#### Markdown.Void

A void component for inline markdown editing.

interface MarkdownVoidProps extends Omit<TextAreaProps, 'onSubmit'> {
  defaultValue?: string;
  onSubmit?: (value: string) => void;
  onCancel?: (e: React.MouseEvent) => void;
}

Association Components

#### AssociationSelect

Select component for related data from specified tables.

type AssociationSelectProps<P = any> = RemoteSelectProps<P> & {
  action?: string;
  multiple?: boolean;
};
PropTypeDefaultDescription
actionstring'list'Data fetching action
multiplebooleanfalseEnable multi-select
type`'string' \'array'`'string'Value type
fieldNamesobject-Field name mappings

Sources: packages/core/client/src/schema-component/antd/association-select/index.md

Filter Components

#### LinkageFilter

Component for frontend linkage rules and condition configuration.

type FilterActionProps<T = {}> = ActionProps & {
  options?: any[];
  form?: Form;
  onSubmit?: (values: T) => void;
  onReset?: (values: T) => void;
}

Built-in Component Types

CategoryComponents
InputInput, TextArea, NumberPicker, Password
SelectSelect, Checkbox, Radio, Switch
DisplayMarkdown, Markdown.Void, LinkageFilter
AssociationAssociationSelect, RecordPicker
DateTimeDatePicker, TimePicker, DateRangePicker

Variables System

The Variables system provides dynamic data access within the Interface Builder, enabling context-aware functionality.

Variable Types

TypeLabelDescription
systemSystemBuilt-in system variables
currentUserCurrent UserLogged-in user information
currentRoleCurrent RoleCurrent user's role
dateNowDate NowCurrent timestamp
formFormForm values and state
recordRecordCurrent data record
variableCustom VariableUser-defined variables

Variable Table Structure

Variables are displayed in a structured table:

ColumnDescription
titleVariable display name
keyVariable identifier
typeVariable data type
actionsEdit and delete operations

Custom Variables

Custom variables can be created and managed in workflows:

{
  title: t('Custom Variables'),
  key: 'customVariables',
  type: 'object',
  children: [
    {
      title: variable.title,
      key: variable.key,
      type: variable.type
    }
  ]
}

Sources: packages/core/client/src/flow/actions/customVariable.tsx

Actions

Actions define user interactions and their corresponding behaviors within the Interface Builder.

Action Types

ActionDescription
submitSubmit form data
cancelCancel current operation
createCreate new record
updateUpdate existing record
deleteDelete record
customCustom action handler

Action Schema Configuration

{
  type: 'object',
  'x-component': 'Action',
  'x-component-props': {
    type: 'primary',
    icon: 'CheckOutlined'
  }
}

UI Mode Configuration

The UI Mode system allows customization of dialog and modal appearances.

footer: (originNode, { OkBtn, CancelBtn }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
    <span>Additional info</span>
    {originNode}
  </div>
)
OptionTypeDescription
nullnullHide footer
ReactNodeReactNodeStatic footer content
function(originNode, { OkBtn, CancelBtn }) => ReactNodeDynamic footer

Sources: packages/core/flow-engine/src/flowSettings.ts

Designer Context

The Designer Context provides runtime information and utilities for schema design mode.

Context Features

  • designable - Current design mode state
  • designerProps - Designer-specific properties
  • resources - Available schema resources
  • schema - Current schema instance
  • refresh - Refresh handler for data updates

Context Usage

const { designable, schema, refresh } = useDesigner();

if (designable) {
  return <DesignablePlugin {...props} />;
}

Integration with Flow Engine

The Interface Builder integrates with NocoBase's Flow Engine to provide workflow-driven interface behavior.

Flow Settings Integration

Flow settings can be embedded within schema components:

{
  type: 'object',
  'x-component': 'FlowSettings',
  properties: {
    content: {
      type: 'string',
      'x-component': 'Markdown',
      'x-component-props': {
        mode: 'sv'
      }
    }
  }
}

Default Parameters

Schemas can define default parameters for flows:

defaultParams: (ctx) => {
  return {
    content: ctx.t('{{t("Default content")}}'),
  };
}

Liquid Template Rendering

Variables support Liquid template syntax:

const result = await ctx.liquid.renderWithFullContext(content, ctx);

Mobile Interface Builder

NocoBase supports mobile-specific interface building through the mobile plugin.

Mobile Pages

PageDescription
Home PageApplication homepage
NotFound Page404 error page

Mobile Layout Components

ComponentDescription
MobileTabBarBottom navigation bar
MobileTabBar.ItemTab bar items
MobileTabBar.LinkLink navigation items

Desktop Mode

Mobile pages can be wrapped for desktop viewing:

<DesktopMode>
  <Mobile />
</DesktopMode>

Plugin Manager Integration

The Plugin Manager provides configuration UI for plugins built with the Interface Builder system.

Plugin Details Display

{
  key: 'info',
  label: t('Plugin Info'),
  children: (
    <>
      <Typography.Title level={3}>{plugin.packageName}</Typography.Title>
      <Tabs items={tabItems} />
    </>
  )
}

Dependency Compatibility

Plugin details include dependency compatibility checking:

{
  key: 'dependencies',
  label: t('Dependencies compatibility check'),
  children: (
    <DependenciesCheck status={data?.data?.depsCompatible} />
  )
}

Best Practices

Schema Organization

  1. Use meaningful name properties for schema identification
  2. Group related components under consistent parent schemas
  3. Leverage decorators (x-decorator) for common patterns

Performance Optimization

  1. Use x-hidden over conditional rendering for hidden elements
  2. Leverage designable flag to skip rendering logic in production
  3. Use void components for modal content

Accessibility

  1. Include aria-label on interactive elements
  2. Use proper heading hierarchy within schema blocks
  3. Ensure keyboard navigation support

See Also

Sources: packages/core/client/src/flow/flows/editMarkdownFlow.tsx

Workflow Engine

Related topics: Interface Builder, Plugin System, Authentication and Permissions

Section Related Pages

Continue reading this section for the full explanation and source context.

Section FlowContext Provider

Continue reading this section for the full explanation and source context.

Section ExecutionCanvas

Continue reading this section for the full explanation and source context.

Section FlowModelRenderer

Continue reading this section for the full explanation and source context.

Related topics: Interface Builder, Plugin System, Authentication and Permissions

Workflow Engine

Overview

The Workflow Engine is NocoBase's core system for designing, executing, and managing automated business processes. It provides a visual canvas-based interface where users can create workflows by connecting different node types, define triggers that initiate workflow execution, and configure custom variables for data transformation.

The engine is designed as a plugin (@nocobase/plugin-workflow) that integrates with the broader NocoBase platform, leveraging the flow-engine core module for rendering and execution logic.

Architecture

The Workflow Engine follows a provider-based architecture with clear separation between UI rendering and execution logic.

    A[Workflow Canvas] --> B[FlowContext Provider]
    B --> C[ExecutionCanvas Component]
    C --> D[CanvasContent Component]
    C --> E[JobModal Component]
    D --> F[FlowModelRenderer]
    F --> G[FlowModelProvider]
    G --> H[ErrorBoundary]
    F --> I[MemoFlowModelRenderer]

Core Components

FlowContext Provider

The FlowContext provides runtime data to all workflow-related components. It encapsulates the current workflow, nodes, execution context, and view state.

<FlowContext.Provider
  value={{
    workflow: workflow.type ? workflow : null,
    nodes,
    execution,
    viewJob,
    setViewJob,
  }}
>

Context Values:

PropertyTypeDescription
workflowWorkflowThe workflow configuration object
nodesNode[]Array of nodes in the workflow
executionExecutionCurrent execution instance
viewJob`Job \null`Job selected for detailed view
setViewJobFunctionCallback to update viewJob state

Sources: packages/plugins/@nocobase/plugin-workflow/src/client/ExecutionCanvas.tsx:21-28

ExecutionCanvas

The ExecutionCanvas is the main container component for viewing workflow executions. It renders the toolbar, status indicators, and delegates content rendering to child components.

Key Features:

  • Breadcrumb navigation to workflow details
  • Execution status badge with color coding
  • Cancel execution capability (when execution is not in terminal state)
  • Last updated timestamp display
<Breadcrumb
  items={[
    { title: <Link to={app.pluginSettingsManager.getRoutePath('workflow')}>{lang('Workflow')}</Link> },
    {
      title: (
        <Tooltip title={`Key: ${workflow.key}`}>
          <Link to={getWorkflowDetailPath(workflow.id)}>{workflow.title}</Link>
        </Tooltip>
      ),
    },
    { title: <ExecutionsDropdown /> },
  ]}
/>

Sources: packages/plugins/@nocobase/plugin-workflow/src/client/ExecutionCanvas.tsx:31-44

FlowModelRenderer

The FlowModelRenderer is the core rendering component that displays the workflow model with all connected nodes. It supports several configuration options:

Props:

PropTypeDefaultDescription
modelModelRequiredThe data model to render
showFlowSettingsbooleantrueWhether to show flow settings panel
flowSettingsVariantstringundefinedVisual variant for settings
hideRemoveInSettingsbooleanfalseHide remove button in settings
showTitlebooleantrueShow the model title
inputArgsany[][]Input arguments for the flow
showErrorFallbackbooleantrueShow error fallback UI
settingsMenuLevelstringundefinedSettings menu hierarchy level
extraToolbarItemsReactNodeundefinedAdditional toolbar content
fallbackReact.FCundefinedCustom fallback component
useCachebooleanfalseEnable render caching

Sources: packages/core/flow-engine/src/components/FlowModelRenderer.tsx:1-50

Memoization:

export const MemoFlowModelRenderer = React.memo(FlowModelRenderer);
MemoFlowModelRenderer.displayName = 'MemoFlowModelRenderer';

The component includes a memoized version (MemoFlowModelRenderer) that skips re-rendering when parent components re-render but props remain unchanged. This optimization does not affect internal reactive updates.

Sources: packages/core/flow-engine/src/components/FlowModelRenderer.tsx:110-112

CanvasContent

The CanvasContent component renders the actual workflow visualization including nodes, edges, and clipboard preview functionality.

Features:

  • Terminal node display (Start/End markers)
  • Clipboard preview for copied nodes
  • Zoom slider control
<div className="workflow-canvas-zoomer">
  <Slider vertical reverse defaultValue={100} step={10} min={10} value={zoom} onChange={setZoom} />
</div>

Sources: packages/plugins/@nocobase/plugin-workflow/src/client/CanvasContent.tsx:1-100

Flow Settings

The FlowSettings class manages flow configuration dialogs and their component registry.

export class FlowSettings {
  public components: Record<string, any> = {};
  public scopes: Record<string, any> = {};
  private antdComponentsLoaded = false;
  public enabled: boolean;
  #forceEnabled = false;
}

Sources: packages/core/flow-engine/src/flowSettings.ts:1-10

Flow settings support customizable footer content through a flexible API:

footer?:
  | React.ReactNode
  | ((originNode: React.ReactNode, extra: { OkBtn: React.FC; CancelBtn: React.FC }) => React.ReactNode)
  | null;

Footer Patterns:

PatternExample
DefaultPreserves original footer with Ok/Cancel buttons
OverlayAdd content above origin footer
ReplaceFull custom footer composition
HiddenSet footer: null to hide

Sources: packages/core/flow-engine/src/flowSettings.ts:1-30

Variables System

The workflow engine supports variable injection for data transformation between nodes.

Custom Variables Configuration

The customVariable.tsx file provides the UI for managing custom workflow variables:

Variable Properties:

PropertyData IndexDescription
TitletitleDisplay name for the variable
IdentifierkeyUnique key for referencing
TypetypeData type classification

Available Variable Types:

TypeLabelUsage
stringStringText data
numberNumberNumeric values
booleanBooleanTrue/false flags
arrayArrayList of values
objectObjectComplex structured data

Actions:

ActionIconDescription
EditEditOutlinedModify variable configuration
DeleteDeleteOutlinedRemove variable from workflow
render: (_: unknown, __: FlowVariable, index: number) => (
  <Space size={12} style={{ whiteSpace: 'nowrap' }}>
    <Button
      type="link"
      size="small"
      icon={<EditOutlined />}
      onClick={() => handleEdit(index)}
      disabled={disabled}
      title={t('Edit')}
    />
    <Button
      type="link"
      size="small"
      icon={<DeleteOutlined />}
      danger
      onClick={() => handleDelete(index)}
      disabled={disabled}
      title={t('Delete')}
    />
  </Space>
)

Sources: packages/core/client/src/flow/actions/customVariable.tsx:1-80

Execution States

The engine tracks execution status through a state machine:

    A[Created] --> B[Running]
    B --> C[Success]
    B --> D[Failed]
    B --> E[Cancelled]
    D --> F[Retry]
    F --> B

Status Options:

StatusColorDescription
RunningProcessingExecution in progress
SuccessSuccessCompleted successfully
FailedErrorExecution encountered an error
CancelledWarningExecution manually stopped

Sources: packages/plugins/@nocobase/plugin-workflow/src/locale/ko-KR.json:1-50

Trigger Points

Workflows can be triggered at various points in the application lifecycle:

TriggerDescription
After SavingTriggered after data save completes
After SubmittingTriggered after form submission succeeds
Before DeletingTriggered before deletion (local mode only)
Button ClickTriggered directly on button click without saving

Sources: packages/plugins/@nocobase/plugin-workflow/src/locale/ko-KR.json:50-100

Error Handling

The system implements multi-level error handling:

  1. ErrorBoundary Wrapper: Catches rendering errors around the FlowModelRenderer
  2. FlowModelProvider: Provides error context to child components
  3. FlowErrorFallback: Renders user-friendly error messages with recovery options
if (showErrorFallback) {
  return (
    <FlowModelProvider model={model}>
      <ErrorBoundary FallbackComponent={FlowErrorFallback}>{content}</ErrorBoundary>
    </FlowModelProvider>
  );
}

Sources: packages/core/flow-engine/src/components/FlowModelRenderer.tsx:85-92

Integration with Plugin System

The workflow plugin integrates with NocoBase's plugin manager through:

  • Route Registration: /workflow path for navigation
  • Settings Manager: app.pluginSettingsManager.getRoutePath('workflow')
  • Localization: Multi-language support via JSON locale files

Sources: packages/plugins/@nocobase/plugin-workflow/src/client/ExecutionCanvas.tsx:35

Summary

The Workflow Engine provides a comprehensive system for building and executing automated workflows within NocoBase. Key aspects include:

  • Visual Canvas: Drag-and-drop workflow design interface
  • Context-Based Architecture: React Context for global state management
  • Flexible Configuration: Customizable settings dialogs and footers
  • Variable System: Support for custom variables with type classification
  • Error Resilience: Built-in error boundaries and fallback components
  • Execution Tracking: Real-time status updates and execution history
  • Plugin Integration: Seamless integration with the NocoBase plugin ecosystem

Sources: packages/plugins/@nocobase/plugin-workflow/src/client/ExecutionCanvas.tsx:21-28

Authentication and Permissions

Related topics: Workflow Engine, Data Modeling, Plugin Development

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Authentication Plugin

Continue reading this section for the full explanation and source context.

Section Authentication Verification Flow

Continue reading this section for the full explanation and source context.

Section User Management

Continue reading this section for the full explanation and source context.

Related topics: Workflow Engine, Data Modeling, Plugin Development

Authentication and Permissions

Overview

NocoBase implements a comprehensive authentication and permissions system built on a plugin-based architecture. The system is designed to provide secure access control through multiple integrated plugins that handle user authentication, role-based access control (RBAC), and granular resource permissions.

Authentication System

Authentication Plugin

The @nocobase/plugin-auth plugin provides the core authentication capabilities for NocoBase. This plugin handles user identity verification, session management, and integrates with various authentication providers.

Authentication Verification Flow

The auth-verification system implements a multi-step verification process to ensure secure access to NocoBase resources.

graph TD
    A[Client Request] --> B{Authentication Required?}
    B -->|Yes| C[Auth Plugin Verification]
    B -->|No| G[Resource Access]
    C --> D{Credentials Valid?}
    D -->|Yes| E[Generate Session Token]
    D -->|No| F[Authentication Failed - 401]
    E --> G[Resource Access with Token]

User Management

The @nocobase/plugin-users plugin extends the authentication system by providing comprehensive user management capabilities. User records store essential identity information and serve as the basis for permission assignments.

Access Control List (ACL) System

ACL Plugin Architecture

The @nocobase/plugin-acl plugin implements NocoBase's Access Control List system, providing fine-grained permission management across collections, actions, and fields.

graph TD
    A[User Request] --> B{ACL Check}
    B --> C{Role Assigned?}
    C -->|No| D[Default Deny]
    C -->|Yes| E[Check Resource Permissions]
    E --> F{Action Allowed?}
    F -->|Yes| G[Execute Action]
    F -->|No| H[Permission Denied - 403]

Permission Model

NocoBase's permissions system follows a hierarchical structure:

Permission LevelScopeDescription
Collectioncollections:*Global collection access
Specific Collectioncollections:postsSingle collection access
Actioncollections:posts:*All actions on collection
Fieldfields:posts:titleSpecific field access
Resourceresources:postsResource-level permissions

Sources: docs/docs/en/users-permissions/acl/permissions.md

Built-in Roles

RoleDescriptionDefault Permissions
adminFull system accessAll permissions
memberBasic user accessLimited to assigned resources
guestUnauthenticated usersMinimal or no access

Sources: docs/docs/en/plugins/@nocobase/plugin-acl/index.md

Permissions Management

Role-Based Access Control

The permissions system in NocoBase is built on the principle of assigning permissions to roles, then assigning roles to users. This follows the standard RBAC (Role-Based Access Control) model.

graph LR
    A[Users] -->|assigned to| B[Roles]
    B -->|grants| C[Permissions]
    C -->|apply to| D[Resources/Actions]
    
    E[Collections] -->|scope| C
    F[Fields] -->|scope| C
    G[Actions] -->|scope| C

Sources: docs/docs/en/users-permissions/index.md

Permission Configuration

Permissions can be configured at multiple levels:

LevelSyntaxExample
All resources*collections:*
Specific resourceresourceNamecollections:posts
Nested resourceparent.childcollections:posts.comments
Field-levelresource:fieldcollections:posts:title

UI Permission Handling

In the client-side implementation, permission checks are integrated throughout the UI components. Fields that users lack permission to modify are automatically restricted:

// From: packages/core/client/src/flow/models/fields/AssociationFieldModel/SubTableFieldModel/SubTableColumnModel.tsx
const messageValue = useMemo(() => {
  return t(
    `The current user only has the UI configuration permission, but don't have "{{actionName}}" permission for field "{{name}}"`,
    {
      name: nameValue,
      actionName: t(capitalize(actionName)),
    },
  ).replaceAll('&gt;', '>');
}, [nameValue, t]);

This code demonstrates how NocoBase handles field-level permissions, displaying lock icons and tooltip messages when users lack action permissions on specific fields.

Security Implementation

Safe Globals in Execution Contexts

For sensitive operations like custom JavaScript execution (e.g., RunJS nodes in workflows), NocoBase implements safe globals to prevent unauthorized access:

// From: packages/core/flow-engine/src/utils/safeGlobals.ts
const allowed: Record<string, any> = {
  clipboard,
};

Object.defineProperty(allowed, 'onLine', {
  get: () => !!nav?.onLine,
  enumerable: true,
  configurable: false,
});

return new Proxy(
  {},
  {
    get(_t, prop: string) {
      if (prop in allowed) return (allowed as any)[prop];
      throw new Error(`Access to navigator property "${String(prop)}" is not allowed.`);
    },
  },
);

This security measure ensures that sensitive browser APIs are either read-only or completely blocked in untrusted execution contexts.

URL Security Validation

When workflows or scripts need to open URLs, NocoBase enforces strict URL validation:

// From: packages/core/flow-engine/src/utils/safeGlobals.ts
const isSafeUrl = (u: string): boolean => {
  try {
    const parsed = new URL(u, getSafeBaseHref());
    const protocol = parsed.protocol.toLowerCase();
    if (protocol === 'about:') return parsed.href === 'about:blank';
    return protocol === 'http:' || protocol === 'https:';
  } catch {
    return false;
  }
};

Only http://, https://, and about:blank URLs are permitted, preventing potential security vulnerabilities from malicious URL schemes.

Plugin Dependencies

The authentication and permissions system depends on a plugin hierarchy:

graph BT
    A[plugin-auth] --> B[plugin-users]
    C[plugin-acl] --> B
    B --> D[plugin-core]
PluginPurpose
plugin-authAuthentication mechanisms
plugin-usersUser management
plugin-aclAccess Control List implementation
DocumentPath
Auth Verificationdocs/docs/en/auth-verification/index.md
ACL Permissionsdocs/docs/en/users-permissions/acl/permissions.md
User Permissions Guidedocs/docs/en/users-permissions/index.md
ACL Plugindocs/docs/en/plugins/@nocobase/plugin-acl/index.md
Auth Plugindocs/docs/en/plugins/@nocobase/plugin-auth/index.md
Users Plugindocs/docs/en/plugins/@nocobase/plugin-users/index.md

Sources: docs/docs/en/users-permissions/acl/permissions.md

AI Integration

Related topics: Overview, Workflow Engine, Plugin Development

Section Related Pages

Continue reading this section for the full explanation and source context.

Section System Components

Continue reading this section for the full explanation and source context.

Section Employee Management

Continue reading this section for the full explanation and source context.

Section Employee Data Model

Continue reading this section for the full explanation and source context.

Related topics: Overview, Workflow Engine, Plugin Development

AI Integration

NocoBase provides a comprehensive AI Integration system through the @nocobase/plugin-ai package. This system enables users to create, manage, and deploy AI employees that can collaborate with human users to build and manage business applications. The AI integration leverages modern LLM (Large Language Model) technology to provide intelligent assistance throughout the platform.

Overview

The AI Integration feature in NocoBase is designed to:

  • Enable AI agents to work alongside human users in a collaborative environment
  • Provide customizable AI employees with different roles and capabilities
  • Support knowledge base integration for context-aware responses
  • Offer tool-calling capabilities for AI to interact with the NocoBase system

Sources: packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/chatbox/Messages.tsx:1-40

Architecture

The AI Integration system follows a plugin-based architecture that integrates seamlessly with the NocoBase core system.

System Components

ComponentPurposeLocation
AI EmployeesVirtual team members that can perform taskspackages/plugins/@nocobase/plugin-ai
Chat InterfaceReal-time messaging between users and AIsrc/client/ai-employees/chatbox/
Admin PanelManagement interface for AI configurationssrc/client/ai-employees/admin/
TemplatesPre-configured AI employee templatessrc/client/ai-employees/admin/Templates.tsx
Tool SystemServer-side tools for AI operationssrc/server/tools/

Sources: packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/admin/Employees.tsx:1-80

AI Employees

AI Employees are virtual team members that can be assigned tasks, communicate with users, and perform various operations within the NocoBase ecosystem.

Employee Management

The Employees component provides a comprehensive interface for managing AI employees:

<SchemaComponent
  components={{ AIEmployeeForm, Avatar, Templates, Enabled, EnableSwitch, CategoryFilter, Username }}
  scope={{
    t,
    useCreateFormProps,
    useEditFormProps,
    useCancelActionProps,
    useCreateActionProps,
    useEditActionProps,
    useDeleteActionProps,
  }}
  schema={{
    type: 'void',
    name: 'ai-employees',
    properties: {
      block: {
        type: 'void',
        'x-component': 'CardItem',
        'x-component-props': {
          heightMode: 'fullHeight',
        },
        'x-decorator': 'TableBlockProvider',
        'x-decorator-props': {
          collection: 'aiEmployees',
          action: 'list',
          params: {
            filter: {
              category: 'business',
            },
          },
          rowKey: 'username',
          dragSort: true,
          dragSortBy: 'sort',
        },
      },
    },
  }}
/>

Sources: packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/admin/Employees.tsx:35-75

Employee Data Model

FieldTypeDescription
usernamestringUnique identifier for the AI employee
categorystringClassification category (e.g., 'business')
enabledbooleanWhether the employee is active
sortnumberDisplay order
templatesarrayPre-configured task templates

Category Filtering

AI employees can be filtered by category using the CategoryFilter component, allowing administrators to organize employees based on their functional areas or roles.

Sources: packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/admin/Employees.tsx:50-55

Chat Interface

The chatbox component provides a real-time messaging interface for user interaction with AI employees.

Message Display

Messages are rendered using the Messages component which handles different message states:

<div className={styles.chatBox}>
  {messages.length > 0 ? (
    <div className={styles.messages}>
      {messages.map((msg) => {
        return (
          <Message
            key={msg.key}
            loading={msg.loading}
            content={msg.content}
          />
        );
      })}
    </div>
  ) : (
    <div
      style={{
        position: 'absolute',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        color: token.colorTextDescription,
      }}
    >
      {t('Work with your AI crew')}
    </div>
  )}
</div>

Sources: packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/chatbox/Messages.tsx:10-40

Message States

StateDescriptionVisual Indicator
normalStandard message displayDefault styling
loadingMessage being processedLoading spinner
errorFailed messageError styling
streamingReal-time responseProgressive rendering

Templates System

Templates provide pre-configured AI employee configurations that can be quickly deployed to create new AI team members.

Template Loading

Templates are loaded dynamically from the server:

const { data: templates, loading } = useRequest<{ data: AIEmployee[] }>(() =>
  api
    .resource('aiEmployees')
    .getTemplates()
    .then((res) => res?.data?.data),
);

Sources: packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/admin/Templates.tsx:1-30

Template Creation Flow

When creating a new employee from a template, the system uses a drawer component with form validation:

<SchemaComponent
  scope={{ useCancelActionProps, useCreateActionProps, useTemplateFormProps }}
  schema={{
    type: 'void',
    name: uid(),
    'x-component': 'Action.Drawer',
    title: '{{t("New AI employee")}}',
    'x-decorator': 'FormV2',
    'x-use-decorator-props': 'useTemplateFormProps',
    properties: {
      form: {
        type: 'void',
        'x-component': 'AIEmployeeForm',
      },
      footer: {
        type: 'void',
        'x-component': 'Action.Drawer.Footer',
        properties: {
          close: {
            title: 'Cancel',
            'x-component': 'Action',
            'x-component-props': {
              type: 'default',
            },
            'x-use-component-props': 'useCancelActionProps',
          },
          submit: {
            title: '{{t("Submit")}}',
            'x-component': 'Action',
            'x-component-props': {
              type: 'primary',
            },
            'x-use-component-props': 'useCreateActionProps',
          },
        },
      },
    },
  }}
/>

Sources: packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/admin/Templates.tsx:35-85

Server-Side Tools

The AI integration includes server-side tools that allow AI employees to interact with various NocoBase system components.

Documentation Reader Tool

The readDocEntry tool enables AI employees to access and read documentation entries:

readDocEntry: {
  description: 'Read a documentation entry',
  parameters: {
    type: 'object',
    properties: {
      module: {
        type: 'string',
        description: 'The module key (e.g., "runjs")',
      },
    },
    required: ['module'],
  },
  async handler(ctx) {
    try {
      const { pluginKey, relativePath, canonicalPath } = parseDocPath(input);
      const meta = docsModules.get(pluginKey);
      if (!meta) {
        throw new Error(`Document module "${pluginKey}" not found.`);
      }
      // Read and return documentation content
    } catch (error) {
      ctx.log?.error?.(error, {
        module: 'ai',
        subModule: 'toolCalling',
        toolName: 'readDocEntry',
      });
      return {
        status: 'error',
        content: `Failed to read docs entry: ${error.message}`,
      };
    }
  },
},

Sources: packages/plugins/@nocobase/plugin-ai/src/server/tools/docs.ts:1-80

Tool Execution Flow

graph TD
    A[User Request] --> B[AI Employee Processing]
    B --> C{Requires Tool?}
    C -->|Yes| D[Tool Selection]
    C -->|No| E[Direct Response]
    D --> F[Execute Server Tool]
    F --> G[Tool Handler]
    G --> H[Error Handling]
    H --> I[Return Result]
    E --> I
    I --> J[Response to User]

Available Server Tools

Tool NamePurposeModule
readDocEntryRead documentation entriesai
customVariableManage flow variablesflow
runjsExecute JavaScript codeflow-engine

AI Context in Workflows

The AI system integrates with NocoBase's workflow engine through a comprehensive context system that provides AI employees access to system resources.

Resource Context

AI employees can interact with resources through the context API:

interface ResourceContext {
  setData: {
    description: '设置资源当前数据(仅前端)';
    detail: '(value: any) => this';
    completion: { insertText: 'ctx.resource.setData(value)' };
  };
  refresh: {
    description: '从后端刷新数据';
    detail: '() => Promise<any>';
    completion: { insertText: 'await ctx.resource.refresh()' };
  };
  on: {
    description: '订阅资源事件';
    detail: '(event: string, callback: (...args) => void) => void';
    completion: { insertText: "ctx.resource.on('refresh', () => {})" };
  };
  setResourceName: {
    description: '设置资源名称';
    detail: '(resourceName: string) => this';
    completion: { insertText: "ctx.resource.setResourceName('users')" };
  };
  setFilterByTk: {
    description: '设置主键/过滤键';
    detail: '(filterByTk: any) => this';
    completion: { insertText: 'ctx.resource.setFilterByTk(filterByTk)' };
  };
  runAction: {
    description: '执行资源动作';
  };
}

Sources: packages/core/flow-engine/src/runjs-context/contexts/base.ts:1-50

Flow Variables

AI integration supports custom variables that can be used in workflows and shared between human and AI collaborators.

Variable Management Interface

The variable management UI provides full CRUD operations:

columns={[
  {
    title: t('Name'),
    dataIndex: 'name',
    key: 'name',
    ellipsis: true,
    render: (text: string) => <span style={{ whiteSpace: 'nowrap' }}>{text}</span>,
  },
  {
    title: t('Identifier'),
    dataIndex: 'key',
    key: 'key',
    ellipsis: true,
  },
  {
    title: t('Type'),
    dataIndex: 'type',
    key: 'type',
    render: (type: FlowVariableType) => (
      <Tag style={{ whiteSpace: 'nowrap' }}>{t(VARIABLE_TYPE_LABELS[type] || type)}</Tag>
    ),
  },
  {
    title: t('Actions'),
    key: 'actions',
    render: (_: unknown, __: FlowVariable, index: number) => (
      <Space size={12}>
        <Button
          type="link"
          size="small"
          icon={<EditOutlined />}
          onClick={() => handleEdit(index)}
        />
        <Button
          type="link"
          size="small"
          icon={<DeleteOutlined />}
          danger
          onClick={() => handleDelete(index)}
        />
      </Space>
    ),
  },
]}

Sources: packages/core/client/src/flow/actions/customVariable.tsx:1-70

Variable Types

TypeLabelDescription
stringStringText value
numberNumberNumeric value
booleanBooleanTrue/false value
dateDateDate and time value
objectObjectComplex data structure
arrayArrayCollection of values

Error Handling

The AI integration system includes comprehensive error handling for both client and server components.

Client-Side Error Fallback

<Result
  style={{ maxWidth: '60vw', margin: 'auto' }}
  status="error"
  title={t('Render Failed')}
  subTitle={subTitle}
  extra={[
    <Button type="primary" key="feedback" href="https://github.com/nocobase/nocobase/issues" target="_blank">
      {t('Feedback')}
    </Button>,
    <Button key="log" loading={loading} onClick={download}>
      {t('Download logs')}
    </Button>,
  ]}
>
  <Paragraph copyable={{ text: error.stack }}>
    <Text type="danger" style={{ whiteSpace: 'pre-line', textAlign: 'center' }}>
      {error.stack}
    </Text>
  </Paragraph>
</Result>

Sources: packages/core/client/src/schema-component/antd/error-fallback/ErrorFallback.tsx:1-30

Server-Side Error Logging

Errors are logged with module context for debugging:

ctx.log?.error?.(error, {
  module: 'ai',
  subModule: 'toolCalling',
  toolName: 'readDocEntry',
});

Installation and Setup

To enable AI integration in NocoBase:

  1. Install the @nocobase/plugin-ai package
  2. Configure the plugin in the NocoBase administration panel
  3. Set up AI provider credentials (API keys for LLM services)
  4. Create AI employees and assign roles
  5. Configure knowledge bases and tools as needed

Summary

The AI Integration system in NocoBase provides a powerful framework for creating intelligent AI employees that can collaborate with human users. Key features include:

  • Employee Management: Create, edit, and organize AI team members with different roles
  • Real-time Chat: Direct communication channel between users and AI employees
  • Template System: Quick deployment of pre-configured AI employees
  • Tool Integration: AI can access NocoBase system capabilities through server-side tools
  • Workflow Integration: AI context available in NocoBase workflow engine
  • Error Handling: Comprehensive error reporting and recovery mechanisms

This system enables organizations to build AI-powered business applications that leverage the intelligence of large language models while maintaining the flexibility and extensibility of the NocoBase no-code platform.

Sources: packages/plugins/@nocobase/plugin-ai/src/client/ai-employees/chatbox/Messages.tsx:1-40

File Storage

Related topics: Data Modeling, Interface Builder

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Type Definitions

Continue reading this section for the full explanation and source context.

Section Read Pretty Mode

Continue reading this section for the full explanation and source context.

Section File Actions

Continue reading this section for the full explanation and source context.

Related topics: Data Modeling, Interface Builder

File Storage

Overview

File Storage in NocoBase is a comprehensive system for managing file uploads, storage, and preview capabilities across the platform. The system is built on top of Ant Design's Upload component and extends it with additional features such as thumbnail preview, file type validation, size restrictions, and integration with the broader schema system.

The file storage subsystem consists of several key components:

  • Upload Component: The primary interface for file uploads
  • Storage Adapters: Backend mechanisms for persisting files
  • File Preview: Preview capabilities for various file types
  • Schema Integration: Deep integration with NocoBase's schema system

Sources: packages/core/client/src/schema-component/antd/upload/index.md:1-24

Upload Component

Type Definitions

The Upload component is defined with the following type signature:

type UploadProps = Omit<AntdUploadProps, 'onChange'> & {
  onChange?: (fileList: UploadFile[]) => void;
  serviceErrorMessage?: string;
  value?: any;
  size?: string;
};

Sources: packages/core/client/src/schema-component/antd/upload/index.md:8-13

The component accepts all Ant Design Upload props while extending them with NocoBase-specific functionality. The value prop allows for controlled usage within schema forms, and size can be used to restrict upload behavior.

Read Pretty Mode

For display-only scenarios, a specialized read-pretty variant is available:

type UploadReadPrettyProps = AntdUploadProps;

Sources: packages/core/client/src/schema-component/antd/upload/index.md:17-18

File List Item Rendering

The file list rendering in Upload.tsx demonstrates how individual uploaded files are displayed to users:

const item = [
  <span key="thumbnail" className={`${prefixCls}-list-item-thumbnail`}>
    <ThumbnailPreviewer file={file} />
  </span>,
  showFileName !== false && file.title ? (
    <span key="title" className={`${prefixCls}-list-item-name`} title={file.title}>
      {file.status === 'uploading' ? t('Uploading') : file.title}
    </span>
  ) : null,
];

Sources: packages/core/client/src/schema-component/antd/upload/Upload.tsx:1-11

The rendered item can be either a clickable link (if file.url exists) or a plain span:

const wrappedItem = file.url ? (
  <a target="_blank" rel="noopener noreferrer" href={file.url} onClick={handleClick}>
    {item}
  </a>
) : (
  <span className={`${prefixCls}-span`}>{item}</span>
);

Sources: packages/core/client/src/schema-component/antd/upload/Upload.tsx:13-20

File Actions

Each file item includes action buttons for managing the upload:

ActionConditionIconHandler
Download!readPretty && file.urlDownloadOutlinedonDownload
Delete!readPretty && !disabled && file.status !== 'uploading'DeleteOutlinedonDelete

Sources: packages/core/client/src/schema-component/antd/upload/Upload.tsx:23-35

Upload Workflow

graph TD
    A[User Selects File] --> B{File Size Check}
    B -->|Greater than 1MB| C[Show Error Alert]
    B -->|Within Limit| D[startScanFile]
    D --> E[Upload to Server]
    E --> F{Upload Status}
    F -->|uploading| G[Show Progress]
    F -->|done| H[Display Thumbnail]
    F -->|error| I[Show Error State]

File Size Validation

The system enforces a 1MB limit on uploaded images with user-friendly error messaging:

if (file && file.size < 1024 * 1024) {
  startScanFile(file);
} else {
  alert(t('The image size is too large. Please compress it to below 1MB before uploading'));
}

Sources: packages/core/client/src/schema-component/antd/input/ScanInput/QRCodeScanner.tsx:1-8

This validation pattern ensures users receive clear guidance when attempting to upload oversized files.

Thumbnail Preview

The thumbnail previewer component handles generating previews for uploaded files. The ThumbnailPreviewer component is referenced in the upload component's item rendering and provides visual feedback for uploaded content.

Integration with Schema System

Schema Designer Integration

Files can be configured and managed through NocoBase's schema system using the GeneralSchemaDesigner component:

<span className={'title-tag'}>
  {showDataSource && dataSource
    ? `${compile(dataSource?.displayName)} > ${compile(title)}`
    : compile(title)}
</span>

Sources: packages/core/client/src/schema-settings/GeneralSchemaDesigner.tsx:1-8

This allows file storage configurations to be embedded within the broader schema initialization and settings infrastructure.

File Type Detection

The upload system includes utility functions for determining file types, including CSS file detection:

export function isCssFile(url: string): boolean {
  if (!url || typeof url !== 'string') {
    return false;
  }
  // 去掉 query 和 hash 后判断文件扩展名
  const pathPart = url.split('?')[0].split('#')[0];
  return pathPart.endsWith('.css');
}

Sources: packages/core/flow-engine/src/utils/resolveModuleUrl.ts:1-14

This utility strips query parameters and hash fragments before checking file extensions, supporting URLs like example.css?v=123 or example.css#section.

Configuration Options

Upload Component Properties

PropertyTypeDescriptionDefault
valueanyControlled value for the file list-
onChange(fileList: UploadFile[]) => voidCallback when file list changes-
serviceErrorMessagestringCustom error message for upload failures-
sizestringSize restriction identifier-
readPrettybooleanDisplay-only modefalse

File List Item States

StatusUI IndicatorAvailable Actions
uploadingProgress indicatorNone
doneThumbnail + filenameDownload, Delete
errorError stateDelete

Best Practices

  1. Size Limits: Always validate file sizes before upload to provide immediate user feedback
  2. Thumbnail Previews: Enable thumbnails to improve user experience for image files
  3. Accessible Links: Use proper target="_blank" and rel="noopener noreferrer" for downloaded files
  4. Status Indicators: Show upload progress and error states clearly
  5. URL Handling: Strip query parameters and hash fragments when determining file types

Sources: packages/core/client/src/schema-component/antd/upload/index.md:1-24

Cluster Mode

Related topics: Deployment, System Architecture

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Components

Continue reading this section for the full explanation and source context.

Section Infrastructure Requirements

Continue reading this section for the full explanation and source context.

Section Environment Variables

Continue reading this section for the full explanation and source context.

Related topics: Deployment, System Architecture

Cluster Mode

Overview

Cluster Mode in NocoBase enables horizontal scaling by running multiple application instances behind a load balancer. This architecture provides high availability, improved performance under concurrent load, and fault tolerance for production deployments.

Architecture Overview

graph TD
    Client1[Client] --> LB[Load Balancer]
    Client2[Client] --> LB
    Client3[Client] --> LB
    LB --> App1[NocoBase Instance 1]
    LB --> App2[NocoBase Instance 2]
    LB --> App3[NocoBase Instance N]
    App1 <--> Redis[(Redis)]
    App2 <--> Redis
    App3 <--> Redis
    App1 <--> DB[(Database)]
    App2 <--> DB
    App3 <--> DB

Core Components

ComponentPurposeRequired
Load BalancerDistributes traffic across instancesYes
NocoBase InstancesApplication servers running the same codebaseYes
Shared DatabaseMySQL/PostgreSQL for persistent data storageYes
RedisLock adapter and pub/sub for inter-instance communicationYes
File StorageS3/MinIO for file uploads (shared across instances)Yes

Prerequisites

Infrastructure Requirements

Before deploying in cluster mode, ensure the following:

  1. Database: MySQL 8.0+ or PostgreSQL 12+ with proper network access
  2. Redis: Redis 6.0+ for distributed locking and pub/sub
  3. File Storage: Shared storage solution (S3-compatible, MinIO, or NFS)
  4. Load Balancer: Nginx, HAProxy, or cloud provider LB

Environment Variables

VariableDescriptionExample
APP_ENVApplication environmentproduction
DB_DIALECTDatabase typemysql or postgres
DB_HOSTDatabase hostlocalhost
DB_PORTDatabase port3306
DB_DATABASEDatabase namenocobase
DB_USERDatabase usernocobase
DB_PASSWORDDatabase password***
REDIS_URLRedis connection stringredis://localhost:6379
CACHE_STORAGECache storage typeredis

Redis Plugins

NocoBase requires two Redis plugins for cluster operation:

Lock Adapter (Redis)

Handles distributed locking to prevent race conditions across instances.

Plugin: @nocobase/plugin-lock-adapter-redis

npm install @nocobase/plugin-lock-adapter-redis

Configuration in database.yml:

plugins:
  - name: lock
    options:
      type: redis
      redis:
        port: 6379
        host: localhost
        password: ''
        db: 0

Pub/Sub Adapter (Redis)

Enables real-time communication between instances for features like:

  • Live query updates
  • Real-time collaboration
  • Broadcast notifications

Plugin: @nocobase/plugin-pubsub-adapter-redis

npm install @nocobase/plugin-pubsub-adapter-redis

Deployment Options

Docker Compose (Development/Testing)

version: '3.8'
services:
  app:
    image: nocobase/app:latest
    replicas: 3
    depends_on:
      - redis
      - db
    environment:
      - APP_ENV=production
      - DB_DIALECT=postgres
      - REDIS_URL=redis://redis:6379
    deploy:
      replicas: 3

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

  db:
    image: postgres:15
    environment:
      - POSTGRES_DB=nocobase
      - POSTGRES_USER=nocobase
      - POSTGRES_PASSWORD=nocobase

Kubernetes Deployment

For production environments, Kubernetes provides:

  • Automatic scaling
  • Rolling updates
  • Self-healing capabilities
  • Service discovery

Refer to the Kubernetes Deployment Guide for detailed configuration.

Configuration

Load Balancer Configuration (Nginx)

upstream nocobase_backend {
    least_conn;
    server app1:13000 weight=5;
    server app2:13000 weight=5;
    server app3:13000 weight=5;
}

server {
    listen 80;
    server_name your-domain.com;

    location / {
        proxy_pass http://nocobase_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /socket.io/ {
        proxy_pass http://nocobase_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

Application Configuration

In data/source/database.yml:

database:
  type: mysql
  ...
  pool: 10

redis:
  host: redis-host
  port: 6379

plugins:
  - '@nocobase/plugin-lock-adapter-redis'
  - '@nocobase/plugin-pubsub-adapter-redis'

Operations

Health Checks

Configure health check endpoints on the load balancer:

EndpointExpected ResponsePurpose
/api/health200 OKInstance health status
/api/healthy200 OKReadiness probe

Scaling

graph LR
    A[Request] --> B{Higher Load?}
    B -->|Yes| C[Scale Up Instances]
    B -->|No| D[Current Scale]
    C --> E[Update LB Pool]
    E --> A

Monitoring

Key metrics to monitor:

  • Request latency per instance
  • Database connection pool usage
  • Redis connection status
  • Session distribution
  • Error rates per instance

Rolling Updates

  1. Deploy new version to subset of instances
  2. Remove updated instances from LB pool temporarily
  3. Update remaining instances
  4. Restore full instance count

Troubleshooting

Common Issues

IssueCauseSolution
502 Bad GatewayAll instances downCheck instance logs, restart services
Stale data displayedCache inconsistencyClear Redis cache, check pub/sub connectivity
Lock contentionHigh concurrencyIncrease Redis resources, optimize locking strategy
WebSocket disconnectionProxy timeoutConfigure longer timeouts in load balancer

Diagnostics

# Check instance connectivity
curl http://instance-ip:13000/api/health

# Verify Redis connectivity
redis-cli -h redis-host ping

# Check database connectivity
npm run nocobase db:ping

Best Practices

  1. Stateless Design: Ensure applications do not store user state locally
  2. Session Management: Use Redis-backed sessions for sticky sessions
  3. Database Connection Pooling: Configure appropriate pool sizes per instance
  4. File Storage: Use shared storage to ensure file consistency
  5. Graceful Shutdown: Configure proper shutdown handlers for rolling updates
  6. Logging: Centralize logs from all instances for debugging

Source: https://github.com/nocobase/nocobase / Human Manual

Plugin Development

Related topics: Plugin System, System Architecture

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Server Plugins

Continue reading this section for the full explanation and source context.

Section Client Plugins

Continue reading this section for the full explanation and source context.

Section Application States

Continue reading this section for the full explanation and source context.

Related topics: Plugin System, System Architecture

Plugin Development

Overview

NocoBase adopts a plugin-based architecture where every feature is implemented as a plugin. This modular design enables:

  • Extensibility: Add new functionality without modifying the core system
  • Maintainability: Features are isolated and independently deployable
  • Reusability: Plugins can be shared and reused across different projects
  • Hot-loading: Plugins can be loaded/unloaded at runtime
graph TD
    A[NocoBase Core] --> B[Plugin System]
    B --> C[Server Plugins]
    B --> D[Client Plugins]
    C --> E[Database Operations]
    C --> F[API Routes]
    C --> G[Event Handlers]
    D --> H[UI Components]
    D --> I[Schema Initializers]
    D --> J[Schema Settings]

Plugin Structure

A typical NocoBase plugin follows this directory structure:

my-plugin/
├── src/
│   ├── client/           # Client-side code
│   │   ├── index.ts      # Client plugin entry
│   │   └── components/   # UI components
│   ├── server/           # Server-side code
│   │   ├── index.ts      # Server plugin entry
│   │   ├── actions/      # Custom actions
│   │   └── migrations/   # Database migrations
│   └── index.ts          # Main entry (client + server)
├── package.json
└── dist/                 # Build output
    └── externalVersion.js

Plugin Types

Server Plugins

Server plugins handle backend logic including database operations, API routes, and event handling.

Entry Point (src/server/index.ts):

import { Plugin } from '@nocobase/server';

export default class MyPlugin extends Plugin {
  async load() {
    // Register collections
    this.app.collection({
      name: 'posts',
      fields: [
        { type: 'string', name: 'title' },
        { type: 'text', name: 'content' },
      ],
    });

    // Register API routes
    this.app.resourcer.define({
      name: 'posts',
      actions: {
        async list(ctx, next) {
          ctx.body = await ctx.db.getRepository('posts').find();
          await next();
        },
      },
    });
  }
}

Plugin.register(MyPlugin);

Sources: packages/core/client/src/pm/PluginDetail.tsx:1-50

Client Plugins

Client plugins manage UI components, schema initializers, and schema settings.

Entry Point (src/client/index.ts):

import { Plugin } from '@nocobase/client';

export default class MyPlugin extends Plugin {
  async load() {
    // Register schema initializer
    this.schemaInitializerManager.addItem(
      'charts',
      'my-plugin:item',
      {
        title: 'My Chart',
        component: 'MyChartComponent',
      }
    );

    // Register schema settings
    this.schemaSettingsManager.add('my-plugin:settings', {
      title: 'My Settings',
      items: [
        { name: 'title', component: 'Input' },
        { name: 'delete', type: 'danger' },
      ],
    });
  }
}

Plugin.register(MyPlugin);

Sources: packages/core/client/src/pm/PluginManagerLink.tsx:1-30

Remote Plugins

NocoBase supports loading plugins remotely via require.js. Remote plugins are configured through the application settings and loaded on demand.

Configuration (src/application/utils/remotePlugins.ts):

export function configRequirejs(requirejs: any, pluginData: PluginData[]) {
  requirejs.requirejs.config({
    waitSeconds: 120,
    paths: pluginData.reduce<Record<string, string>>((acc, cur) => {
      acc[cur.packageName] = cur.url;
      return acc;
    }, {}),
  });
}

export function processRemotePlugins(
  pluginData: PluginData[], 
  resolve: (plugins: [string, typeof Plugin][]) => void
) {
  return (...pluginModules: (typeof Plugin & { default?: typeof Plugin })[]) => {
    const res: [string, typeof Plugin][] = pluginModules
      .map<[string, typeof Plugin]>((item, index) => [
        pluginData[index].name, 
        item?.default || item
      ])
      .filter((item) => item[1]);
    resolve(res);
  };
}

Key characteristics:

  • Timeout: 120 seconds wait time for plugin loading
  • Path Mapping: Maps package names to remote URLs
  • Default Export: Automatically handles both default and named exports

Sources: packages/core/client/src/application/utils/remotePlugins.ts:40-70

Plugin Lifecycle

stateDiagram-v2
    [*] --> Registered
    Registered --> Loading
    Loading --> Loaded
    Loaded --> Enabled
    Enabled --> Disabled
    Disabled --> Enabled
    Enabled --> Unloaded
    Unloaded --> [*]

Application States

The plugin system tracks various application states during initialization:

State CodeStatusIconDescription
APP_PREPARINGinfoLoadingOutlinedApp preparing
APP_INITIALIZINGinfoLoadingOutlinedApp initializing
APP_INITIALIZEDinfo-App initialized
APP_NOT_INSTALLED_ERRORwarning-App not installed
APP_STOPPEDwarning-App stopped
APP_COMMANDINGinfoLoadingOutlinedApp commanding
ENOENT, APP_ERROR, LOAD_ERRORerror-App error

Sources: packages/core/client/src/nocobase-buildin-plugin/index.tsx:1-60

Plugin Manager

The Plugin Manager provides a UI interface for managing plugins with the following features:

Plugin Detail Display

interface PluginDetailProps {
  plugin: {
    packageName: string;
    version: string;
    name: string;
    displayName?: string;
    description?: string;
    version?: string;
  };
  data?: {
    packageJson: {
      license?: string;
    };
    homepage?: string;
    depsCompatible: boolean | null;
    isCompatible: boolean;
  };
}

The plugin detail view displays:

  • Package Name: Unique identifier for the plugin
  • Version: Current installed version
  • Display Name: Human-readable name
  • Description: Plugin functionality description
  • License: Package license type
  • Homepage: External documentation URL
  • Dependencies: Compatibility status

Sources: packages/core/client/src/pm/PluginDetail.tsx:1-100

Dependencies Compatibility Check

{
  key: 'dependencies',
  label: t('Dependencies compatibility check'),
  children: (
    <>
      {data?.data?.depsCompatible === false ? (
        <Typography.Text type="danger">
          {t('`dist/externalVersion.js` not found or failed to `require`. Please rebuild this plugin.')}
        </Typography.Text>
      ) : (
        <>
          {!data?.data?.['isCompatible'] && (
            <Alert
              showIcon
              type={'error'}
              message={t('Plugin dependencies check failed...')}
            />
          )}
          <Table
            rowKey={'name'}
            pagination={false}
            columns={dependenciesCompatibleTableColumns}
            dataSource={data?.data?.depsCompatible}
          />
        </>
      )}
    </>
  ),
}
Check TypeConditionMessage
Build Requireddist/externalVersion.js not foundRebuild plugin required
CompatibilityisCompatible === falseDependency version mismatch
SuccessAll checks passDependencies compatible

Sources: packages/core/client/src/pm/PluginDetail.tsx:20-45

Plugin Settings

Plugins can register their own settings pages in the administration interface:

const settingItems = settings
  .filter((setting) => setting.visible !== false)
  .map((setting) => {
    return {
      key: setting.name,
      icon: setting.icon,
      label: setting.link ? (
        <div onClick={() => window.open(setting.link)}>
          {compile(setting.title)}
        </div>
      ) : (
        <Link to={setting.path}>{compile(setting.title)}</Link>
      ),
    };
  });
PropertyTypeDescription
namestringUnique setting identifier
titlestringDisplay title
iconReactNodeSetting icon
pathstringNavigation route
linkstringExternal link (optional)
visiblebooleanVisibility control

Sources: packages/core/client/src/pm/PluginManagerLink.tsx:1-50

Building Plugins

Build Output Requirements

After building a plugin, ensure the following files exist in the dist/ directory:

dist/
├── index.js
├── client.js
├── server.js
└── externalVersion.js    # Required for compatibility

The externalVersion.js file exports version information for dependency compatibility checks.

Remote Plugin Loading

interface PluginData {
  packageName: string;
  url: string;
  name: string;
}

Plugins loaded remotely must:

  1. Export a default class extending Plugin
  2. Be accessible via the configured URL
  3. Include externalVersion.js for dependency validation

Sources: packages/core/client/src/application/utils/remotePlugins.ts:1-40

Error Handling

Plugin Load Errors

When plugins fail to load, the system logs detailed error messages:

if (emptyPlugins.length > 0) {
  console.error(
    '[nocobase load plugin error]: These plugins do not have an `export.default` exported content or there is an error in the plugins. error plugins: \r\n%s',
    emptyPlugins.join(', \r\n'),
  );
}

Common error causes:

  • Missing export default in the plugin entry
  • Syntax errors in plugin code
  • Circular dependency issues
  • Timeout during remote plugin loading

App Error States

Error CodeSeverityResolution
ENOENTerrorCheck file paths and build output
APP_ERRORerrorReview application logs
LOAD_ERRORerrorVerify plugin exports and dependencies
APP_NOT_INSTALLEDwarningRun installation command
APP_STOPPEDwarningRestart the application

Sources: packages/core/client/src/nocobase-buildin-plugin/index.tsx:40-55

Schema Integration

Plugins can extend the application schema system by registering:

Schema Initializers

Enable adding new items to schema initialization panels:

this.schemaInitializerManager.addItem(
  scope: string,      // Parent group identifier
  key: string,        // Unique item key
  item: SchemaInitializerItem  // Item configuration
);

Schema Settings

Add configuration panels for schema components:

this.schemaSettingsManager.add(
  name: string,
  config: SchemaSettingsConfig
);

Best Practices

  1. Always export default: Plugin classes must use export default for proper loading
  2. Include externalVersion.js: Required for dependency compatibility checks
  3. Handle errors gracefully: Wrap async operations in try-catch blocks
  4. Use unique namespacing: Prefix plugin-specific names with plugin name
  5. Document dependencies: Clearly specify version requirements in package.json

Sources: packages/core/client/src/pm/PluginDetail.tsx:1-50

Doramagic Pitfall Log

Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.

high REST API: Multiple select field not working in edit form

The project may affect permissions, credentials, data exposure, or host boundaries.

medium v2.1.0-alpha.33

First-time setup may fail or require extra isolation and rollback planning.

medium v2.1.0-beta.30

First-time setup may fail or require extra isolation and rollback planning.

medium v2.0.51

Users may get misleading failures or incomplete behavior unless configuration is checked carefully.

Doramagic Pitfall Log

Doramagic extracted 16 source-linked risk signals. Review them before installing or handing real data to the project.

1. Security or permission risk: REST API: Multiple select field not working in edit form

  • Severity: high
  • Finding: Security or permission risk is backed by a source signal: REST API: Multiple select field not working in edit form. Treat it as a review item until the current version is checked.
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/nocobase/nocobase/issues/8836

2. Installation risk: v2.1.0-alpha.33

  • Severity: medium
  • Finding: Installation risk is backed by a source signal: v2.1.0-alpha.33. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/nocobase/nocobase/releases/tag/v2.1.0-alpha.33

3. Installation risk: v2.1.0-beta.30

  • Severity: medium
  • Finding: Installation risk is backed by a source signal: v2.1.0-beta.30. Treat it as a review item until the current version is checked.
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/nocobase/nocobase/releases/tag/v2.1.0-beta.30

4. Configuration risk: v2.0.51

  • Severity: medium
  • Finding: Configuration risk is backed by a source signal: v2.0.51. Treat it as a review item until the current version is checked.
  • User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/nocobase/nocobase/releases/tag/v2.0.51

5. Configuration risk: v2.1.0-alpha.32

  • Severity: medium
  • Finding: Configuration risk is backed by a source signal: v2.1.0-alpha.32. Treat it as a review item until the current version is checked.
  • User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/nocobase/nocobase/releases/tag/v2.1.0-alpha.32

6. Configuration risk: v2.1.0-beta.29

  • Severity: medium
  • Finding: Configuration risk is backed by a source signal: v2.1.0-beta.29. Treat it as a review item until the current version is checked.
  • User impact: Users may get misleading failures or incomplete behavior unless configuration is checked carefully.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/nocobase/nocobase/releases/tag/v2.1.0-beta.29

7. Capability assumption: README/documentation is current enough for a first validation pass.

  • Severity: medium
  • Finding: README/documentation is current enough for a first validation pass.
  • User impact: The project should not be treated as fully validated until this signal is reviewed.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: capability.assumptions | github_repo:306829688 | https://github.com/nocobase/nocobase | README/documentation is current enough for a first validation pass.

8. Maintenance risk: Maintainer activity is unknown

  • Severity: medium
  • Finding: Maintenance risk is backed by a source signal: Maintainer activity is unknown. Treat it as a review item until the current version is checked.
  • User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: evidence.maintainer_signals | github_repo:306829688 | https://github.com/nocobase/nocobase | last_activity_observed missing

9. Security or permission risk: no_demo

  • Severity: medium
  • Finding: no_demo
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: downstream_validation.risk_items | github_repo:306829688 | https://github.com/nocobase/nocobase | no_demo; severity=medium

10. Security or permission risk: No sandbox install has been executed yet; downstream must verify before user use.

  • Severity: medium
  • Finding: No sandbox install has been executed yet; downstream must verify before user use.
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: risks.safety_notes | github_repo:306829688 | https://github.com/nocobase/nocobase | No sandbox install has been executed yet; downstream must verify before user use.

11. Security or permission risk: no_demo

  • Severity: medium
  • Finding: no_demo
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: risks.scoring_risks | github_repo:306829688 | https://github.com/nocobase/nocobase | no_demo; severity=medium

12. Security or permission risk: v2.0.52

  • Severity: medium
  • Finding: Security or permission risk is backed by a source signal: v2.0.52. Treat it as a review item until the current version is checked.
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: Source-linked evidence: https://github.com/nocobase/nocobase/releases/tag/v2.0.52

Source: Doramagic discovery, validation, and Project Pack records

Community Discussion Evidence

These external discussion links are review inputs, not standalone proof that the project is production-ready.

Sources 11

Count of project-level external discussion links exposed on this manual page.

Use Review before install

Open the linked issues or discussions before treating the pack as ready for your environment.

Community Discussion Evidence

Doramagic exposes project-level community discussion separately from official documentation. Review these links before using nocobase with real data or production workflows.

Source: Project Pack community evidence and pitfall evidence