Automation
February 5, 2024
12 min read
6 views

Building Automation Workflows with n8n: A Complete Guide

A complete developer guide to n8n — from core concepts and self-hosting to building multi-step workflows with HTTP requests, webhooks, conditional branching, error handling, sub-workflows, and AI agent nodes.

n8n Workflow Automationn8n Tutorialn8n Self-HostedNo-Code Automationn8n Webhookn8n AI AgentBusiness Process Automationn8n vs Zapiern8n HTTP RequestWorkflow Automation 2024
Building Automation Workflows with n8n: A Complete Guide

n8n (pronounced "n-eight-n") is a source-available workflow automation platform that lets you connect any service, run custom code, and build AI-powered pipelines — all without vendor lock-in. Unlike Zapier or Make, n8n can be fully self-hosted, gives you access to raw HTTP requests, and lets you write JavaScript or Python inside nodes.

1. Core Concepts

  • Workflow — a directed graph of nodes connected by edges. Execution flows left to right.
  • Node — a single unit of work: trigger, action, transform, or condition.
  • Trigger node — starts a workflow. Can be manual, scheduled (Cron), a Webhook, or an app event.
  • Item — n8n's data unit. Every node receives and outputs an array of items, each a JSON object.
  • Credentials — encrypted connection details (API keys, OAuth tokens) stored separately from workflows.
  • Expressions — dynamic values using {{ $json.fieldName }} or {{ $node['NodeName'].json.value }}.

2. Self-Hosting n8n with Docker

yaml
version: '3.8'
services:
  n8n:
    image: n8nio/n8n:latest
    restart: always
    ports:
      - '5678:5678'
    environment:
      - N8N_HOST=n8n.yourdomain.com
      - DB_TYPE=postgresdb
      - DB_POSTGRESDB_HOST=postgres
      - DB_POSTGRESDB_DATABASE=n8n
      - DB_POSTGRESDB_USER=n8n
      - DB_POSTGRESDB_PASSWORD=secret
      - N8N_ENCRYPTION_KEY=your-32-char-secret-key
    volumes:
      - n8n_data:/home/node/.n8n
    depends_on:
      - postgres
  postgres:
    image: postgres:15
    environment:
      - POSTGRES_DB=n8n
      - POSTGRES_USER=n8n
      - POSTGRES_PASSWORD=secret
volumes:
  n8n_data:
  postgres_data:

3. Your First Workflow — Scheduled HTTP Request

  • Add a Schedule Trigger node — set interval to Every Hour.
  • Add an HTTP Request node — set Method to GET, URL to your API endpoint.
  • Add a Set node to reshape the response using expressions: {{ $json.data.title }}.
  • Add a Slack node — connect your credential, set Channel to #alerts.
  • Click Save, then Test Workflow to run manually and inspect each node's output.

4. Webhooks — Trigger Workflows from External Events

javascript
const response = await fetch('https://n8n.yourdomain.com/webhook/order-placed', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    orderId: '12345',
    customer: { name: 'Jane Doe', email: 'jane@example.com' },
    total: 149.99,
  }),
});
// Access in n8n: {{ $json.orderId }}, {{ $json.customer.email }}

Always validate webhook payloads in production. Use n8n's built-in Header Auth or a Respond to Webhook node with custom validation to reject requests without a valid secret.

5. Conditional Branching with IF and Switch

javascript
// IF node condition examples:
{{ $json.total > 100 }}
{{ $json.customer?.email !== undefined && $json.customer.email !== '' }}

// Switch node — route by order status:
// Case 'pending'  → notify warehouse
// Case 'shipped'  → send tracking email
// Case 'refunded' → update CRM

6. Transforming Data with the Code Node

javascript
// Flatten a nested API response and enrich each item
const items = $input.all();

return items.flatMap((item) => {
  const order = item.json;
  return order.lineItems.map((lineItem) => ({
    json: {
      orderId:       order.id,
      orderDate:     new Date(order.createdAt).toISOString().split('T')[0],
      sku:           lineItem.sku,
      quantity:      lineItem.quantity,
      lineTotal:     (lineItem.quantity * lineItem.price).toFixed(2),
      customerEmail: order.customer.email,
    },
  }));
});

7. Error Handling

n8n has two layers of error handling: per-node retry settings, and a global Error Trigger workflow that fires whenever any workflow fails. Connect Error Trigger → Slack for immediate alerts across your entire n8n instance.

8. Sub-Workflows — Reusable Workflow Modules

  • Create a child workflow that starts with an Execute Workflow Trigger node.
  • In the parent, add an Execute Workflow node and select the child by name.
  • Pass data using "Fields to Send" — it arrives as $json in the child's trigger.
  • The child's last node output is returned to the parent as the Execute Workflow node's output.

9. AI Agent Nodes — LLM-Powered Workflows

javascript
// AI Agent workflow pattern:
// 1. Webhook Trigger → receives a support ticket text
// 2. AI Agent node:
//    - Model: OpenAI GPT-4o
//    - System prompt: 'Classify the ticket severity (low/medium/high) and suggest a resolution team.'
//    - Tools: HTTP Request Tool (to query your knowledge base API)
// 3. IF node: route by {{ $json.output.severity }}
//    - high   → PagerDuty alert + assign to senior team
//    - medium → create Jira ticket + send email
//    - low    → auto-reply with FAQ link

10. n8n vs Zapier vs Make — Quick Comparison

  • Self-hosting: n8n ✓ (full control, no usage caps) | Zapier ✗ | Make ✗
  • Custom code: n8n ✓ (JS + Python nodes) | Zapier limited | Make limited
  • Pricing model: n8n free self-hosted, cloud from $20/mo | Zapier from $19.99/mo with task limits | Make from $9/mo with operation limits
  • AI agent support: n8n ✓ native | Zapier partial | Make partial
  • Version control / Git: n8n ✓ export JSON, push to Git | Zapier ✗ | Make ✗

n8n's real power is in combining its 400+ built-in integrations with custom code nodes and AI agents. You can build workflows that would require a dedicated backend service in any other tool.

Want to automate your business operations with n8n? BitPixel Coders designs and implements custom n8n automation workflows and AI agent pipelines — get in touch for a free strategy session.

Get a Free Consultation