Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Principle:Langgenius Dify Service Layer Architecture

From Leeroopedia
Knowledge Sources Dify
Domains Frontend, Architecture, API
Last Updated 2026-02-12 07:00 GMT

Overview

The Dify frontend employs a layered HTTP service architecture that separates low-level fetch mechanics from authenticated request handling and domain-specific API modules, providing a consistent and maintainable approach to server communication.

Description

At the foundation of the service layer sits a fetch wrapper (service/fetch.ts) built on the ky HTTP client. This layer defines content types, constructs base options including CSRF headers and passport tokens, handles HTTP status codes (204 no-content normalization, 401 unauthorized, 403 forbidden), and provides lifecycle hooks (beforeRequest, afterResponse, beforeError) that enforce cross-cutting concerns such as error toasting, CSRF cookie injection, and marketplace API prefix routing.

Above the fetch wrapper, the base service layer (service/base.ts) exposes typed HTTP verb functions (get, post, put, del, patch) that handle JSON serialization, authentication token refresh on 401 responses, and Server-Sent Event (SSE) streaming for real-time chat and workflow execution. The SSE implementation parses chunked event streams and dispatches typed callbacks for workflow nodes, thought chains, message completions, annotations, and file attachments.

Domain-specific service modules (service/common.ts, service/explore.ts, service/annotation.ts, etc.) compose these base functions into named API calls with proper TypeScript typing, forming the outermost layer that application components consume. Each module focuses on a single domain, keeping API surface areas small and auditable.

Usage

Use this principle when:

  • Adding new backend API endpoints to the frontend and need to follow the existing layered pattern
  • Implementing real-time streaming features (SSE) for chat, workflow, or pipeline execution
  • Modifying cross-cutting HTTP concerns such as authentication headers, CSRF protection, or error handling

Theoretical Basis

This architecture follows the Layered Architecture pattern where each layer has a single responsibility and depends only on layers below it. The separation of transport mechanics (ky configuration, hooks), authenticated request handling (token refresh, SSE streaming), and domain API modules mirrors the classic Service Layer pattern from enterprise application design, ensuring that changes to authentication flows do not ripple into domain-specific code.

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment