n8n v2
Comprehensive n8n v2.0 reference for building workflow automation. Use this skill when working with n8n workflows, especially for (1) creating workflow JSON files for import, (2) implementing human-in-the-loop approval workflows with Wait nodes, (3) troubleshooting Execute Sub-Workflow node issues, (4) setting up API credentials (LinkedIn, Anthropic, NewsAPI), (5) building orchestrator patterns with sub-workflows, (6) using expressions in nodes, (7) understanding MCP server limitations, or (8) any n8n workflow development task.
By- name:
- n8n-v2
- description:
- Comprehensive n8n v2.0 reference for building workflow automation. Use this skill when working with n8n workflows, especially for (1) creating workflow JSON files for import, (2) implementing human-in-the-loop approval workflows with Wait nodes, (3) troubleshooting Execute Sub-Workflow node issues, (4) setting up API credentials (LinkedIn, Anthropic, NewsAPI), (5) building orchestrator patterns with sub-workflows, (6) using expressions in nodes, (7) understanding MCP server limitations, or (8) any n8n workflow development task.
n8n v2.0 Workflow Development
Overview
Comprehensive reference for building n8n workflows using v2.0 patterns and best practices. This skill provides complete documentation for nodes, expressions, patterns, troubleshooting, and production-ready examples.
Quick Start Guide
1. Test APIs First
curl -X GET "https://api.example.com/endpoint" \
-H "Authorization: Bearer $TOKEN"
2. Create Workflow JSON
Generate workflow JSON with nodes and connections.
3. Import into n8n
n8n UI > Settings > Import from File
4. Configure & Fix
- Replace Execute Sub-Workflow nodes (if needed)
- Configure credentials
- Test each node
5. Test Execution
Use MCP server mcp__n8n__execute_workflow or manual trigger
Core Concepts
n8n MCP Server Integration
What it CAN do:
- ✅ Search workflows
- ✅ View workflow details
- ✅ Execute workflows
What it CANNOT do:
- ❌ Create workflows
- ❌ Modify workflows
- ❌ Manage credentials
Workaround: Generate JSON files, import via UI
📖 Deep dive: references/mcp-limitations.md
Node Library
Complete reference for all n8n nodes:
Trigger Nodes: Manual Trigger, Execute Workflow Trigger Data Processing: Code, Set, Merge, Filter, Split in Batches Flow Control: IF, Wait Integration: HTTP Request, RSS Feed Read Action: Execute Workflow, Respond to Webhook
Each node documented with configuration examples, parameters, and patterns.
📖 Complete reference: references/node-library.md
Expression Syntax
Dynamic values in node parameters using ={{ expression }}:
{{ $json.field }} // Current item
{{ $('Node Name').first().json.field }} // Cross-node
{{ $json.url || 'default' }} // Fallback
{{ new Date().toISOString() }} // Date/time
`urn:li:person:${$json.sub}` // Template literal
📖 Complete guide: references/expression-syntax.md
Common Workflows
Human-in-the-Loop Approval
Use Wait nodes with forms (NOT respondToWebhook):
Trigger → Generate Content → Wait Node (form) → IF → Action
📖 Complete patterns: references/wait-nodes-guide.md
Multi-Workflow Orchestration
Orchestrator coordinates sub-workflows:
Main Orchestrator
├── Trigger
├── Execute Sub-Workflow: Data Fetcher
├── Wait Node: Review
├── Execute Sub-Workflow: Processor
└── Execute Sub-Workflow: Output
📖 All patterns: references/workflow-patterns.md
News Aggregation
Multi-source data fetch, normalize, merge, deduplicate, rank:
Trigger
├── HTTP Request: Source 1 → Normalize
├── HTTP Request: Source 2 → Normalize
└── RSS Feed: Source 3 → Normalize
→ Merge → Deduplicate → Rank
📖 Detailed patterns: references/workflow-patterns.md
AI Content Generation
Sub-workflow pattern for AI content:
Execute Workflow Trigger
→ Code: Build Prompt
→ HTTP Request: AI API
→ Code: Extract Response
📖 Implementation: references/workflow-patterns.md
Critical Issues & Solutions
Execute Sub-Workflow "Out of Date" Error
Problem: Imported nodes show error after import
Solution:
- Delete old Execute Sub-Workflow nodes
- Add fresh nodes from palette
- Select "Database" and choose workflow
📖 Detailed troubleshooting: references/execute-sub-workflow-issues.md
Wait Node Not Pausing
❌ Wrong: respondToWebhook, Set nodes, IF on unset fields
✅ Correct: Wait node with resume: "form"
📖 Complete guide: references/wait-nodes-guide.md
LinkedIn unauthorized_scope_error
❌ Turn OFF both: "Organization Support" and "Legacy" toggles
📖 All auth issues: references/api-credentials.md
Templates & Examples
Basic Templates
Starting points for common structures:
assets/templates/wait-node-approval-template.jsonassets/templates/orchestrator-template.jsonassets/templates/sub-workflow-template.json
Complete Workflow Examples
Production-ready workflows you can import and use:
News Aggregation - Multi-source fetch, normalize, deduplicate, rank
assets/examples/news-aggregation-workflow.jsonContent Generation - AI-powered content creation sub-workflow
assets/examples/content-generation-workflow.jsonLinkedIn Member ID - Retrieve your LinkedIn member URN
assets/examples/linkedin-member-id-workflow.jsonMulti-Source Deduplication - Merge and deduplicate pattern
assets/examples/multi-source-deduplication-workflow.json
Code Snippet Library
Reusable JavaScript for Code nodes:
Deduplication - Remove duplicates by URL, title, ID, or multiple fields
code-snippets/deduplication.jsRanking Algorithms - Multi-factor ranking (relevance, recency, engagement)
code-snippets/ranking-algorithms.jsData Normalization - Unify data from different API sources
code-snippets/data-normalization.jsForm Data Preparation - Format data for Wait node forms
code-snippets/form-data-preparation.jsCross-Node Data Access - Reference data from other nodes
code-snippets/cross-node-data-access.js
API Credentials Quick Reference
LinkedIn OAuth2:
- Scopes:
openid,profile,w_member_social - ❌ OFF: Organization Support, Legacy
- URN format:
urn:li:person:{id}
Anthropic API:
- Header:
x-api-key - Model:
claude-3-5-sonnet-20241022 - Temp: 0.7, Max tokens: 400
NewsAPI:
- Header:
X-Api-Key - Endpoints:
/v2/everything,/v2/top-headlines - Free tier: 100 requests/day
📖 Complete setup: references/api-credentials.md
Reference Documentation
Core References
- node-library.md - Comprehensive node documentation
- expression-syntax.md - Complete expression guide
- workflow-patterns.md - Common workflow architectures
- wait-nodes-guide.md - Human-in-the-loop patterns
- api-credentials.md - Authentication setup
- mcp-limitations.md - MCP server constraints
- execute-sub-workflow-issues.md - Sub-workflow troubleshooting
- troubleshooting.md - Common issues and solutions
Official n8n Documentation
Open this reference as its own page
API Credentials Setup Guide
LinkedIn OAuth2
App Setup
- Create app at https://www.linkedin.com/developers/apps
- Configure OAuth redirect URLs in app settings
- Required scopes:
openid,profile,w_member_social
n8n Credential Configuration
Important toggles (both must be OFF):
- ❌ Turn OFF "Organization Support" toggle
- ❌ Turn OFF "Legacy" toggle
Both toggles cause unauthorized_scope_error if enabled.
Getting Your Member ID
LinkedIn requires your member ID in URN format for posting and profile operations.
Method: Use LinkedIn UserInfo API
Create a simple workflow:
- Manual Trigger
- HTTP Request to
https://api.linkedin.com/v2/userinfo - Use LinkedIn OAuth2 credentials
- Extract
subfield from response
Configuration:
{
"method": "GET",
"url": "https://api.linkedin.com/v2/userinfo",
"authentication": "predefinedCredentialType",
"nodeCredentialType": "linkedInOAuth2Api"
}
Response:
{
"sub": "abc123xyz", // This is your member ID
"name": "Your Name",
"email": "your@email.com"
}
URN Format:
The member ID must be formatted as a URN for LinkedIn API calls:
urn:li:person:{member_id}
Examples:
- If
subiss7_nIa3ccD, useurn:li:person:s7_nIa3ccD - If
subisabc123, useurn:li:person:abc123
In expressions:
// Convert sub to URN
={{ `urn:li:person:${$json.sub}` }}
See also: assets/examples/linkedin-member-id-workflow.json for complete workflow example
Anthropic API
Setup
- Get API key from https://console.anthropic.com/
- Add as "Header Auth" credential in n8n
- Header name:
x-api-key - Header value: Your API key
Common Models
claude-3-5-sonnet-20241022- Best for content generationclaude-3-opus-20240229- Most capable, higher costclaude-3-haiku-20240307- Fastest, lowest cost
Recommended Parameters for Content Generation
{
"model": "claude-3-5-sonnet-20241022",
"temperature": 0.7,
"max_tokens": 400
}
NewsAPI
Setup
- Get API key from https://newsapi.org/
- Add as "Header Auth" credential in n8n
- Header name:
X-Api-Key - Header value: Your API key
Rate Limits
Free tier: 100 requests/day (sufficient for most use cases)
Common Endpoints
/v2/everything - Search All Articles
Search through millions of articles from news sources and blogs.
URL: https://newsapi.org/v2/everything
Query Parameters:
q: Keywords or phrases to search for (required)sources: Comma-separated news source IDsfrom: Earliest date to retrieve (ISO 8601)to: Latest date to retrieve (ISO 8601)language: 2-letter ISO-639-1 code (e.g.,en)sortBy:relevancy,popularity, orpublishedAtpageSize: Number of results (max 100)
Example:
{
"url": "https://newsapi.org/v2/everything",
"qs": {
"q": "AI OR automation",
"language": "en",
"sortBy": "publishedAt",
"pageSize": 50
}
}
/v2/top-headlines - Breaking News
Get breaking news headlines for a country and category.
URL: https://newsapi.org/v2/top-headlines
Query Parameters:
country: 2-letter ISO 3166-1 code (e.g.,us)category:business,entertainment,general,health,science,sports,technologyq: Keywords to search forpageSize: Number of results (max 100)
Example:
{
"url": "https://newsapi.org/v2/top-headlines",
"qs": {
"country": "us",
"category": "technology",
"pageSize": 20
}
}
Response Format
Article structure:
{
"source": {
"id": "source-id",
"name": "Source Name"
},
"author": "Author Name",
"title": "Article Title",
"description": "Article description",
"url": "https://article-url.com",
"urlToImage": "https://image-url.com/image.jpg",
"publishedAt": "2024-01-15T10:30:00Z",
"content": "Article content..."
}
Important notes:
- NewsAPI doesn't provide engagement scores (likes, shares, comments)
- For ranking by relevance, implement custom scoring based on keywords, recency, and source
publishedAtis in ISO 8601 format
Data Normalization Example
Normalize NewsAPI response to common schema:
{
"assignments": {
"assignments": [
{
"name": "title",
"value": "={{ $json.title }}",
"type": "string"
},
{
"name": "url",
"value": "={{ $json.url }}",
"type": "string"
},
{
"name": "source",
"value": "={{ $json.source.name }}",
"type": "string"
},
{
"name": "timestamp",
"value": "={{ $json.publishedAt }}",
"type": "string"
},
{
"name": "summary",
"value": "={{ $json.description }}",
"type": "string"
},
{
"name": "score",
"value": 0,
"type": "number"
}
]
}
}
General Troubleshooting
Authentication Errors
- Verify API key is correct and not expired
- Check header names match exactly (case-sensitive)
- Ensure required scopes are granted (OAuth)
Rate Limiting
- Implement exponential backoff for retries
- Cache responses when possible
- Use webhook triggers instead of polling when available
Open this reference as its own page
Execute Workflow Node Issues
Node Naming Clarification
Important: In n8n v2.0+, the Execute Workflow node:
- Node type in JSON: Still
n8n-nodes-base.executeWorkflow(unchanged) - UI label: Changed to "Execute Sub-Workflow" in the node palette
- Functionality: Same as before - executes other workflows
This is NOT an error: Having "type": "n8n-nodes-base.executeWorkflow" in your JSON is correct for v2.0.
The Problem
When importing workflows via JSON, Execute Workflow nodes sometimes show an error after import.
Error message: "This node is out of date. Please upgrade by removing it and adding a new one"
When this happens:
- After importing a workflow JSON file into n8n
- The node appears in the workflow with an error indicator
- The workflow cannot execute until the node is fixed
When this does NOT happen:
- When reviewing JSON files (the JSON itself is fine)
- When the node type is
n8n-nodes-base.executeWorkflow(this is correct)
Why This Happens
The Execute Workflow node configuration structure can become incompatible during import/export cycles, especially:
- When importing workflows exported from different n8n versions
- When node internal structure has changed between versions
- When workflow references become stale
Solution
If you see the "out of date" error after importing:
- Import the workflow JSON (Execute Workflow nodes may show errors)
- Delete the old Execute Workflow nodes showing errors
- Add fresh "Execute Sub-Workflow" nodes from the node palette (they use the same
executeWorkflowtype) - Select "Database" as source
- Choose the target workflow from the dropdown
Best Practice
When creating workflow JSON files for import:
- Option 1: Include Execute Workflow nodes normally - they usually import fine
- Option 2: If you experience import issues, omit these nodes and add them manually after import
- Option 3: Document which nodes might need recreation after import
Identifying Execute Workflow Nodes in JSON
Correct node structure in v2.0:
{
"parameters": {
"source": "database",
"workflowId": "={{ $('Select Workflow').item.json.workflowId }}"
},
"name": "Execute Sub-Workflow",
"type": "n8n-nodes-base.executeWorkflow",
"typeVersion": 1,
"position": [820, 300]
}
Key points:
"type": "n8n-nodes-base.executeWorkflow"is correct (not "executeSubWorkflow")"name"can be anything (commonly "Execute Sub-Workflow" or "Execute Workflow")- UI shows this as "Execute Sub-Workflow" in the palette, but JSON type is unchanged
When to Recreate These Nodes
Recreate only if:
- ✅ You see "This node is out of date" error after importing
- ✅ The node shows a red error indicator in the workflow
- ✅ The workflow execution fails with this node
Do NOT recreate if:
- ❌ You only see
executeWorkflowin the JSON (this is normal) - ❌ The node is working fine after import
- ❌ You're just reviewing the JSON file before importing
See Also
references/node-library.md- Complete Execute Workflow node documentationreferences/workflow-patterns.md- Orchestrator patterns using Execute Workflow nodes
Open this reference as its own page
n8n Expression Syntax Guide
Complete reference for expressions used in n8n workflows. Expressions allow dynamic values in node parameters using ={{ expression }} syntax.
Table of Contents
- Basic Syntax
- Cross-Node References
- String Operations
- Conditional Expressions
- Array Operations
- Object Operations
- Date/Time Operations
- Regular Expressions
- Number Operations
- JSON Operations
- Input Access Functions
- Common Patterns
- Expressions in Different Node Types
- Debugging Expressions
Basic Syntax
Accessing Current Item
{{ $json.fieldName }} // Get field from current item
{{ $json['field name'] }} // Field with spaces or special characters
{{ $json.nested.field }} // Nested field access
{{ $json.array[0] }} // Array element by index
{{ $json.object.nested.deep }} // Deep nested access
Data Types
All JavaScript data types are supported:
{{ $json.stringField }} // String
{{ $json.numberField }} // Number
{{ $json.booleanField }} // Boolean
{{ $json.objectField }} // Object
{{ $json.arrayField }} // Array
{{ $json.nullField }} // null
Expression Prefix
Expressions MUST start with = in node configuration:
// In node parameter
"value": "={{ $json.field }}" // Expression (evaluated)
"value": "static text" // Literal (not evaluated)
"url": "=https://api.com/{{ $json.id }}" // Expression with text
Cross-Node References
Access Another Node's Output
// First item from named node
{{ $('Node Name').item.json.field }}
{{ $('Node Name').first().json.field }}
// All items from named node
{{ $('Node Name').all() }}
// Specific item by index
{{ $('Node Name').item(0).json.field }}
{{ $('Node Name').item(1).json.field }}
// Check if node has data
{{ $('Node Name').itemMatching(0) }}
Real example from workflow:
// Access data prepared before Wait node
const preparedData = $('Prepare Review').first().json;
const stories = preparedData.stories;
Access Node Parameters
{{ $parameter.workflowId }} // Node parameter value
{{ $parameter.fieldName }} // Any configured parameter
Access Workflow Information
{{ $workflow.id }} // Current workflow ID
{{ $workflow.name }} // Current workflow name
{{ $workflow.active }} // Is workflow active
String Operations
Concatenation
// Using + operator
{{ "Hello " + $json.name }}
// Using template literals
{{ `${$json.firstName} ${$json.lastName}` }}
{{ `Score: ${$json.score}` }}
String Methods
{{ $json.text.toLowerCase() }}
{{ $json.text.toUpperCase() }}
{{ $json.text.trim() }}
{{ $json.text.substring(0, 100) }}
{{ $json.text.slice(0, 100) }}
{{ $json.text.replace('old', 'new') }}
{{ $json.text.split(',') }}
{{ $json.text.includes('keyword') }}
{{ $json.text.startsWith('prefix') }}
{{ $json.text.endsWith('suffix') }}
{{ $json.text.length }}
Template Literals
// Dynamic URLs
={{ `https://api.com/item/${$json.id}` }}
={{ `https://example.com/user/${$json.username}/posts` }}
// Formatted strings
={{ `Score: ${$json.score}, Rank: ${$json.rank}` }}
={{ `Posted ${$json.commentsCount} comments` }}
Real Example - URL Construction
// Hacker News item URL
={{ $json.url || `https://news.ycombinator.com/item?id=${$json.id}` }}
Conditional Expressions
Ternary Operator
// Basic ternary
{{ $json.score > 50 ? 'High' : 'Low' }}
// With computations
{{ $json.points > 100 ? $json.points * 2 : $json.points }}
// Nested ternary
{{ $json.score > 100 ? 'Excellent' : $json.score > 50 ? 'Good' : 'Poor' }}
Logical OR for Defaults
// Fallback to default
{{ $json.url || 'https://example.com' }}
{{ $json.title || 'Untitled' }}
{{ $json.score || 0 }}
// Chain multiple fallbacks
{{ $json.description || $json.summary || $json.title || 'No description' }}
Nullish Coalescing
// Use ?? for null/undefined only (not empty string or 0)
{{ $json.value ?? 'default' }}
Optional Chaining
// Safe property access
{{ $json.user?.email }}
{{ $json.settings?.theme?.color }}
// With fallback
{{ $json.user?.email ?? 'no-email@example.com' }}
Array Operations
Array Methods
// Length
{{ $json.items.length }}
// Join
{{ $json.tags.join(', ') }}
// Map
{{ $json.items.map(x => x.name) }}
{{ $json.items.map(x => x.price * 1.1) }}
// Filter
{{ $json.items.filter(x => x.score > 50) }}
{{ $json.items.filter(x => x.active === true) }}
// Find
{{ $json.items.find(x => x.id === 123) }}
{{ $json.items.find(x => x.name === 'target') }}
// Some/Every
{{ $json.items.some(x => x.urgent) }}
{{ $json.items.every(x => x.validated) }}
// Sort
{{ $json.items.sort((a, b) => b.score - a.score) }}
// Slice
{{ $json.items.slice(0, 5) }} // First 5 items
Real Example - Extract Hashtags
// Match all hashtags
{{ $json.text.match(/#\w+/g) }}
// Join as string
{{ $json.text.match(/#\w+/g)?.join(' ') || '' }}
Object Operations
Access Properties
// Dot notation
{{ $json.user.email }}
{{ $json.settings.notifications.email }}
// Bracket notation (for special characters)
{{ $json['field-with-dashes'] }}
{{ $json['field with spaces'] }}
{{ $json['2024-data'] }} // Starts with number
Object Methods
// Get keys
{{ Object.keys($json) }}
{{ Object.keys($json.settings) }}
// Get values
{{ Object.values($json) }}
// Get entries
{{ Object.entries($json) }}
Date/Time Operations
Current Time
// Current timestamp
{{ new Date().toISOString() }}
{{ Date.now() }} // Unix timestamp (ms)
// Formatted date
{{ new Date().toLocaleDateString() }}
{{ new Date().toLocaleTimeString() }}
Parse and Format
// Parse date string to ISO
{{ new Date($json.timestamp).toISOString() }}
// Convert Unix timestamp (seconds) to ISO
={{ new Date($json.time * 1000).toISOString() }}
// Get timestamp
{{ new Date($json.pubDate).getTime() }}
Date Calculations
// Age in hours
{{ (Date.now() - new Date($json.timestamp).getTime()) / (1000 * 60 * 60) }}
// Age in days
{{ (Date.now() - new Date($json.timestamp).getTime()) / (1000 * 60 * 60 * 24) }}
// Add days
{{ new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString() }}
Real Example - Time-based Scoring
// Recent = higher score
const ageHours = (Date.now() - new Date($json.timestamp).getTime()) / (1000 * 60 * 60);
const recencyScore = ageHours < 6 ? 3 : ageHours < 24 ? 2 : ageHours < 48 ? 1 : 0;
Regular Expressions
Pattern Matching
// In Filter node
"operation": "regex",
"value2": "(?i)(AI|machine learning|automation)"
// In Code node
const match = $json.title.match(/(?i)(AI|ML|automation)/);
if (match) {
// Keyword found
}
// Test pattern
{{ /pattern/.test($json.field) }}
// Extract matches
{{ $json.text.match(/\d+/g) }} // All numbers
{{ $json.text.match(/@\w+/g) }} // All @mentions
Case-Insensitive Flag
// (?i) at start of pattern for case-insensitive
"(?i)(keyword1|keyword2)"
// Or use /i flag
/keyword/i.test($json.text)
Real Example - Keyword Filtering
// Multiple keywords, case-insensitive
"value2": "(?i)(AI|machine learning|automation|n8n|workflow|API)"
Number Operations
Math Operations
// Basic arithmetic
{{ $json.score * 2 }}
{{ $json.price + $json.tax }}
{{ $json.total / $json.count }}
{{ $json.quantity - $json.used }}
// Math functions
{{ Math.round($json.value) }}
{{ Math.floor($json.value) }}
{{ Math.ceil($json.value) }}
{{ Math.max($json.a, $json.b) }}
{{ Math.min($json.a, $json.b) }}
{{ Math.abs($json.value) }}
{{ Math.pow($json.base, 2) }}
{{ Math.sqrt($json.value) }}
Number Formatting
// Fixed decimals
{{ $json.price.toFixed(2) }}
// Parse string to number
{{ parseInt($json.stringNumber) }}
{{ parseFloat($json.stringDecimal) }}
{{ Number($json.stringValue) }}
JSON Operations
Parse and Stringify
// Parse JSON string
{{ JSON.parse($json.jsonString) }}
// Stringify object
{{ JSON.stringify($json.object) }}
// Stringify with formatting
{{ JSON.stringify($json.object, null, 2) }}
Quote Filter
For embedding strings in JSON bodies:
"jsonBody": "={\n \"content\": {{ $json.text | quote }}\n}"
The | quote filter properly escapes strings for JSON.
Input Access Functions
In Code Nodes
// Get all input items
$input.all()
// Returns: [{ json: {...} }, { json: {...} }, ...]
// Get first item
$input.first()
// Returns: { json: {...} }
// Get last item
$input.last()
// Get current item in iteration
$input.item
// Access JSON directly
$input.first().json.field
Return Format Requirement
Code nodes MUST return array of objects with json property:
// Correct
return [{ json: { result: 'data' } }];
// Multiple items
return [
{ json: { id: 1 } },
{ json: { id: 2 } }
];
// Transform all
return $input.all().map(item => ({
json: {
...item.json,
processed: true
}
}));
// Wrong (will fail)
return { result: 'data' };
return 'data';
Common Patterns
URL Normalization
// Normalize URL for comparison
const normalizedUrl = $json.url
.toLowerCase()
.replace(/^https?:\/\/(www\.)?/, '')
.replace(/\/$/, '');
Field with Fallback Chain
// Try multiple fields
{{ $json.description || $json.summary || $json.title || 'No description' }}
{{ $json.image || $json.thumbnail || $json.icon || '/default.png' }}
Conditional Field Access
// Check existence before access
{{ $json.user ? $json.user.email : 'No email' }}
// Optional chaining (safer)
{{ $json.user?.email ?? 'No email' }}
LinkedIn Member URN Format
// Convert member ID to URN format
`urn:li:person:${$json.sub}`
// Example: { "sub": "abc123" } → "urn:li:person:abc123"
Extract Domain from URL
// In Code node
const domain = new URL($json.url).hostname.replace(/^www\./, '');
// In expression
{{ new URL($json.url).hostname }}
Score Normalization
// Normalize different scoring systems to 0-1
const normalized = $json.score / 100;
// Or to 0-10 scale
const scaled = ($json.score / $json.maxScore) * 10;
Expressions in Different Node Types
Set Node
{
"assignments": {
"assignments": [
{
"name": "title",
"value": "={{ $json.headline }}",
"type": "string"
}
]
}
}
HTTP Request URL
{
"url": "=https://api.example.com/item/{{ $json.id }}.json"
}
HTTP Request JSON Body
{
"jsonBody": "={{ JSON.stringify({ query: $json.searchTerm }) }}"
}
Filter Conditions
{
"conditions": {
"number": [
{
"value1": "={{ $json.score }}",
"operation": "larger",
"value2": 20
}
]
}
}
Wait Node Form Description
Supports markdown:
{
"formDescription": "## Story Title\n\n{{ $json.title }}\n\n**URL:** {{ $json.url }}\n\n**Score:** {{ $json.score }}"
}
Dynamic content from previous node:
{
"formDescription": "={{ $json.storyList }}"
}
IF Node Conditions
{
"conditions": {
"string": [
{
"value1": "={{ $json['Action'] }}",
"operation": "equals",
"value2": "Approve"
}
]
}
}
Code Node
NO ={{ }} needed in Code nodes - write plain JavaScript:
// Direct JavaScript
const input = $input.first().json;
const result = input.score * 2;
return [{ json: { doubled: result } }];
Debugging Expressions
View Expression Results
- Execute the node
- Click node to view output
- Check "Output" tab for results
- Inspect data structure
Common Errors
Undefined field:
{{ $json.nonexistent }} // Returns undefined
Type mismatch:
{{ $json.stringNumber + 5 }} // May concatenate instead of add
{{ Number($json.stringNumber) + 5 }} // Correct
Syntax error:
{{ $json.field }} // Correct
{{ $json.field } // Wrong - missing closing brace
Cross-node reference before execution:
{{ $('Node Name').item.json.field }}
// Error if "Node Name" hasn't executed yet
Safe Field Access
// Use optional chaining
{{ $json.user?.email ?? 'default@example.com' }}
// Or ternary
{{ $json.user ? $json.user.email : 'default@example.com' }}
// Or logical OR (but treats empty string as falsy)
{{ $json.email || 'default@example.com' }}
Type Checking
// Check if field exists
{{ $json.field !== undefined }}
// Check type
{{ typeof $json.field === 'string' }}
// Check if array
{{ Array.isArray($json.field) }}
Performance Tips
Simple expressions in Set nodes, complex logic in Code nodes
- Set node:
={{ $json.field.toUpperCase() }} - Code node: Complex transformations, loops, multiple operations
- Set node:
Avoid repeated cross-node access
// Bad - accesses node 3 times {{ $('Node').item.json.a + $('Node').item.json.b + $('Node').item.json.c }} // Good - use Code node const data = $('Node').first().json; const sum = data.a + data.b + data.c;Cache computed values
// In Code node, compute once const normalized = $input.all().map(item => ({ json: { ...item.json, normalizedUrl: normalizeUrl(item.json.url) } }));Use Code nodes for loops rather than complex array expressions
See Also
references/node-library.md- Node-specific expression usagecode-snippets/- Reusable expression patternsassets/examples/- Real workflow examples- n8n Expression Documentation
Open this reference as its own page
n8n MCP Server Limitations
Overview
The n8n MCP (Model Context Protocol) server integration allows Claude to interact with your n8n instance, but has important limitations to understand before working with workflows.
Key point: The MCP server provides read-only and execution capabilities. It CANNOT create or modify workflows directly.
What the MCP Server CAN Do
1. View Workflows
Tool: mcp__n8n__search_workflows
Capabilities:
- Search for workflows by name
- List all workflows in n8n instance
- Get workflow metadata (ID, name, active status)
Example use cases:
- "Search for workflows containing 'LinkedIn'"
- "Show me all workflows"
- "Find the news aggregation workflow"
2. Get Workflow Details
Tool: mcp__n8n__get_workflow_details
Capabilities:
- Read complete workflow JSON structure
- View node configurations
- Inspect node connections
- See parameter settings
Example use cases:
- "Show me how the content generator workflow is structured"
- "What nodes are in the main orchestrator?"
- "How is the Wait node configured in this workflow?"
3. Execute Workflows
Tool: mcp__n8n__execute_workflow
Capabilities:
- Trigger workflow execution
- Pass input data to workflows
- Get execution results
- Test workflows programmatically
Example use cases:
- "Run the news fetcher workflow"
- "Execute the content generator with this data"
- "Test the LinkedIn posting workflow"
IMPORTANT REQUIREMENT: MCP access must be enabled for workflows to be executable via MCP.
Enabling MCP Access
To make a workflow executable via MCP, it must meet these requirements:
- Workflow must be published (saved and activated)
- Must have one of these trigger nodes:
- Schedule Trigger
- Webhook Trigger
- Form Trigger
- Chat Trigger
Error if requirements not met:
Error updating MCP settings
MCP access can only be set for published workflows with one of
the following trigger nodes: Schedule Trigger, Webhook Trigger,
Form Trigger, Chat Trigger.
Common issue: Workflows with Manual Trigger or Execute Workflow Trigger cannot have MCP access enabled.
Workaround for testing sub-workflows:
- Sub-workflows (with Execute Workflow Trigger) cannot be executed directly via MCP
- Execute them indirectly by running the parent orchestrator workflow
- Or add a Webhook Trigger temporarily for testing via MCP
What the MCP Server CANNOT Do
❌ Create Workflows
The MCP server cannot create new workflows directly in n8n.
Limitation impact: You cannot ask Claude to "create a new workflow" via MCP.
Workaround:
- Generate workflow JSON file
- Import manually via n8n UI (Settings > Import from File)
- Configure credentials in UI
- Activate workflow
Recommended pattern:
# Generate workflow JSON
claude create-workflow-json > my-workflow.json
# Import manually in n8n UI
# Settings > Import from File > Select my-workflow.json
❌ Modify Workflows
The MCP server cannot edit existing workflows.
Limitation impact: You cannot ask Claude to "update the Wait node" or "add a new HTTP Request node" via MCP.
Workaround:
- Export workflow via n8n UI
- Modify JSON file
- Re-import updated JSON via n8n UI
- Fix any Execute Sub-Workflow nodes if needed
Version control pattern:
# Keep workflow JSONs in version control
/workflows/
├── main-orchestrator.json
├── data-fetcher.json
└── processor.json
# Edit JSON files
# Commit changes
# Re-import into n8n
❌ Delete Workflows
The MCP server cannot remove workflows from n8n.
Workaround: Use n8n UI to delete workflows (Workflow > Settings > Delete)
❌ Update Credentials
The MCP server cannot add or modify API credentials.
Limitation impact: After importing workflows, you must manually configure credentials.
Workaround:
- Import workflow JSON
- n8n shows "Missing credentials" errors on nodes
- Configure credentials in n8n UI (Home > Credentials > Add)
- Assign credentials to nodes
Credential types commonly needed:
- LinkedIn OAuth2
- Anthropic API (Header Auth)
- NewsAPI (Header Auth)
- Custom HTTP Header Auth
❌ Activate/Deactivate Workflows
The MCP server cannot change workflow active status.
Workaround: Use n8n UI toggle to activate/deactivate workflows
❌ Manage Workflow Settings
The MCP server cannot modify:
- Workflow execution order
- Error workflows
- Timezone settings
- Execution timeouts
Workaround: Configure in n8n UI (Workflow > Settings)
Recommended Workflows
Creating New Workflows
Step-by-step process:
Design phase (use MCP)
- Search existing workflows for patterns
- Review similar workflow structures
- Identify nodes needed
Test APIs (use bash/curl)
- Test endpoints before building
- Verify response formats
- Confirm authentication works
Generate JSON
- Create workflow JSON file
- Include all nodes and connections
- Omit Execute Sub-Workflow nodes (add manually later)
Import via UI
- n8n UI > Settings > Import from File
- Select generated JSON file
- Workflow appears in n8n
Configure credentials
- n8n UI > Home > Credentials > Add
- Create required credentials
- Assign to nodes
Fix Execute Sub-Workflow nodes
- Delete old Execute Sub-Workflow nodes
- Add fresh nodes from palette
- Select workflows from dropdown
Test execution (use MCP)
- Use
mcp__n8n__execute_workflow - Verify results
- Debug any issues
- Use
Activate (use UI)
- Toggle workflow to active
- Monitor executions
Modifying Existing Workflows
Step-by-step process:
View current state (use MCP)
- Get workflow details
- Understand current structure
Export workflow
- n8n UI > Workflow > Download
- Save JSON file
Edit JSON
- Modify node configurations
- Add/remove nodes
- Update connections
Re-import
- n8n UI > Settings > Import from File
- Select updated JSON
- Overwrites existing workflow
Fix issues
- Execute Sub-Workflow nodes may need recreation
- Verify credentials still assigned
Test (use MCP)
- Execute workflow
- Verify changes work
Testing Workflows
Using MCP for testing:
// Execute workflow with test data
mcp__n8n__execute_workflow({
workflowId: "123",
data: {
testInput: "sample data"
}
})
Benefits:
- Automated testing
- Repeatable execution
- Programmatic verification
Version Control Best Practices
Since MCP can't create/modify workflows directly, treat workflow JSON files as source of truth.
Project Structure
/project-root/
├── workflows/
│ ├── main-orchestrator.json
│ ├── news-fetcher.json
│ ├── content-generator.json
│ └── linkedin-poster.json
├── README.md
└── .gitignore
Workflow
- Edit JSON files in version control
- Commit changes with descriptive messages
- Import into n8n via UI
- Test via MCP execution
- Iterate as needed
Git Commit Messages
git commit -m "Add Wait node for content approval"
git commit -m "Update LinkedIn posting to use member URN format"
git commit -m "Fix deduplication logic in news fetcher"
MCP Commands Reference
Search Workflows
mcp__n8n__search_workflows({ query: "news" })
Returns: Array of workflows matching search term
Response:
[
{
"id": "123",
"name": "News Aggregator",
"active": true
}
]
Get Workflow Details
mcp__n8n__get_workflow_details({ workflowId: "123" })
Returns: Complete workflow JSON including nodes, connections, settings
Use for:
- Understanding workflow structure
- Finding node configurations
- Inspecting connections
Execute Workflow
mcp__n8n__execute_workflow({
workflowId: "123",
data: { input: "value" }
})
Returns: Execution result with output data
Parameters:
workflowId: ID of workflow to executedata: Input data to pass to workflow (optional)
Common Use Cases
Use MCP When:
✅ Testing workflows programmatically ✅ Viewing workflow structure and configuration ✅ Searching for existing patterns and implementations ✅ Triggering automated workflow executions ✅ Debugging workflow logic by examining node configurations ✅ Monitoring workflow execution results
Use n8n UI When:
🎨 Creating new workflows visually 🎨 Modifying workflows (adding/removing/configuring nodes) 🎨 Managing credentials and authentication 🎨 Activating/deactivating workflows 🎨 Configuring workflow settings 🎨 Fixing Execute Sub-Workflow nodes after import 🎨 Visual workflow design and debugging
Use JSON Files When:
📄 Version controlling workflows 📄 Sharing workflows with team 📄 Batch creating similar workflows 📄 Documenting workflow structure 📄 Creating workflow templates
Troubleshooting
Problem: "I can't create a workflow via MCP"
Solution: This is expected. Generate workflow JSON file and import via n8n UI.
Problem: "Imported workflow has errors"
Common causes:
- Execute Sub-Workflow nodes need recreation
- Credentials not configured
- Node version mismatches
Solution:
- Check for Execute Sub-Workflow errors - delete and recreate these nodes
- Configure missing credentials in n8n UI
- Verify all nodes have required parameters
Problem: "MCP can't modify my workflow"
Solution: This is expected. Export workflow, modify JSON, re-import via UI.
Problem: "Error updating MCP settings" when enabling MCP access
Error message:
Error updating MCP settings
MCP access can only be set for published workflows with one of
the following trigger nodes: Schedule Trigger, Webhook Trigger,
Form Trigger, Chat Trigger.
Cause: Your workflow uses Manual Trigger or Execute Workflow Trigger, which are not compatible with MCP access.
Solutions:
Option 1: Use parent workflow
- If this is a sub-workflow, execute the parent orchestrator instead
- Parent workflow should have a compatible trigger (Schedule, Webhook, Form, or Chat)
Option 2: Add compatible trigger temporarily
- Add a Webhook Trigger to the workflow for testing
- Configure it to receive test data
- Enable MCP access
- Test via MCP
- Remove Webhook Trigger when done
Option 3: Use Manual execution
- Keep Manual Trigger for workflows that don't need MCP access
- Execute manually in n8n UI for testing
Which workflows need MCP access:
- Main orchestrator workflows (should use Schedule or Webhook Trigger)
- Standalone workflows you want to trigger programmatically
Which workflows DON'T need MCP access:
- Sub-workflows (Execute Workflow Trigger) - executed indirectly
- Testing/helper workflows with Manual Trigger
See Also
references/execute-sub-workflow-issues.md- Fixing Execute Sub-Workflow errors after importreferences/workflow-patterns.md- Common workflow structures to implementassets/examples/- Complete workflow JSON examples- n8n Import/Export Documentation
Open this reference as its own page
n8n Node Library Reference
Complete reference for nodes used in n8n v2.0 workflows. Each node includes configuration examples, parameters, use cases, and patterns extracted from production workflows.
Table of Contents
- Trigger Nodes
- Data Processing Nodes
- Flow Control Nodes
- Integration Nodes
- Action Nodes
- Node Versioning
- Node Positioning
Trigger Nodes
Manual Trigger
Type: n8n-nodes-base.manualTrigger (v1)
Starts workflow manually from the n8n UI.
Use cases:
- Testing workflows during development
- On-demand execution
- Debugging workflow logic
Configuration:
{
"parameters": {},
"name": "Manual Trigger",
"type": "n8n-nodes-base.manualTrigger",
"typeVersion": 1,
"position": [240, 400]
}
Parameters: None required
Output: Empty object {}
Common pattern: Use as starting point for workflows during development, then replace with appropriate trigger (Schedule, Webhook, etc.) for production.
Execute Workflow Trigger
Type: n8n-nodes-base.executeWorkflowTrigger (v1)
Receives input from parent workflow when this workflow is called as a sub-workflow.
Use cases:
- Sub-workflows called by orchestrators
- Reusable workflow components
- Modular workflow architecture
Configuration:
{
"parameters": {},
"name": "Execute Workflow Trigger",
"type": "n8n-nodes-base.executeWorkflowTrigger",
"typeVersion": 1,
"position": [240, 300]
}
Parameters: None required
Accessing parent data:
// In Code node after this trigger
$input.all() // Get all items from parent
$input.first().json // Get first item data
Output: Passes through data from parent workflow
Pattern: Sub-workflows that process data and return results to orchestrator.
Data Processing Nodes
Code Node
Type: n8n-nodes-base.code (v2)
Execute JavaScript to transform, filter, or process data.
Use cases:
- Complex data transformation
- Deduplication logic
- Ranking and scoring algorithms
- Custom business logic
- Array manipulation
Configuration:
{
"parameters": {
"jsCode": "// Your JavaScript code\nreturn $input.all();"
},
"name": "Process Data",
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [460, 300]
}
Key parameters:
jsCode: JavaScript code to execute (string)
Available variables:
$input.all() // Array of all input items
$input.first() // First input item
$input.last() // Last input item
$input.item // Current item in iteration
$json // Current item's JSON data
$('Node Name').first().json // Reference another node
$('Node Name').all() // All items from another node
Return format:
Must return array of objects with json property:
return [
{ json: { field: 'value1' } },
{ json: { field: 'value2' } }
];
// Single item
return [{ json: resultObject }];
// Transform all items
return $input.all().map(item => ({
json: {
...item.json,
newField: 'computed value'
}
}));
Example - Deduplication:
const items = $input.all();
const seen = new Set();
const unique = [];
for (const item of items) {
const key = item.json.url.toLowerCase();
if (!seen.has(key)) {
seen.add(key);
unique.push(item);
}
}
return unique;
Example - Data extraction:
// Extract specific fields
const items = $input.all();
return items.map(item => ({
json: {
title: item.json.title,
url: item.json.url,
score: item.json.score || 0
}
}));
See also: code-snippets/ for reusable patterns
Set Node
Type: n8n-nodes-base.set (v3.3)
Create or modify fields in data items. Primary tool for data normalization.
Use cases:
- Normalizing data from different sources to common schema
- Adding computed fields
- Renaming fields
- Setting constant values
- Type conversion
Configuration:
{
"parameters": {
"assignments": {
"assignments": [
{
"id": "title",
"name": "title",
"value": "={{ $json.headline }}",
"type": "string"
},
{
"id": "score",
"name": "score",
"value": "={{ $json.points }}",
"type": "number"
},
{
"id": "source",
"name": "source",
"value": "Hacker News",
"type": "string"
}
]
},
"options": {}
},
"name": "Normalize Data",
"type": "n8n-nodes-base.set",
"typeVersion": 3.3,
"position": [680, 300]
}
Key parameters:
assignments.assignments: Array of field mappingsid: Internal identifiername: Output field namevalue: Expression or literal valuetype: Data type (string, number, boolean, object, array)
Expression patterns:
// Static value
"value": "Hacker News"
// Map from existing field
"value": "={{ $json.title }}"
// With fallback
"value": "={{ $json.url || 'https://example.com' }}"
// Computed
"value": "={{ $json.score * 2 }}"
// Type conversion
"value": "={{ new Date($json.time * 1000).toISOString() }}"
Common pattern - Data normalization:
When aggregating from multiple sources, normalize each source to common schema:
HN API → Set Node (normalize to common schema)
NewsAPI → Set Node (normalize to common schema)
RSS Feed → Set Node (normalize to common schema)
↓
Merge Node
Common schema example:
{
"title": "string",
"url": "string",
"source": "string",
"score": "number",
"comments": "number",
"timestamp": "ISO date string",
"summary": "string"
}
Merge Node
Type: n8n-nodes-base.merge (v2.1)
Combine data from multiple inputs into single output.
Use cases:
- Aggregating data from multiple sources
- Combining parallel processing branches
- Joining related data
Modes:
append: Combine all items into one list (most common)combine: Pair items from input 1 and 2choose: Pick one input or the othermultiplex: Create cartesian product
Configuration (append mode):
{
"parameters": {
"mode": "append"
},
"name": "Merge All Sources",
"type": "n8n-nodes-base.merge",
"typeVersion": 2.1,
"position": [1560, 400]
}
Connection pattern:
Multiple nodes connect to Merge as inputs:
Source 1 ──┐
Source 2 ──┼─→ Merge Node → Combined Output
Source 3 ──┘
Input indices (0, 1, 2...) increment automatically for each connection.
Common pattern - Multi-source aggregation:
HTTP Request (HN) ──┐
HTTP Request (API) ──┼─→ Merge (append) → Deduplicate → Process
RSS Feed Read ───────┘
Filter Node
Type: n8n-nodes-base.filter (v2)
Keep only items that match specified conditions.
Use cases:
- Filtering by field values
- Removing invalid/incomplete data
- Keyword matching
- Quality control
- Threshold filtering
Configuration:
{
"parameters": {
"conditions": {
"string": [
{
"value1": "={{ $json.title }}",
"operation": "regex",
"value2": "(?i)(AI|machine learning|automation)"
}
],
"number": [
{
"value1": "={{ $json.score }}",
"operation": "larger",
"value2": 20
}
]
}
},
"name": "Filter Stories",
"type": "n8n-nodes-base.filter",
"typeVersion": 2,
"position": [1120, 240]
}
Condition types:
String operations:
contains: Substring matchequals: Exact matchnotEquals: Not equalregex: Regular expressionstartsWith: Begins withendsWith: Ends with
Number operations:
equals,notEqualslarger,largerEqualsmaller,smallerEqual
Boolean operations:
equals,notEquals
DateTime operations:
after,before,between
Regex example:
// Case-insensitive keyword matching
"value2": "(?i)(AI|ML|automation|n8n)"
// URL pattern
"value2": "^https://.*\\.com$"
Multiple conditions: All conditions must match (AND logic). For OR logic, use multiple Filter nodes in parallel or use Code node.
Split in Batches Node
Type: n8n-nodes-base.splitInBatches (v3)
Process large arrays in smaller chunks, creating a loop.
Use cases:
- API rate limiting (process N items at a time)
- Memory management for large datasets
- Batch API requests
- Progressive processing
Configuration:
{
"parameters": {
"batchSize": 30,
"options": {}
},
"name": "Batch Process Items",
"type": "n8n-nodes-base.splitInBatches",
"typeVersion": 3,
"position": [680, 240]
}
Key parameters:
batchSize: Number of items per batch (e.g., 10, 30, 50)
How it works:
- Splits input array into batches
- Processes first batch
- Loop continues for next batch
- When all batches complete, workflow proceeds
Loop structure:
Split in Batches → Process Batch → HTTP Request ─┐
↑ │
└──────────────────────────────────────────┘
Downstream nodes must connect back to Split in Batches for loop continuation.
Common pattern - Rate-limited API calls:
Get IDs (100 items) → Split in Batches (10) → HTTP Request → Process
Processes 10 items at a time instead of overwhelming API with 100 requests.
Flow Control Nodes
IF Node
Type: n8n-nodes-base.if (v2)
Branch workflow based on conditions.
Use cases:
- Approval/rejection flows
- Conditional processing
- Error handling
- Data routing
- Status checking
Configuration:
{
"parameters": {
"conditions": {
"string": [
{
"value1": "={{ $json['Action'] }}",
"operation": "equals",
"value2": "Approve"
}
]
}
},
"name": "Check Approval",
"type": "n8n-nodes-base.if",
"typeVersion": 2,
"position": [1560, 400]
}
Outputs:
- Output 0 (true branch): Condition matched
- Output 1 (false branch): Condition not matched
Connection structure:
"connections": {
"IF Node": {
"main": [
[{ "node": "Approved Action", "type": "main", "index": 0 }],
[{ "node": "Rejected Action", "type": "main", "index": 0 }]
]
}
}
Accessing Wait node form data:
// Check dropdown selection
"value1": "={{ $json['Approval Status'] }}"
// Check text input
"value1": "={{ $json['Comments'] }}"
Multiple conditions: Supports string, number, boolean, dateTime conditions. All must match (AND logic).
Common pattern - Human approval:
Wait Node (form) → IF Node → True: Post to API
→ False: Send notification
Wait Node
Type: n8n-nodes-base.wait (v1.1)
Pause workflow execution until resume condition is met.
Use cases:
- Human approval workflows
- Form submissions
- Manual review gates
- Scheduled delays
- Webhook callbacks
Resume modes:
form: Human fills out form (most common)webhook: External system sends webhookafter: Time-based delay
Configuration (form mode):
{
"parameters": {
"resume": "form",
"form": {
"formTitle": "Review Content",
"formDescription": "Please review and approve:",
"formFields": {
"values": [
{
"fieldLabel": "Action",
"fieldType": "dropdown",
"fieldOptions": {
"values": [
{"option": "Approve"},
{"option": "Reject"}
]
},
"requiredField": true
}
]
}
}
},
"name": "Wait for Approval",
"type": "n8n-nodes-base.wait",
"typeVersion": 1.1,
"position": [900, 400]
}
Field types:
dropdown: Select from optionstext: Single-line text inputtextarea: Multi-line text inputnumber: Numeric inputdate: Date picker
Accessing form data:
After Wait node resumes, access submitted values in next node:
// In expression
{{ $json['Action'] }}
{{ $json['Comments'] }}
// In Code node
const action = $json['Action'];
const comments = $json['Comments'];
IMPORTANT: Wait node actually pauses execution. Do NOT use:
- respondToWebhook (doesn't pause)
- Set nodes with manual notes (doesn't pause)
- IF nodes checking fields that were never set (doesn't pause)
See: references/wait-nodes-guide.md for complete documentation
Integration Nodes
HTTP Request Node
Type: n8n-nodes-base.httpRequest (v4.2)
Make HTTP API calls to any REST endpoint.
Use cases:
- Fetching data from APIs
- Posting data to external systems
- Webhook calls
- Any HTTP-based integration
Configuration (GET request):
{
"parameters": {
"url": "https://api.example.com/data",
"authentication": "predefinedCredentialType",
"nodeCredentialType": "httpHeaderAuth",
"options": {}
},
"name": "Fetch Data",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [460, 400]
}
Configuration (POST with JSON body):
{
"parameters": {
"method": "POST",
"url": "https://api.anthropic.com/v1/messages",
"authentication": "predefinedCredentialType",
"nodeCredentialType": "anthropicApi",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "anthropic-version",
"value": "2023-06-01"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={{ JSON.stringify($json.requestData) }}",
"options": {}
},
"name": "Call Anthropic API",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [680, 300]
}
Key parameters:
method: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONSurl: Can use expressions for dynamic URLsauthentication: none, predefinedCredentialType, genericCredentialTypenodeCredentialType: Type of credential (httpHeaderAuth, oAuth2Api, etc.)sendHeaders: true to add custom headersheaderParameters: Array of header name/value pairssendBody: true for POST/PUT/PATCHspecifyBody: json, form, rawjsonBody: JSON body as string or expression
Dynamic URL:
"url": "=https://api.example.com/item/{{ $json.id }}.json"
Authentication types:
- Header Auth: API keys in headers
- OAuth2: For LinkedIn, Google, etc.
- Basic Auth: Username/password
- None: For public APIs
Response access:
{{ $json.responseField }} // API response data
{{ $statusCode }} // HTTP status code (200, 201, etc.)
Common pattern - Check status:
HTTP Request → IF Node (check $statusCode === 201) → Success/Failure branches
See: references/api-credentials.md for credential setup
RSS Feed Read Node
Type: n8n-nodes-base.rssFeedRead (v1)
Fetch and parse RSS/Atom feeds.
Use cases:
- Blog aggregation
- News monitoring
- Content curation
- Feed-based workflows
Configuration:
{
"parameters": {
"url": "https://blog.n8n.io/rss/",
"options": {}
},
"name": "Read Blog Feed",
"type": "n8n-nodes-base.rssFeedRead",
"typeVersion": 1,
"position": [460, 560]
}
Key parameters:
url: RSS feed URL
Output fields:
title: Article titlelink: Article URLpubDate: Publication datecontentSnippet: Text excerptcontent: Full content (HTML)creator: Author namecategories: Article categories/tags
Common pattern - Normalize after read:
RSS Feed Read → Set Node (normalize to common schema) → Merge with other sources
Example normalization:
{
"name": "title",
"value": "={{ $json.title }}",
"type": "string"
},
{
"name": "url",
"value": "={{ $json.link }}",
"type": "string"
},
{
"name": "timestamp",
"value": "={{ $json.pubDate }}",
"type": "string"
},
{
"name": "source",
"value": "Blog RSS",
"type": "string"
}
Action Nodes
Execute Workflow Node
Type: n8n-nodes-base.executeWorkflow (v1)
UI Label: "Execute Sub-Workflow" (in node palette)
Important: In n8n v2.0+, this node is labeled "Execute Sub-Workflow" in the UI, but the node type in JSON remains n8n-nodes-base.executeWorkflow. This is normal and correct.
Call another workflow as a sub-workflow.
Use cases:
- Orchestrator patterns
- Workflow reuse
- Modular workflow architecture
- Breaking complex workflows into manageable pieces
Configuration:
{
"parameters": {
"workflowId": "={{ $parameter.workflowId }}",
"options": {}
},
"name": "Execute Sub-Workflow",
"type": "n8n-nodes-base.executeWorkflow",
"typeVersion": 1,
"position": [680, 400]
}
Source selection:
database: Select workflow from dropdown (recommended for production)localFile: Use workflow fileparameter: Dynamic workflow ID via expression
Import Issue: When importing workflow JSON, Execute Workflow nodes sometimes show "out of date" error after import.
When this happens:
- The node appears with a red error indicator after importing
- Error message: "This node is out of date. Please upgrade by removing it and adding a new one"
- This does NOT mean the JSON is wrong - the node type
executeWorkflowis correct
Workaround if you see the error:
- Import workflow JSON
- Delete Execute Workflow nodes showing errors (not all of them, only ones with errors)
- Add fresh "Execute Sub-Workflow" nodes from palette (same type, just recreated)
- Select "Database" as source
- Choose target workflow from dropdown
Best practice:
- Include Execute Workflow nodes normally in your JSON - they usually import fine
- If you frequently have import issues, consider omitting these nodes and adding manually
Data flow:
Orchestrator: Execute Workflow Node (passes data)
↓
Sub-workflow: Execute Workflow Trigger (receives data)
↓
Process data
↓
Return result (last node output)
↓
Orchestrator: Receives result from Execute Workflow Node
See: references/execute-sub-workflow-issues.md for detailed troubleshooting
Respond to Webhook Node
Type: n8n-nodes-base.respondToWebhook (v1)
Send HTTP response back to webhook caller.
Use cases:
- Webhook-based workflows
- API endpoints
- Synchronous responses to HTTP requests
Configuration:
{
"parameters": {
"respondWith": "json",
"responseBody": "={{ $json }}",
"options": {}
},
"name": "Respond to Webhook",
"type": "n8n-nodes-base.respondToWebhook",
"typeVersion": 1,
"position": [900, 400]
}
Key parameters:
respondWith: json, text, htmlresponseBody: Data to returnresponseCode: HTTP status code (default 200)
IMPORTANT: This node does NOT pause workflow execution. It returns a response immediately while the workflow continues.
For human input, use Wait nodes instead.
Anti-pattern:
❌ Webhook Trigger → Respond to Webhook (asking for input)
This returns immediately - user never gets to provide input.
Correct pattern:
✅ Webhook Trigger → Wait Node (form) → Process → Respond to Webhook
Node Versioning
Nodes have typeVersion indicating schema version:
Common versions:
- manualTrigger: v1
- executeWorkflowTrigger: v1
- httpRequest: v4.2
- code: v2
- set: v3.3
- merge: v2.1
- filter: v2
- if: v2
- wait: v1.1
- splitInBatches: v3
- rssFeedRead: v1
- executeWorkflow: v1
Version compatibility:
When importing workflows, n8n usually auto-upgrades node versions. Exception: Execute Workflow nodes often require manual recreation.
Check version: Look at typeVersion in node configuration.
Node Positioning
Nodes are positioned on 2D canvas using [x, y] coordinates (pixels).
Conventions:
- Horizontal flow: Increase x by ~220 per node
- Parallel branches: Vary y coordinate
- Grid alignment: Use multiples of 20
Example positions:
Trigger: [240, 400]
Process: [460, 400]
Decision (IF): [680, 400]
├─ True: [900, 300]
└─ False: [900, 500]
Continue: [1120, 400]
Visual layout:
Start → Process → Decision ┬→ Branch A → Merge
└→ Branch B ──┘
Positioning doesn't affect execution - it's purely for visual organization.
See Also
references/expression-syntax.md- Using expressions in node parametersreferences/workflow-patterns.md- How nodes connect in common patternscode-snippets/- Reusable Code node implementationsassets/examples/- Complete workflow examplesreferences/wait-nodes-guide.md- Detailed Wait node documentationreferences/execute-sub-workflow-issues.md- Troubleshooting Execute Workflowreferences/api-credentials.md- Setting up authentication
Open this reference as its own page
n8n Troubleshooting Guide
Common issues and solutions when working with n8n v2.0 workflows.
Table of Contents
- Execute Sub-Workflow Issues
- Authentication Issues
- Data Issues
- Expression Issues
- Workflow Execution Issues
- Data Quality Issues
- API Integration Issues
- Performance Issues
- Import/Export Issues
- Debug Checklist
Execute Sub-Workflow Issues
See execute-sub-workflow-issues.md for dedicated documentation.
Quick summary:
- Problem: "Node out of date" error after import
- Solution: Delete old Execute Sub-Workflow nodes, add fresh ones from palette
Authentication Issues
LinkedIn unauthorized_scope_error
Symptoms:
- OAuth flow completes successfully
- API calls return 401 or 403 errors
- Error message: "Insufficient permissions" or "unauthorized_scope_error"
Root cause: Organization Support or Legacy toggles are enabled in credentials
Solution:
- Open n8n UI > Home > Credentials
- Find LinkedIn OAuth2 credential
- Edit credential
- Turn OFF both toggles: ❌ Organization Support, ❌ Legacy
- Save and test
API Key Authentication Failing
Symptoms:
- 401 Unauthorized or 403 Forbidden errors
- "Invalid API key" messages
Checklist:
- Header name is exact match (case-sensitive):
X-Api-Keynotx-api-key - Credential type matches node's
nodeCredentialType - API key not expired
- Not hitting rate limits
Data Issues
Field is Undefined
Common causes:
- Typo in field name:
$json.titelvs$json.title - Wrong node referenced
- Field doesn't exist in some items
Solutions:
// Use optional chaining
{{ $json.field?.nestedField ?? 'default' }}
// Fallback chain
{{ $json.field || 'default' }}
Data Lost Between Nodes
Common causes:
- Filter node removed all items
- Code node not returning correct format
- Connection missing
Solution - Correct Code node return:
// Correct
return [{ json: { data } }];
return items.map(item => ({ json: item }));
// Wrong
return { data };
return data;
Merge Node Not Combining Data
Checklist:
- Mode is
appendfor combining lists - All inputs connected
- Upstream nodes executed successfully
Expression Issues
Expression Not Evaluating
Solutions:
- Check syntax:
={{ expression }}not{{ expression }} - Enable expression mode in node parameter (toggle)
- Escape literal braces if needed
Cross-Node Reference Returns Empty
Solutions:
- Node name exact match (case-sensitive)
- Node has executed
- Correct syntax:
$('Node Name').first().json.field
Workflow Execution Issues
Wait Node Not Pausing
Solution: Use Wait node with resume: "form", NOT respondToWebhook or Set nodes.
See wait-nodes-guide.md for details.
Split in Batches Infinite Loop
Solution: Ensure downstream nodes connect back to Split in Batches for loop continuation.
Data Quality Issues
Duplicate Items
Solution: Use Code node for deduplication:
const items = $input.all();
const seen = new Set();
const unique = [];
for (const item of items) {
const key = item.json.url.toLowerCase().replace(/\/$/, '');
if (!seen.has(key)) {
seen.add(key);
unique.push(item);
}
}
return unique;
See code-snippets/deduplication.js
Date/Time Format Mismatch
Solution: Normalize to ISO format:
// Set node
"value": "={{ new Date($json.pubDate).toISOString() }}"
// Unix timestamp (seconds)
"value": "={{ new Date($json.time * 1000).toISOString() }}"
API Integration Issues
Rate Limit Errors
Solutions:
- Use Split in Batches to reduce request frequency
- Add delays between requests
- Cache responses
LinkedIn Member ID Format Error
Solution: Use URN format:
// urn:li:person:{id}
={{ `urn:li:person:${$json.sub}` }}
Performance Issues
Workflow Timeout
Solutions:
- Filter data earlier in workflow
- Use Split in Batches
- Optimize Code nodes (avoid nested loops)
Memory Issues
Solutions:
- Process in batches
- Limit array sizes
- Keep only essential fields
Import/Export Issues
Imported Workflow Shows Errors
Solutions:
- Execute Sub-Workflow nodes: delete and recreate
- Reconfigure credentials
- Verify all connections
Debug Checklist
- Execute nodes individually and check output
- Trace data flow through workflow
- Verify expressions in isolation
- Inspect connections visually
- Review credentials configuration
- Check n8n logs
- Test APIs externally (curl/Postman)
See Also
references/execute-sub-workflow-issues.mdreferences/wait-nodes-guide.mdreferences/api-credentials.mdreferences/expression-syntax.mdreferences/node-library.md
Open this reference as its own page
Wait Nodes for Human-in-the-Loop Workflows
The Right Way: Wait Nodes
For workflows that need human approval or input, use Wait nodes with "Resume: On Form Submitted".
Key Features
- Actually pauses execution until the form is submitted
- Form fields: dropdowns, text inputs, number inputs, etc.
- Data access: Submitted values available in next node via
$json['Field Name']
Configuration Structure
{
"type": "n8n-nodes-base.wait",
"parameters": {
"resume": "form",
"form": {
"formTitle": "Title shown to user",
"formDescription": "Instructions (supports markdown)",
"formFields": {
"values": [
{
"fieldLabel": "Field Name",
"fieldType": "dropdown",
"fieldOptions": {
"values": [
{"option": "Option 1"},
{"option": "Option 2"}
]
},
"requiredField": true
}
]
}
}
}
}
Field Types
dropdown- Select one option from a listtext- Single-line text inputtextarea- Multi-line text inputnumber- Numeric inputdate- Date picker
Accessing Form Data
After the Wait node resumes, access submitted values in the next node:
// In a Code node or expression
$json['Field Name'] // Gets the submitted value
// Example: Check approval status
if ($json['Approval Status'] === 'Approved') {
// Continue with approved workflow
}
Wrong Approaches (Don't Use)
These patterns do NOT pause execution:
❌ respondToWebhook nodes - These return a response but don't pause the workflow ❌ Set nodes with manual notes - Notes like "MANUAL STEP: Edit this node" don't stop execution ❌ IF nodes checking fields that were never set - The workflow continues immediately with empty/null values
Common Use Cases
Content Approval
{
"formTitle": "Review Generated Content",
"formDescription": "## Generated LinkedIn Post\n\n{{ $json.generated_post }}\n\n**Approve or request edits:**",
"formFields": {
"values": [
{
"fieldLabel": "Action",
"fieldType": "dropdown",
"fieldOptions": {
"values": [
{"option": "Approve and Post"},
{"option": "Edit Content"},
{"option": "Reject"}
]
},
"requiredField": true
},
{
"fieldLabel": "Edited Content",
"fieldType": "textarea",
"requiredField": false
}
]
}
}
Data Validation
{
"formTitle": "Verify Extracted Data",
"formDescription": "Please verify the extracted information is correct:",
"formFields": {
"values": [
{
"fieldLabel": "Name",
"fieldType": "text",
"requiredField": true
},
{
"fieldLabel": "Email",
"fieldType": "text",
"requiredField": true
},
{
"fieldLabel": "Confirmed",
"fieldType": "dropdown",
"fieldOptions": {
"values": [
{"option": "Yes"},
{"option": "No, needs correction"}
]
},
"requiredField": true
}
]
}
}
All Field Types with Examples
Dropdown
{
"fieldLabel": "Priority",
"fieldType": "dropdown",
"fieldOptions": {
"values": [
{"option": "High"},
{"option": "Medium"},
{"option": "Low"}
]
},
"requiredField": true
}
Text (single-line)
{
"fieldLabel": "Title",
"fieldType": "text",
"requiredField": true
}
Textarea (multi-line)
{
"fieldLabel": "Comments",
"fieldType": "textarea",
"requiredField": false
}
Number
{
"fieldLabel": "Quantity",
"fieldType": "number",
"requiredField": true
}
Date
{
"fieldLabel": "Publish Date",
"fieldType": "date",
"requiredField": true
}
Note: Date field returns ISO 8601 format string (e.g., 2024-01-15T00:00:00.000Z)
Accessing Form Data in Subsequent Nodes
After Wait node resumes, submitted data is available in $json.
In IF Node
Check submitted values to branch workflow:
{
"conditions": {
"string": [
{
"value1": "={{ $json['Action'] }}",
"operation": "equals",
"value2": "Approve"
}
]
}
}
In Code Node
Process form submission:
// Access form data
const action = $json['Action'];
const comments = $json['Comments'];
const editedContent = $json['Edited Content'];
// Example: Use edited content if provided, otherwise use original
const finalContent = editedContent || $json.originalContent;
return [{
json: {
action,
content: finalContent,
comments,
approvedAt: new Date().toISOString()
}
}];
In Set Node
Transform form data:
{
"assignments": {
"assignments": [
{
"name": "approved",
"value": "={{ $json['Action'] === 'Approve' }}",
"type": "boolean"
},
{
"name": "userComments",
"value": "={{ $json['Comments'] }}",
"type": "string"
}
]
}
}
Retrieving Stored Data After Wait
Common pattern: Store data before Wait node, retrieve after:
Before Wait node (Code node):
const stories = $input.all().slice(0, 5);
return [{
json: {
stories: stories.map(s => s.json),
formattedList: stories.map((s, i) => `${i+1}. ${s.json.title}`).join('\n')
}
}];
Wait node:
{
"formDescription": "={{ $json.formattedList }}",
"formFields": {
"values": [
{
"fieldLabel": "Select Story",
"fieldType": "dropdown",
"fieldOptions": {
"values": [
{"option": "Story 1"},
{"option": "Story 2"},
{"option": "Story 3"}
]
},
"requiredField": true
}
]
}
}
After Wait node (Code node):
// Retrieve stored data from before Wait node
const storedData = $('Prepare Data').first().json;
const selectedIndex = parseInt($json['Select Story'].replace('Story ', '')) - 1;
const selectedStory = storedData.stories[selectedIndex];
return [{
json: selectedStory
}];
Form Description Markdown Formatting
The formDescription field supports markdown for rich formatting.
Basic Formatting
{
"formDescription": "## Heading\n\n**Bold text**\n\n*Italic text*\n\n- List item 1\n- List item 2"
}
Renders as:
## Heading
**Bold text**
*Italic text*
- List item 1
- List item 2
Dynamic Content
Include data from previous nodes:
{
"formDescription": "## Review Story\n\n**Title:** {{ $json.title }}\n\n**URL:** {{ $json.url }}\n\n**Score:** {{ $json.score }}\n\n**Summary:**\n{{ $json.summary }}"
}
Complex Layouts
{
"formDescription": "## Approval Required\n\n### Generated Content\n\n{{ $json.generatedPost }}\n\n---\n\n### Metadata\n\n| Field | Value |\n|-------|-------|\n| Source | {{ $json.source }} |\n| Score | {{ $json.score }} |\n| Date | {{ $json.publishedAt }} |\n\n---\n\n**Please approve or reject:**"
}
Using Expressions for Full Control
Pass pre-formatted markdown from Code node:
Code node before Wait:
const items = $input.all();
const formattedDescription = `
## Select a Story to Share
${items.map((item, i) => `
### ${i+1}. ${item.json.title}
**Source:** ${item.json.source}
**Score:** ${item.json.score} points
**URL:** ${item.json.url}
${item.json.summary}
---
`).join('\n')}
`;
return [{
json: {
description: formattedDescription,
items: items.map(i => i.json)
}
}];
Wait node:
{
"formDescription": "={{ $json.description }}"
}
Field Validation
n8n provides basic validation through requiredField property.
Required vs Optional
{
"formFields": {
"values": [
{
"fieldLabel": "Email",
"fieldType": "text",
"requiredField": true // User must fill this
},
{
"fieldLabel": "Comments",
"fieldType": "textarea",
"requiredField": false // Optional field
}
]
}
}
Custom Validation
For advanced validation, use IF node or Code node after Wait:
// In Code node after Wait
const email = $json['Email'];
const isValidEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
if (!isValidEmail) {
throw new Error('Invalid email format');
}
return $input.all();
Complete Workflow Example
For a full production example with Wait nodes, see:
assets/examples/news-aggregation-workflow.json - Includes human review step with Wait node
Documentation
See Also
references/node-library.md- Complete Wait node documentationreferences/workflow-patterns.md- Human-in-the-loop patterncode-snippets/form-data-preparation.js- Form data formatting helpers
Open this reference as its own page
n8n Workflow Patterns
Orchestrator Pattern
Use a main orchestrator workflow to coordinate multiple sub-workflows.
Benefits
- Separation of concerns
- Reusable sub-workflows
- Easier testing and debugging
- Clear workflow organization
Structure
Main Orchestrator
├── Trigger (Schedule, Webhook, Manual)
├── Execute Sub-Workflow: Data Fetcher
├── Wait Node: Human Review
├── Execute Sub-Workflow: Data Processor
└── Execute Sub-Workflow: Output Handler
Example: Content Generation Pipeline
Main Orchestrator
├── Schedule Trigger (daily at 9am)
├── Execute Sub-Workflow: News Fetcher
├── Wait Node: Review News Items
├── Execute Sub-Workflow: Content Generator
├── Wait Node: Approve Content
└── Execute Sub-Workflow: Social Media Poster
Sub-Workflow Pattern
Create focused, single-purpose workflows that can be reused.
Guidelines
- Each sub-workflow should do one thing well
- Accept inputs via workflow execution
- Return outputs for the parent workflow
- Handle errors gracefully with error workflows
Input/Output
Sub-workflows receive data from parent workflows:
// In sub-workflow, access parent data
$input.all()
Return data to parent:
// Last node output is returned to parent
return [{
json: {
result: "processed data",
status: "success"
}
}];
Human-in-the-Loop Pattern
Use Wait nodes to pause workflows for human input.
See wait-nodes-guide.md for detailed Wait node configuration.
Basic Flow
Trigger
├── Fetch/Generate Data
├── Wait Node: Review & Approve
├── IF Node: Check Approval
│ ├── Approved → Continue
│ └── Rejected → End or Loop
└── Execute Action
Data Aggregation Pattern
Combine data from multiple sources and deduplicate.
Example Structure
Trigger
├── HTTP Request: Source 1
├── HTTP Request: Source 2
├── HTTP Request: Source 3
├── Merge Node (combine all)
├── Code Node: Deduplicate
└── Code Node: Rank/Score
Deduplication Logic
// Deduplicate by URL
const seen = new Set();
const unique = [];
for (const item of items) {
const normalizedUrl = item.url.toLowerCase().replace(/\/$/, '');
if (!seen.has(normalizedUrl)) {
seen.add(normalizedUrl);
unique.push(item);
}
}
return unique.map(item => ({ json: item }));
Error Handling Pattern
Handle errors gracefully in workflows.
Error Workflow
Create a dedicated error workflow:
Error Trigger
├── Code Node: Format Error Message
├── Send Notification (Email, Slack, etc.)
└── Log to Database
Link error workflow in node settings:
- Settings → Error Workflow → Select your error workflow
Testing Pattern
Test APIs and data sources before building full workflows.
Recommended Approach
Test via Bash/curl first
curl -X GET "https://api.example.com/endpoint" \ -H "Authorization: Bearer $TOKEN"Verify response format
- Check field names
- Understand data structure
- Test authentication
Then create workflow JSON
- Now you know exactly what fields to use
- Avoid import → test → fail → fix cycles
News Aggregation Pattern
Fetch data from multiple sources, normalize to common schema, merge, and deduplicate.
Complete Flow
Trigger
├── HTTP Request: Hacker News API
│ └── Set: Normalize to common schema
├── HTTP Request: NewsAPI
│ └── Set: Normalize to common schema
├── RSS Feed Read: Blog
│ └── Set: Normalize to common schema
└── Merge (append mode)
├── Code: Deduplicate by URL
├── Code: Rank/Score items
└── Filter: Top N items
Key Steps
1. Fetch from multiple sources in parallel
All HTTP Request and RSS nodes execute simultaneously for faster aggregation.
2. Normalize each source to common schema
Each source outputs different field names. Use Set node immediately after each source:
// Common schema
{
"title": "string",
"url": "string",
"source": "string",
"score": "number",
"comments": "number",
"timestamp": "ISO date string",
"summary": "string"
}
3. Merge all normalized data
Merge node combines all sources into single array.
4. Deduplicate
Use Code node to remove duplicates by normalized URL.
5. Rank/Score
Calculate relevance score based on keywords, recency, and engagement.
See: assets/examples/news-aggregation-workflow.json for complete implementation
Content Generation with AI Pattern
Generate content using AI API (Anthropic, OpenAI, etc.) within workflow.
Structure
Execute Workflow Trigger (receives input data)
├── Code: Build prompt from input
├── HTTP Request: Call AI API
├── Code: Extract and format response
└── Return result to parent
Implementation Details
1. Build prompt dynamically
// In Code node
const input = $input.first().json;
const prompt = `Create a LinkedIn post about: ${input.title}
URL: ${input.url}
Summary: ${input.summary}
Requirements:
- Professional tone
- 2-3 paragraphs
- Include relevant hashtags`;
return [{
json: {
prompt,
title: input.title
}
}];
2. Call AI API
{
"method": "POST",
"url": "https://api.anthropic.com/v1/messages",
"authentication": "predefinedCredentialType",
"nodeCredentialType": "anthropicApi",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "anthropic-version",
"value": "2023-06-01"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={{ JSON.stringify({\n model: 'claude-3-5-sonnet-20241022',\n max_tokens: 400,\n temperature: 0.7,\n messages: [{\n role: 'user',\n content: $json.prompt\n }]\n}) }}"
}
3. Extract response
// In Code node
const response = $input.first().json;
const generatedText = response.content[0].text;
return [{
json: {
generatedContent: generatedText,
model: response.model,
usage: response.usage
}
}];
See: assets/examples/content-generation-workflow.json
Scoring and Ranking Pattern
Calculate relevance scores and rank items.
Multi-Factor Ranking
Combine multiple factors with weighted scores:
// In Code node
const items = $input.all().map(item => item.json);
// Configuration
const config = {
highValueKeywords: ['ai', 'automation', 'n8n'],
mediumValueKeywords: ['technology', 'workflow', 'integration'],
weights: {
relevance: 0.5,
recency: 0.3,
engagement: 0.2
}
};
// Score each item
const scoredItems = items.map(item => {
let relevanceScore = 0;
let recencyScore = 0;
let engagementScore = 0;
// Relevance scoring (keyword matching)
const text = (item.title + ' ' + item.summary).toLowerCase();
config.highValueKeywords.forEach(keyword => {
if (text.includes(keyword)) relevanceScore += 3;
});
config.mediumValueKeywords.forEach(keyword => {
if (text.includes(keyword)) relevanceScore += 1;
});
// Recency scoring (time-based)
const ageHours = (Date.now() - new Date(item.timestamp).getTime()) / (1000 * 60 * 60);
if (ageHours < 6) recencyScore = 3;
else if (ageHours < 24) recencyScore = 2;
else if (ageHours < 48) recencyScore = 1;
// Engagement scoring
const score = item.score || 0;
if (score > 100) engagementScore = 3;
else if (score > 50) engagementScore = 2;
else if (score > 20) engagementScore = 1;
// Calculate weighted final score
const finalScore =
(relevanceScore * config.weights.relevance) +
(recencyScore * config.weights.recency) +
(engagementScore * config.weights.engagement);
return {
...item,
finalScore,
relevanceScore,
recencyScore,
engagementScore
};
});
// Sort by score (descending)
const ranked = scoredItems.sort((a, b) => b.finalScore - a.finalScore);
return ranked.map(item => ({ json: item }));
See: code-snippets/ranking-algorithms.js for reusable implementation
Connection Patterns
How nodes connect in workflows.
Sequential Pattern
Linear flow, one node after another:
Node A → Node B → Node C → Node D
JSON structure:
{
"connections": {
"Node A": {
"main": [[{"node": "Node B", "type": "main", "index": 0}]]
},
"Node B": {
"main": [[{"node": "Node C", "type": "main", "index": 0}]]
}
}
}
Parallel Pattern
Multiple nodes execute simultaneously:
┌→ Node B
Trigger ───┼→ Node C → Merge
└→ Node D
JSON structure:
{
"connections": {
"Trigger": {
"main": [[
{"node": "Node B", "type": "main", "index": 0},
{"node": "Node C", "type": "main", "index": 0},
{"node": "Node D", "type": "main", "index": 0}
]]
},
"Node B": {
"main": [[{"node": "Merge", "type": "main", "index": 0}]]
},
"Node C": {
"main": [[{"node": "Merge", "type": "main", "index": 1}]]
},
"Node D": {
"main": [[{"node": "Merge", "type": "main", "index": 2}]]
}
}
}
Benefits:
- Faster execution (simultaneous)
- Independent operations
- Merge combines results
Conditional Branching Pattern
IF node creates true/false paths:
┌→ True Path → Action A
IF Node ───────┤
└→ False Path → Action B
JSON structure:
{
"connections": {
"IF Node": {
"main": [
[{"node": "Action A", "type": "main", "index": 0}], // True (index 0)
[{"node": "Action B", "type": "main", "index": 0}] // False (index 1)
]
}
}
}
Loop Pattern
Split in Batches creates loop:
Split in Batches → Process Item → HTTP Request ─┐
↑ │
└─────────────────────────────────────────┘
↓ (after all batches)
Continue Workflow
Use case: Process large arrays in smaller chunks
Complete Workflow Examples
Comprehensive, production-ready workflow JSONs:
assets/examples/news-aggregation-workflow.json- Multi-source aggregation with deduplicationassets/examples/content-generation-workflow.json- AI content generation sub-workflowassets/examples/multi-source-deduplication-workflow.json- Focused deduplication exampleassets/examples/linkedin-member-id-workflow.json- LinkedIn member ID retrieval
Documentation References
See Also
code-snippets/deduplication.js- Reusable deduplication codecode-snippets/ranking-algorithms.js- Scoring and ranking implementationscode-snippets/data-normalization.js- Common normalization patternsreferences/node-library.md- Individual node documentationreferences/expression-syntax.md- Expression patterns used in workflows
More in this playbook
Safe to turn on
Use this skill when an agent or person is about to create, change or enable an automation inside someone else's account or a shared environment: "create this workflow", "build it in the customer's account", "turn it on", "go live", "deploy this automation". Produces a proposal the human approves, an automation created in the off state, and a short list of what only the human can finish.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.

