🔧 n8n Workflow Automation Cơ bản
Trong bài này, chúng ta sẽ tìm hiểu các concepts cơ bản của n8n và tạo workflow đầu tiên.
n8n là gì?
n8n Overview
n8n là một workflow automation platform cho phép bạn:
- Kết nối các apps và services
- Tự động hóa tasks lặp đi lặp lại
- Build logic phức tạp với visual editor
- Self-host hoặc dùng cloud
Diagram
graph LR
T[Trigger] --> N1[Node 1]
N1 --> N2[Node 2]
N2 --> N3[Node 3]
N3 --> O[Output]Core Concepts
1. Workflows
Workflow là một chuỗi các nodes được kết nối:
- Trigger: Bắt đầu workflow (schedule, webhook, manual)
- Nodes: Thực hiện actions (HTTP, database, AI, etc.)
- Connections: Kết nối data giữa nodes
2. Nodes
Các loại nodes chính:
| Type | Description | Examples |
|---|---|---|
| Trigger | Khởi động workflow | Webhook, Schedule, Manual |
| Action | Thực hiện task | HTTP, Email, Slack |
| Logic | Control flow | IF, Switch, Merge |
| Transform | Xử lý data | Code, Set, Filter |
3. Expressions
Expressions cho phép dynamic values:
JavaScript
1// Truy cập data từ node trước2{{ $json.name }}34// Truy cập từ node cụ thể5{{ $node["HTTP Request"].json.data }}67// JavaScript expressions8{{ $json.price * 1.1 }}910// Built-in functions11{{ $now.format("YYYY-MM-DD") }}Workflow Đầu tiên
Hello World Workflow
- Manual Trigger: Click để chạy
- Set Node: Tạo data
- Code Node: Xử lý data
Diagram
graph LR
MT[Manual Trigger] --> S[Set: Create Data]
S --> C[Code: Process]
C --> R[Result]Cấu hình Step-by-Step
Step 1: Add Manual Trigger
- Click "+" để add node
- Search "Manual Trigger"
- Node này không cần config
Step 2: Add Set Node
- Add node "Set"
- Click "Add Field"
- Add fields:
name: "John Doe"email: "john@example.com"score: 85
Step 3: Add Code Node
- Add node "Code"
- Chọn JavaScript mode
- Code:
JavaScript
1// Input data2const items = $input.all();34// Process each item5for (const item of items) {6 const score = item.json.score;7 8 // Add grade based on score9 if (score >= 90) {10 item.json.grade = "A";11 } else if (score >= 80) {12 item.json.grade = "B";13 } else if (score >= 70) {14 item.json.grade = "C";15 } else {16 item.json.grade = "D";17 }18 19 // Add timestamp20 item.json.processedAt = new Date().toISOString();21}2223return items;Step 4: Execute
- Click "Execute Workflow"
- Xem kết quả ở mỗi node
HTTP Request Example
Call External API
Diagram
graph LR
MT[Manual Trigger] --> H[HTTP Request]
H --> C[Code: Transform]
C --> O[Output]HTTP Request Node config:
- Method: GET
- URL:
https://api.github.com/users/octocat - Headers:
Accept: application/json
Code Node:
JavaScript
1const items = $input.all();23for (const item of items) {4 // Extract relevant fields5 item.json = {6 username: item.json.login,7 name: item.json.name,8 followers: item.json.followers,9 repos: item.json.public_repos,10 avatar: item.json.avatar_url11 };12}1314return items;Control Flow
IF Node
Tạo conditional logic:
Diagram
graph TD
T[Trigger] --> IF{Score >= 80?}
IF -->|True| A[Send Congratulations]
IF -->|False| B[Send Encouragement]IF Node config:
- Condition:
{{ $json.score }}>= 80 - True output → Node A
- False output → Node B
Switch Node
Multiple conditions:
JavaScript
1// Switch conditions2{{ $json.status }}34// Cases5"pending" → Process pending6"approved" → Send approval7"rejected" → Send rejectionMerge Node
Combine data từ nhiều paths:
Diagram
graph TD
T[Trigger] --> A[Path A]
T --> B[Path B]
A --> M[Merge]
B --> M
M --> O[Output]Loop và Batch Processing
Split In Batches
Xử lý nhiều items:
Diagram
graph LR
T[Trigger] --> S[Split: Batch 10]
S --> P[Process]
P --> |Loop| S
P --> O[Output]Config:
- Batch Size: 10
- Options: Continue on fail
Loop Over Items
Với Code node:
JavaScript
1const results = [];2const items = $input.all();34for (const item of items) {5 // Process each item6 const processed = {7 ...item.json,8 processed: true,9 timestamp: Date.now()10 };11 results.push({ json: processed });12}1314return results;Error Handling
Error Trigger
Catch errors từ workflow khác:
Diagram
graph LR
E[Error Trigger] --> L[Log Error]
L --> N[Notify Admin]Try/Catch trong Code
JavaScript
1try {2 const items = $input.all();3 4 for (const item of items) {5 if (!item.json.required_field) {6 throw new Error("Missing required field");7 }8 // Process...9 }10 11 return items;12 13} catch (error) {14 // Return error info15 return [{16 json: {17 error: true,18 message: error.message,19 timestamp: new Date().toISOString()20 }21 }];22}Credentials
Setup Credentials
- Settings → Credentials
- Click "Add Credential"
- Chọn service (e.g., OpenAI, Slack)
- Nhập API key/secrets
- Save và sử dụng trong nodes
Security
- Không hardcode credentials trong workflows
- Sử dụng credential management của n8n
- Encrypt sensitive data
Best Practices
Workflow Best Practices
- Naming: Đặt tên rõ ràng cho workflows và nodes
- Error Handling: Luôn có error handling
- Testing: Test với sample data trước
- Logging: Add logging cho debugging
- Modularity: Chia nhỏ workflows phức tạp
- Documentation: Comment code và notes
Bài tập thực hành
Hands-on Exercise
Build Your First Workflow:
- Tạo workflow fetch data từ API
- Transform data với Code node
- Add conditional logic với IF node
- Handle errors gracefully
Target: Workflow hoạt động end-to-end với error handling
Tiếp theo
Trong bài tiếp theo, chúng ta sẽ học về Integrations - kết nối n8n với các services phổ biến.
