Lý thuyết
25 phút
Bài 3/7

n8n Basics - Workflow Automation

Giới thiệu n8n và tạo workflow đầu tiên

🔧 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:

TypeDescriptionExamples
TriggerKhởi động workflowWebhook, Schedule, Manual
ActionThực hiện taskHTTP, Email, Slack
LogicControl flowIF, Switch, Merge
TransformXử lý dataCode, Set, Filter

3. Expressions

Expressions cho phép dynamic values:

JavaScript
1// Truy cập data từ node trước
2{{ $json.name }}
3
4// Truy cập từ node cụ thể
5{{ $node["HTTP Request"].json.data }}
6
7// JavaScript expressions
8{{ $json.price * 1.1 }}
9
10// Built-in functions
11{{ $now.format("YYYY-MM-DD") }}

Workflow Đầu tiên

Hello World Workflow

  1. Manual Trigger: Click để chạy
  2. Set Node: Tạo data
  3. 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:

Step 3: Add Code Node

  • Add node "Code"
  • Chọn JavaScript mode
  • Code:
JavaScript
1// Input data
2const items = $input.all();
3
4// Process each item
5for (const item of items) {
6 const score = item.json.score;
7
8 // Add grade based on score
9 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 timestamp
20 item.json.processedAt = new Date().toISOString();
21}
22
23return 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();
2
3for (const item of items) {
4 // Extract relevant fields
5 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_url
11 };
12}
13
14return 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 conditions
2{{ $json.status }}
3
4// Cases
5"pending" Process pending
6"approved" Send approval
7"rejected" Send rejection

Merge 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();
3
4for (const item of items) {
5 // Process each item
6 const processed = {
7 ...item.json,
8 processed: true,
9 timestamp: Date.now()
10 };
11 results.push({ json: processed });
12}
13
14return 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 info
15 return [{
16 json: {
17 error: true,
18 message: error.message,
19 timestamp: new Date().toISOString()
20 }
21 }];
22}

Credentials

Setup Credentials

  1. Settings → Credentials
  2. Click "Add Credential"
  3. Chọn service (e.g., OpenAI, Slack)
  4. Nhập API key/secrets
  5. 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
  1. Naming: Đặt tên rõ ràng cho workflows và nodes
  2. Error Handling: Luôn có error handling
  3. Testing: Test với sample data trước
  4. Logging: Add logging cho debugging
  5. Modularity: Chia nhỏ workflows phức tạp
  6. Documentation: Comment code và notes

Bài tập thực hành

Hands-on Exercise

Build Your First Workflow:

  1. Tạo workflow fetch data từ API
  2. Transform data với Code node
  3. Add conditional logic với IF node
  4. 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.

Tài liệu tham khảo