Dosu LogoDosu Logo
Ask
Join our Discord
Organization avatar
difyPublic
Dify
Documentsdify
Chatbot Widget Embedding
Chatbot Widget Embedding
Type
Topic
Status
Published
Created
Jul 20, 2026
Updated
Jul 24, 2026
Updated by
Dosu Bot

Chatbot Widget Embedding#

Dify's embeddable chatbot widget lets you integrate a Dify chatbot application into any external website. The widget uses an iframe + bubble button model: a fixed bubble button appears on the host page; clicking it reveals an iframe that loads /chatbot/[token] from the Dify instance. You can also skip the bubble entirely and embed the iframe directly.

Key Files#

LayerPath
Embed script (public)web/public/embed.js
Next.js page routeweb/app/(shareLayout)/chatbot/[token]/page.tsx
React componentweb/app/components/base/chat/embedded-chatbot/index.tsx
State hookweb/app/components/base/chat/embedded-chatbot/hooks.tsx
URL param helpersweb/app/components/base/chat/utils.ts

Embedding via embed.js#

Include the script on any HTML page. The difyChatbotConfig object must be defined before the script tag, and the script must be placed after the <body> element :

<script>
  window.difyChatbotConfig = {
    token: 'YOUR_CHATBOT_TOKEN', // required
    baseUrl: 'https://udify.app', // optional; defaults to https://udify.app
  }
</script>
<script src="https://udify.app/embed.min.js" defer></script>

Config Reference#

KeyTypeDefaultDescription
tokenstring—Required. App token from chatbot settings.
baseUrlstringhttps://udify.appBase URL of your Dify instance.
routeSegmentstringchatbotRoute segment; change only for custom deployments.
inputsobject{}Input variable values to pre-populate.
systemVariablesobject{}System variables (internally prefixed sys.*).
userVariablesobject{}User context variables (internally prefixed user.*).
sendOnEnterbooleantruefalse disables Enter-to-send (useful for CJK IME).
draggablebooleanfalseAllow the bubble button to be dragged.
dragAxis'x' | 'y' | 'both''both'Constrain drag direction.
containerPropsobject{}DOM properties/styles applied to the button container.
dynamicScriptbooleanfalseRun immediately instead of waiting for body.onload.
isDevbooleanfalseUses dev.udify.app when true.


URL Structure and Query Parameters#

The iframe loads {baseUrl}/{routeSegment}/{token}?{params} . The page component at /chatbot/[token]/page.tsx renders <EmbeddedChatbot> inside <AuthenticatedLayout>.

All variable values are gzip-compressed then base64-encoded before being appended as query params . The chatbot page decodes them via decodeBase64AndDecompress().

Query parameter namespacing:

PrefixConfig sourceDecoded by
(none)config.inputsgetProcessedInputsFromUrlParams()
sys.config.systemVariablesgetProcessedSystemVariablesFromUrlParams()
user.config.userVariablesgetProcessedUserVariablesFromUrlParams()

Additionally, sendOnEnter=false is passed as a plain (uncompressed) query param .

The redirect_url system parameter is special — the page will merge query strings from its decoded value into the system variable set .

URL length is validated; a console error is logged if it exceeds 2048 characters .


Cross-Origin (postMessage) Protocol#

The embed script and the iframe communicate via window.postMessage with strict origin validation :

  1. Iframe → Parent: dify-chatbot-iframe-ready — signals the iframe has loaded.
  2. Parent → Iframe: dify-chatbot-config — sends { isToggledByButton, isDraggable }.
  3. Iframe → Parent: dify-chatbot-expand-change — triggers the expand/collapse resize on the parent side.

The parent derives targetOrigin from config.baseUrl and validates all incoming messages against it .


CORS for Embedded Endpoints#

Before PR #30587, embedded bots failed cross-origin because CORS preflight requests were rejected. The fix in api/extensions/ext_blueprints.py introduces per-route CORS rules:

  • /chat-messages and /chat-messages/* — supports_credentials=False, allows only Content-Type and the app-code header, methods GET / POST / OPTIONS.
  • All other routes — retain supports_credentials=True with full authenticated headers.

This allows unauthenticated preflight for embedded chat endpoints while keeping authenticated CORS for the console and service API .


Direct iframe Embedding (No Script)#

Skip the bubble UI entirely by pointing a plain <iframe> at the chatbot URL:

<iframe
  src="https://udify.app/chatbot/YOUR_TOKEN"
  style="width: 100%; height: 100%; min-height: 700px"
  allow="microphone;clipboard-write"
></iframe>

Variables can be appended as gzip+base64-encoded query parameters following the same namespacing rules described above.

Documents
Account Activity Tracking
Agent API Routes
Agent App Architecture
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent App Event Architecture
Agent App Input Variables
Agent Cost and Usage Tracking
Agent File Handling
Agent File Upload Configuration
Agent Icon Data Model
Agent Log Event Pipeline
Agent Message History
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent Model Settings
Agent Node Data Models
Agent Response Schema
Agent Runtime
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent Runtime Backend Initialization
Agent Runtime Layer Provider Registration
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent Sandbox SSRF Allowlisting
Agent Shell Layer
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent Strategy Plugin Architecture
Agent V2 Architecture
Dify Agent Server 模块分析 (Commit 55f95dbc)
Agent V2 Configure Interface
Agent V2 Feature Flags
Agent V2 File and Vision Handling
Agent V2 Publish Validation
Agent V2 Variable System
Agent Workflow Node Variable References
API Documentation Pipeline
App Mode Configuration
App Publishing and Embedding
Audio to Text API
Auth Route Architecture
Automatic Rule Generation
Avatar Management
Branding Customization
Browser Tab and State Management
Builtin Tool Provider Credentials
Celery Task Resilience
Chat Action Bar Mobile Visibility
Chat Avatar Rendering
Chatbot Conversation State Recovery
Chatbot Widget Embedding
Collaborative Workflow Editing
Console API DELETE Request Handling
Console Authentication
Conversation Deep-Linking
Credential Encryption and Secret Management
CSV Data Ingestion
Custom Tool Authentication
Custom Tool HTTP Timeout Configuration
Custom Tool OpenAPI Integration
Data Export
Database Migration System
Database Session Management
Database Transaction Isolation
Dataset Batch Import
Dataset Deletion
Dataset Permission Model
Dataset Segmentation Configuration
Dependency Injection and Testability
Dify Agent Server 模块分析 (Commit 55f95dbc)
Dify Agent Monorepo Structure
Dify Agent Server 模块分析 (Commit 55f95dbc)
Dify Cloud Billing
Dify OpenAPI
difyctl CLI
Docker Container Security
Docker Deployment and Upgrades
Docker Frontend Configuration
Docker Image Publishing
Docker Networking
Docker Storage and Permissions
Document Indexing Operations
DocumentSegment Position Assignment
Draft Variable Storage Cleanup
E2B Sandbox Integration
Edition-Based Feature Gating
Elasticsearch Integration
Embedding Cache Integrity
Excel Extractor
External Knowledge Integration
Extractor Encoding Fallback
File Access Control
File Array Handling
File Download Architecture
File Download Security
File Storage Synchronization
File Upload and Download Integrity
File Upload Configuration
File Upload Processing
File URL Resolution
Flask Application Architecture
Flask Blueprint and Route Registration
Graph Streaming Infrastructure
Home Directory Management
HTTP Request Node
HTTP Request Node Key-Value Editor
HTTP Request Node Size Constraints
httpx and Gevent Compatibility
Human Input Node
Hybrid Search
Icon URL Resolution
Iframe Embedding Security
Internationalization and Locale Management
Jina Reranker Integration
JSON-in-Markdown Parsing
JWT Authentication
Keyboard Shortcut Management
Keyword Moderation
Knowledge Base API
Knowledge Base Document Processing
Knowledge Base Metadata Filtering
Knowledge Base Summarization Pipeline
Langfuse Integration
Lexical Editor Integration
LLM Provider Message Validation
LLM Structured Output
Local Development Configuration
Local Embedding Model Deployment
Log Filtering
Markdown Extractor Heading Parsing
Markdown Rendering
Marketplace Plugin Filtering
MCP Client Transport and Connectivity
MCP OAuth Integration
MCP Protocol Integration
MCP Protocol Integration for Dify Workflows
MCP Provider Architecture
MCP Tool Content Processing
MCP Tool Integration
MCP Tool Parameter Binding
MCP Tool Provider Management
Messaging Platform Integration
Milvus Integration
Model Provider Error Handling
Monaco Editor Integration
Multi-Tenant Context Propagation
Multimodal Knowledge Base Support
Multimodal Prompt Delivery
N+1 Query Optimization
Next.js Routing and Redirects
Next.js SSR Authentication
Nginx Reverse Proxy Configuration
Notion Extractor Table Parsing
NumPy CPU Compatibility
OAuth Login Flow
Observability and Tracing
OpenAI-Compatible Server Integration
OpenAPI Spec Accuracy
OpenDAL Storage Backend
Ops Trace Data Models
Oracle Database Connectivity
Parallel Workflow Execution
Parent-Child Retrieval Architecture
Plugin API Key Configuration
Plugin Architecture
Plugin Credential Management
Plugin Daemon Architecture
Plugin Daemon Communication
Plugin Daemon Model Parameter Handling
Plugin Database Integrity
Plugin Error Handling
Plugin File Handling
Plugin Lifecycle Management
Plugin Marketplace Connectivity
Plugin Model Caching
Plugin Permissions
Plugin Storage Configuration
Plugin System Timeouts
Plugin Taxonomy and Validation
Plugin Trigger OAuth Refresh
Private Address Detection
Provider Model & Credential Management
Pyrefly Type Checker
RAG Web Crawling Providers
Rate Limiting and Concurrency Control
RBAC Initialization
RBAC Permission Key Lookup
Reasoning Model Integration
Reasoning Tag Filtering
Redis Connection Management
Redis Streaming Resilience
Release Breaking Changes
Remote File Fetching
Remote File Handling and Validation
Retrieval Filtering and Scoring
RTL Locale Support
Sandbox Code Execution
Sandbox Network Isolation
Segment Update and Attachment Lifecycle
Server Deployment Configuration
Service API Error Handling
Service API Pagination
Shell Provider Lifecycle
Snippet Variable Handling
SQLite Test Infrastructure
SSE Stream Lifecycle
SSE Stream Terminal Event Delivery
SSR Data Fetching
SSRF Proxy
Suggested Questions After Answer
Summary Index
Tenant-Isolated Document Indexing Queue
Test Doubles and In-Memory Repositories
TiDB Vector Full-Text Search
Time Tools
Timestamp Management
Tool File URL Signing
Tool Node Input Validation
Tool OAuth Authorization
Tool Provider Authorization
Trace Task Pipeline
User and Tenant Context Propagation
Dify Agent Server 模块分析 (Commit 55f95dbc)
User Roles and Permissions
Variable Pool Falsy Value Handling
Variable Resolution and Template Substitution
Vector Database Plugin Architecture
Vector Store Integration
Weaviate Vector Store
Web Container Docker Configuration
Webhook Trigger System
WebSocket Service Architecture
Word Document Extraction
Workflow Agent Node Configuration
Workflow and Agent Composition
Workflow Conditional Branching
Workflow Container Nodes
Workflow Conversation State Management
Workflow Draft Synchronization
Workflow Execution Dispatch
Dify Agent Server 模块分析 (Commit 55f95dbc)
Workflow Execution Persistence
Workflow Fail Branch Architecture
Workflow File Handling
Workflow Graph Validation
Workflow Iteration Node Execution
Workflow LLM Node Configuration
Workflow Memory Management
Workflow Node Canvas Summary Rendering
Workflow Node Versioning
Workflow Pause-Resume State Management
Workflow Resume Architecture
Workflow Run State Management
Workflow Schedule Triggers
Workflow Test Run Execution
Workflow Timeout and Execution Limits
Workflow Tool Visibility and Access Control
Workflow Trigger Log Lifecycle
Workflow Variable Size Management