n8n
The complete guide
Open-source automation without limits. 400+ Integrations, built-in AI Nodes, Self-hosting and full JavaScript — everything you need to build professional-grade automations, for free.
On model versions: the code on this page pins gpt-4o. As of September 2026 providers retire versions and model names change — check the current model list in OpenAI's documentation and swap the string before running. What the code demonstrates does not depend on the version. And on prices: vendor pricing changes often and the figures on this page are not checked automatically. Confirm the current price on the vendor's own pricing page before deciding.
What is n8n and why is it different?
n8n (pronounced "n-eight-n") is an open-source visual automation tool that lets you connect apps, build complex Workflows, and run AI Agents — all in a drag-and-drop interface. Unlike Zapier and Make.com, which run everything in their cloud for a monthly fee, n8n enables full Self-hosting: your data stays with you, and Executions are free forever.
n8n's philosophy is "visual-first, code when needed" — most automations are built visually, but when you need complex logic you can drop full JavaScript into a Code Node. That's what sets it apart from the competition: not a choice between no-code and code, but both together.
n8n vs Zapier vs Make.com — a quick comparison table
| Criterion | n8n | Make.com | Zapier |
|---|---|---|---|
| Self-hosted cost | Free forever 🏆 | Not available | Not available |
| Cloud cost (base) | $20/month | $9/month 🏆 | $19.99/month |
| Ease of use | Medium | Very easy 🏆 | Easy |
| Logical flexibility | Very high 🏆 | Medium | Low |
| Full JavaScript | Yes 🏆 | Limited | No |
| Built-in AI Nodes | Yes — LangChain 🏆 | Limited | Basic |
| Data privacy | Full (Self-hosted) 🏆 | Cloud only | Cloud only |
| Number of Integrations | 400+ | 2,000+ | 7,000+ 🏆 |
n8n wins when you have many Executions, sensitive data that cannot be sent to an external cloud, or when you need complex logic with JavaScript. Make.com / Zapier are better when you want to start fast with 200+ ready-made integrations.
Installation — 3 options
n8n can be installed in three main ways. For most users Docker is the best choice — it is isolated, easy to update, and works identically on every operating system.
Option 1 — Docker (recommended for servers)
# Basic run — n8n available at http://localhost:5678
docker run -it --rm \
--name n8n \
-p 5678:5678 \
-v ~/.n8n:/home/node/.n8n \
n8nio/n8n
Option 2 — Docker Compose (for production)
version: "3"
services:
n8n:
image: n8nio/n8n
restart: always
ports:
- "5678:5678"
volumes:
- ~/.n8n:/home/node/.n8n
environment:
- N8N_BASIC_AUTH_ACTIVE=true
- N8N_BASIC_AUTH_USER=admin
- N8N_BASIC_AUTH_PASSWORD=your_secure_password
- N8N_ENCRYPTION_KEY=your_32_char_key
- N8N_HOST=your-domain.com
- N8N_PORT=5678
- N8N_PROTOCOL=https
Option 3 — npm (for local development)
# Requirement: Node.js 18+
npx n8n
# or global installation
npm install n8n -g
n8n start
# open: http://localhost:5678
Deploy n8n to Railway.app for free (500 hours/month). Search "n8n" in the Railway template library and within 2 minutes you'll have a working n8n environment with a free public URL.
Core concepts
Before building your first Workflow, it's important to understand n8n's basic building blocks.
Triggers — what starts the Workflow?
- Webhook Trigger: An incoming HTTP POST/GET from an external app — the most common way
- Schedule (Cron): Runs on a schedule — every day at 09:00, hourly, the 1st of every month
- App Event Triggers: Listens for specific events — "new email in Gmail", "new row in Sheets"
- Manual Trigger: Manual trigger for testing from the UI
- Error Trigger: Triggered when an error occurs in another Workflow
Nodes — the building blocks of the Workflow
- Input Nodes: Read data — HTTP Request, Google Sheets Read, Database Query
- Process Nodes: Code, Set, IF, Switch, Merge, Loop Over Items, Function
- Output Nodes: Gmail Send, Slack Message, Notion Create Page, DB Insert
- AI Nodes: AI Agent, OpenAI, Claude, Embeddings, Vector Store (see the AI section)
Data Flow — how does data flow?
Each Node receives an array of Items — each Item is a JSON Object. If the previous Node returned 5 items, the next Node processes each of them separately (unless Merge). This is what's called an "implicit loop" — an automatic loop.
Expressions — accessing data
{{ $json.email }} // the email field from the current Item
{{ $json.user.name }} // nested field
{{ $now.format('YYYY-MM-DD') }} // today's date
{{ $items("Gmail Trigger")[0].json.subject }} // a field from a specific Node
{{ $env.MY_API_KEY }} // environment variable
{{ $json.price * 1.17 }} // a math calculation
{{ $json.text.toUpperCase() }} // string operations
{
"id": 1,
"email": "user@example.com",
"name": "John Doe",
"company": "StartupXYZ",
"createdAt": "2026-04-16T09:00:00Z",
"tags": ["lead", "enterprise"]
}
IF / Switch — Branching Logic
- IF Node: Splits into 2 paths by a condition — True / False
- Switch Node: Splits into multiple paths by value (like switch/case in code)
- Loop Over Items: Processes an array — sends a request for each item separately
- Error Trigger + Try/Catch: For structured error handling
First Workflow — step by step
We'll build a full Workflow: a Webhook receives data → sends an HTTP Request to an external API → processes the response → sends an email with the result.
Step 1 — Webhook Trigger
Click "+ Add Node" → search "Webhook" → select Webhook. Configure:
- HTTP Method:
POST - Path:
my-first-workflow - Authentication: None (for testing)
n8n will give you a URL: https://your-n8n.com/webhook/my-first-workflow
Step 2 — HTTP Request Node
Add a Node → HTTP Request. Configure:
Method: GET
URL: https://jsonplaceholder.typicode.com/posts/{{ $json.postId }}
# postId comes from the Webhook body
Step 3 — Set Node (Transform)
Add a Set Node to shape the data:
# Define new Fields:
subject: "New post: {{ $json.title }}"
body: "{{ $json.body }}"
postId: {{ $json.id }}
fetchedAt: {{ $now.toISO() }}
Step 4 — Gmail Node (Send Email)
- Resource:
Message - Operation:
Send - To:
{{ $json.recipientEmail }} - Subject:
{{ $json.subject }} - Message:
{{ $json.body }}
Step 5 — Test!
curl -X POST https://your-n8n.com/webhook/my-first-workflow \
-H "Content-Type: application/json" \
-d '{"postId": 1, "recipientEmail": "you@example.com"}'
Click "Test Workflow" in n8n before Activation. The Webhook will be available for 120 seconds and you'll see the data flow from Node to Node in green.
AI & LLM Nodes — n8n as an AI Orchestrator
This is the most important section for our readers. n8n v1.0+ includes a full LangChain integration with an AI Agent Node, Vector Store Nodes, Embeddings and more — all visually, without a single line of code (if you don't want to).
AI Agent Node — the heart of n8n AI
The AI Agent Node is a LangChain Agent that runs directly in n8n. It receives a Chat Message, decides which Tools to use, runs them, and returns an answer. Tools are other Nodes in n8n — Google Search, Calculator, HTTP Request, Notion, and more.
All the AI Nodes in n8n
- AI Agent: A full Agent with Tool Use — ReAct loop, multi-step reasoning
- OpenAI Chat Model: GPT-4o, GPT-4 Turbo — direct connection to the OpenAI API
- Anthropic (Claude): Claude 3.5 Sonnet/Opus retired — for complex analysis
- Google Gemini: Gemini 1.5 Pro/Flash — a 1M-token context window
- Ollama: Runs local models — Llama 3, Mistral, Qwen (full privacy)
- Embeddings Nodes: OpenAI Embeddings, Google Embeddings — for a Vector DB
- Vector Store Nodes: Pinecone, Supabase pgvector, Qdrant, Chroma
- Chat Memory: Buffer Memory, Summary Memory, Redis Memory — keeping history
- Document Loaders: PDF, CSV, JSON, Website Scraper — for a RAG Pipeline
Code Node — AI Processing with JavaScript
When you need logic the built-in Nodes don't provide, the Code Node allows full JavaScript with access to the entire n8n API:
// Code Node — custom AI processing
const items = $input.all();
const results = [];
for (const item of items) {
const response = await $http.request({
method: 'POST',
url: 'https://api.openai.com/v1/chat/completions',
headers: {
Authorization: `Bearer ${$env.OPENAI_API_KEY}`,
'Content-Type': 'application/json'
},
body: {
model: 'gpt-4o',
messages: [
{
role: 'system',
content: 'You help analyze lead data. Return JSON only.'
},
{
role: 'user',
content: `Analyze the following lead:\n${JSON.stringify(item.json)}`
}
],
response_format: { type: 'json_object' }
}
});
const analysis = JSON.parse(
response.choices[0].message.content
);
results.push({
json: {
...item.json,
aiScore: analysis.score,
aiSummary: analysis.summary,
nextAction: analysis.recommendedAction
}
});
}
return results;
Popular integrations
n8n comes with 400+ Native Nodes and thousands more integrations via the HTTP Request Node (any API with documentation).
Google Workspace
- Gmail: Send, read, search, label, create Drafts, track Attachments
- Google Sheets: Read, write, update, delete, search — an easy database for everyone
- Google Drive: Upload, Download, create folders, share
- Google Calendar: Create events, check availability, update
- Google Docs: Create documents, update content, merge Templates
CRM & Business Tools
- HubSpot: Contacts, Deals, Forms, Emails — a full CRM
- Salesforce: SOQL queries, Leads, Opportunities
- Notion: Databases, Pages, Blocks — a database + wiki
- Airtable: Records, Views, Automations
Communication
- Slack: Messages, Channel management, Files, Webhooks
- Telegram Bot: Send, receive, Inline Keyboards, Media
- WhatsApp Business: Via Twilio or 360dialog — Messages, Templates
- Discord: Bot messages, Channel management
E-commerce & Dev
- Shopify: Orders, Products, Customers, Inventory
- WooCommerce: Orders, Coupons, Products
- GitHub: Issues, PRs, Repos, Webhooks
- Jira / Linear: Issues, Sprints, Comments
- HTTP Request Node: Any API with documentation — unlimited flexibility
Advanced techniques
Sub-workflows — Reusable Components
A Sub-workflow is a Workflow called from another Workflow. It enables modularity — one "Send Email" Sub-workflow that all other Workflows call. One change updates them all.
# To run a Sub-workflow:
# Add a Node: "Execute Workflow"
# Workflow: select the Sub-workflow
# Wait for Sub-workflow Completion: true
# Parameters: { "email": "{{ $json.email }}" }
Webhooks with Authentication
# Header Authentication
Authorization: Bearer {{ $env.WEBHOOK_SECRET }}
# Basic Auth
Username: {{ $env.WEBHOOK_USER }}
Password: {{ $env.WEBHOOK_PASS }}
# HMAC Signature Verification (Code Node)
const crypto = require('crypto');
const signature = $request.headers['x-hub-signature-256'];
const expectedSig = 'sha256=' + crypto
.createHmac('sha256', $env.WEBHOOK_SECRET)
.update(JSON.stringify($request.body))
.digest('hex');
if (signature !== expectedSig) {
throw new Error('Invalid webhook signature');
}
Database Nodes
- PostgreSQL: Execute Query, Insert, Update, Delete — a full database
- MySQL / MariaDB: Query execution + Parameterized queries
- MongoDB: CRUD operations, Aggregation pipelines
- Redis: Get/Set/Delete Keys — for Cache and Queue Mode
- SQLite: For small self-hosted projects
Triggering Workflows Programmatically
# Trigger a Webhook from the Terminal
curl -X POST https://your-n8n.com/webhook/my-workflow \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_SECRET" \
-d '{"action": "process", "userId": 123, "data": "hello"}'
# Trigger via the n8n REST API
curl -X POST https://your-n8n.com/api/v1/workflows/1/activate \
-H "X-N8N-API-KEY: your-api-key"
Queue Mode — Scaling for high volume
For sites with thousands of Executions per hour, n8n supports Queue Mode with Redis:
# .env for Queue Mode
EXECUTIONS_MODE=queue
QUEUE_BULL_REDIS_HOST=redis
QUEUE_BULL_REDIS_PORT=6379
N8N_CONCURRENCY_PRODUCTION_LIMIT=10
# Docker Compose with Redis
services:
redis:
image: redis:7-alpine
restart: always
n8n-main:
image: n8nio/n8n
environment:
- EXECUTIONS_MODE=queue
n8n-worker:
image: n8nio/n8n
command: n8n worker
scale: 3 # 3 worker processes
1. Set N8N_ENCRYPTION_KEY (32+ characters) before the first deployment. 2. Enable Basic Auth or a Reverse Proxy with HTTPS. 3. Back up ~/.n8n daily — where all the Workflows live. 4. Set N8N_LOG_LEVEL=info and monitor Error logs.
n8n vs Make.com vs Zapier — a full analysis
All the tools are good — the question is what your case is. Here's how to decide:
| Situation | Choose n8n | Choose Make.com | Choose Zapier |
|---|---|---|---|
| Tight budget | ✓ Self-hosted free | — | — |
| Sensitive data | ✓ Data at home | — | — |
| Many integrations | 400+ | 2,000+ | ✓ 7,000+ |
| Fast start | — | ✓ Easy onboarding | — |
| Complex AI Agents | ✓ LangChain built-in | — | — |
| Complex JavaScript | ✓ Full JS | — | — |
| Completely non-technical | — | ✓ The friendliest UI | — |
| Enterprise + Support | — | — | ✓ Enterprise support |
Most businesses start with Make.com (easy to start) and move to n8n Self-hosted when Executions raise the pricing, or when they need advanced AI Agents. There's no problem holding both.
5 ready-to-build projects
5 real Workflows ready to copy, ordered by difficulty:
Every website form submission → Google Sheets → a welcome email → Mailchimp
RSS Feeds → AI summarizes → an automatic scheduled LinkedIn + Twitter Post
WhatsApp message → AI classifies and replies → Notion Ticket → Slack Alert to the team
Gmail → Claude analyzes and drafts a reply → saves a Draft → Human-in-the-loop approval
A Lead comes in → AI Qualify → CRM → Slack Alert → AI Personalized Email Sequence
Cheat sheet — Quick Reference
Common Expressions
// accessing data
{{ $json.fieldName }} // a Basic field
{{ $json.nested.field }} // nested
{{ $json.array[0].value }} // first in the array
// date and time
{{ $now.toISO() }} // ISO format
{{ $now.format('DD/MM/YYYY') }} // day/month/year format
{{ $now.minus({days: 7}).toISO() }} // one week back
// files and environment
{{ $env.MY_SECRET_KEY }} // env variable
{{ $binary.data }} // binary data (files)
// another Node
{{ $items("Node Name")[0].json.field }} // from a specific Node
{{ $("Node Name").first().json.field }} // shortcut
// Conditional
{{ $json.score > 80 ? "VIP" : "Standard" }} // ternary
Common Cron Expressions
| Expression | Meaning |
|---|---|
| 0 9 * * 1-5 | Every workday at 09:00 |
| 0 */2 * * * | Every two hours |
| */15 * * * * | Every 15 minutes |
| 0 8 1 * * | The 1st of the month at 08:00 |
| 0 23 * * 0 | Every Sunday at 23:00 |
| 0 0 * * * | Midnight every night |
Common Node Patterns
# Pattern 1 — Enrich Data
HTTP Request (GET /users/{id}) → Set (merge fields) → output
# Pattern 2 — Filter + Route
IF (score > 80) → [True] Premium path / [False] Standard path
# Pattern 3 — Batch Processing
Split In Batches (size: 10) → HTTP Request → Wait (1s) → Merge
# Pattern 4 — Error Handling
Try: [Main Workflow] → Catch: Error Trigger → Slack Alert + Retry
# Pattern 5 — RAG Pipeline
Document Loader → Text Splitter → Embeddings → Vector Store Insert
Webhook Testing Tips
- Usengrok for local development:
ngrok http 5678— generates a temporary public URL - Click "Listen for Test Event" in n8n before sending the Webhook
- Webhook.site — a free tool to inspect the Payload before connecting to n8n
- Always check the Response Code — n8n returns 200 even if the Workflow failed
Important Environment Variables
N8N_ENCRYPTION_KEY=32_char_secret_key # required!
N8N_HOST=your-domain.com
N8N_PORT=5678
N8N_PROTOCOL=https
N8N_BASIC_AUTH_ACTIVE=true
N8N_BASIC_AUTH_USER=admin
N8N_BASIC_AUTH_PASSWORD=secure_password
N8N_LOG_LEVEL=info # debug | info | warn | error
EXECUTIONS_DATA_SAVE_ON_SUCCESS=all # keep history
EXECUTIONS_DATA_MAX_AGE=168 # keep 7 days (hours)
The next step
Now that you know n8n — the natural next step is to integrate AI Agents. n8n + the Claude API = an AI Agent that can act in every business tool you've connected. The AI Agents guide will help you build a real Agent with Tool Use and RAG.