n8nOpenWAWhatsApp APIDockerCloudflare Tunnelsself-hostedOllamaAI

Self-Host a Free WhatsApp API on Your Own Machine with n8n and OpenWA

·45 min read

This is the single-page version of a 6-part series. Every step is here — read top to bottom and you will have a working WhatsApp AI bot running on your own machine by the end.


Table of Contents


  • Part 1 — n8n + Cloudflare Tunnel Setup
  • Part 2 — OpenWA Docker Setup
  • Part 3 — Connecting n8n to OpenWA



  • Prerequisites


  • Docker installed (or Podman with socket activation)
  • A domain proxied through Cloudflare (free tier works)
  • cloudflared installed on the host
  • A Linux machine — this guide uses ~/projects as the workspace
  • A phone with WhatsApp installed



  • Part 1 — n8n + Cloudflare Tunnel Setup


    Read the dedicated post: n8n + Cloudflare Tunnel Setup

    Step 1: Directory and Docker Compose


    Create the project directory:


    
    mkdir -p ~/projects/n8n
    cd ~/projects/n8n
    

    Create docker-compose.yml:


    
    services:
      n8n:
        image: n8nio/n8n:latest
        container_name: n8n
        restart: unless-stopped
        ports:
          - "5679:5678"
        environment:
          - N8N_HOST=n8n.yourdomain.com
          - N8N_PORT=5678
          - N8N_PROTOCOL=https
          - N8N_EDITOR_BASE_URL=https://n8n.yourdomain.com
          - WEBHOOK_URL=https://n8n.yourdomain.com/
          - N8N_DEFAULT_BINARY_DATA_MODE=filesystem
          - N8N_PROXY_HOPS=1
          - N8N_RUNNERS_ENABLED=true
          - GENERIC_TIMEZONE=UTC
        volumes:
          - n8n_data:/home/node/.n8n
        healthcheck:
          test: ["CMD", "wget", "--spider", "-q", "http://localhost:5678/healthz"]
          interval: 30s
          timeout: 10s
          retries: 5
    
    volumes:
      n8n_data:
        driver: local
    
    networks:
      default:
        name: openwa-network
    

    Replace n8n.yourdomain.com with your actual subdomain throughout.


    Important — the shared Docker network: Both n8n and OpenWA must be on the same Docker network so n8n can reach OpenWA at http://openwa-api:2785 by container name. The compose above creates a network named openwa-network. When you bring up OpenWA in Part 2, make sure its compose also joins this network — add the following to your docker-compose.dev.yml under OpenWA:


    
    networks:
      default:
        name: openwa-network
        external: true
    

    If they are on separate networks, n8n will get connection refused when trying to send WhatsApp messages — and the error won't tell you why.


    Follow the Cloudflare Tunnel Setup guide to install cloudflared, create the tunnel, configure ingress rules, and route your domain.

    Once the tunnel is live and n8n is reachable at https://n8n.yourdomain.com, continue below.


    n8nctl — a simple script to start/stop n8n and the Cloudflare tunnel together. Get it here.



    Part 2 — OpenWA Docker Setup


    Read the dedicated post: OpenWA Docker Setup — From Zero to First Login

    OpenWA is an open-source WhatsApp API gateway built on NestJS and whatsapp-web.js. It gives you a REST API to send and receive messages without paying Meta for WhatsApp Business API access.


    GitHub: github.com/rmyndharis/OpenWA


    Clone and One Command


    
    cd ~/projects
    git clone https://github.com/rmyndharis/OpenWA.git
    cd OpenWA
    docker compose -f docker-compose.dev.yml up -d
    

    No environment files to create. The dev compose has zero-config defaults for everything: NestJS API + dashboard on port 2785, SQLite, Chromium headless, named volume for all data, ports bound to 127.0.0.1.


    Before you start — append this to the bottom of docker-compose.dev.yml in the OpenWA directory so it joins the same network as n8n:


    
    networks:
      default:
        name: openwa-network
    

    Then run the compose command above. Without this, n8n cannot reach OpenWA by container name and you will get silent connection refused errors.


    Wait for It to Start


    
    docker compose -f docker-compose.dev.yml logs -f
    

    Look for OpenWA is running on http://localhost:2785. Takes 10–20 seconds on first run.


    Login to the Dashboard


    Open http://localhost:2785. The first-boot screen prompts for the admin API key.


    
    # Find the container name
    docker ps --format '{{.Names}}'
    
    # Read the key
    sudo docker exec container-name cat /app/data/.api-key
    

    Paste the key into the dashboard. Store it in a password manager — you need it for every API call and for n8n credentials.


    Session State Machine


    disconnected → connecting → authenticating (scan QR) → ready


    Stuck at "authenticating"? Pin a known-good WhatsApp Web version in .env:


    
    WWEBJS_WEB_VERSION=2.3000.1023204257
    



    Part 3 — Connecting n8n to OpenWA


    Read the dedicated post: Connecting n8n to OpenWA — First Integration

    n8n and OpenWA run on the same machine. OpenWA never needs a public URL. n8n → OpenWA is always localhost:2785. OpenWA → n8n (webhooks) requires your public Cloudflare Tunnel URL.


    Step 1: Register the Webhook in OpenWA


    Go to http://localhost:2785 → Webhooks → Create Webhook.


    Fill in:

  • Session — select your session (e.g. default)
  • URL — https://n8n.yourdomain.com/webhook-test/ (test) or https://n8n.yourdomain.com/webhook/ (production)
  • Events — pick the ones you need (see below)

  • Tip: Register the test URL first (/webhook-test/). Use the test URL while building and debugging your workflow — it doesn't require authentication. Once everything works, switch to the production URL (/webhook/).

    Available events:


    Event When it fires
    message.received A message arrives on your WhatsApp
    message.sent A message is sent from your session
    message.ack Message delivery/read acknowledgement
    message.failed Message failed to send
    message.revoked A message was deleted by sender
    session.status Session status changes
    session.qr QR code generated (scan required)
    session.authenticated Session authenticated successfully
    session.disconnected Session disconnects
    group.join Someone joins a group
    group.leave Someone leaves a group
    group.update Group info updated
    * All events

    For a basic bot, select message.received only. Adding * fires on everything — including your own outgoing messages, which will cause an infinite loop if your workflow replies unconditionally.


    Step 2: Add the OpenWA Credential in n8n


    Open https://n8n.yourdomain.com → Credentials → Add Credential → HTTP Header Auth:

  • Name: X-API-Key
  • Value: your OpenWA API key

  • Before Step 3: Open your n8n Webhook node and click Listen. Then send a message from WhatsApp (or have someone message you). n8n will receive the payload. If you see the incoming data in the Webhook node's output — you are connected. Proceed to Step 3.

    Step 3: Configure the HTTP Request Node


    Add an HTTP Request node in your n8n workflow:


  • Method: POST
  • URL: http://localhost:2785/api/send/text
  • Authentication: HTTP Header Auth → select the credential created in Step 3
  • Body:

  • 
    {
      "session": "default",
      "to": "{{ $json.message.from }}",
      "text": "Got your message!"
    }
    



    Part 4 — WhatsApp + n8n Workflow Varieties


    Read the dedicated post: 3 WhatsApp + n8n Workflow Varieties

    Three workflows from the same webhook trigger. All use: OpenWA at http://openwa-api:2785 (Docker network hostname, not localhost), Ollama llama3.2:3b for AI, 30-message Simple Memory per chatId.


    Variety 1: Personal AI Chat Bot


    IF node fires when body.data.contact.pushName equals the name you set. Everyone else is silently ignored.


    Three mistakes:

  • Wrong pushName — check the webhook payload for the actual value, not your contact list name
  • Memory is per chatId — you're already covered for multiple people automatically
  • No system prompt — change "You are a helpful assistant" to something specific immediately

  • Variety 2: Group @agent Bot


    The bot lives in a WhatsApp group. Someone @mentions it to get a response — without the mention filter, every message in the group fires the workflow and the bot replies to its own replies → infinite loop.


    How it works:

  • IF node fires when body.data.isGroup == true AND message contains "@agent"
  • Everyone in the group can chat with the bot by tagging it
  • The bot sees all messages but only responds when @mentioned

  • Two mistakes to avoid:

  • No @agent filter — bot fires on every group message including its own replies → infinite loop
  • Generic system prompt — groups are noisy; use short, direct response instructions. Something like: "You are a helpful group assistant. Keep answers brief and relevant."
  • 30 messages in a busy group — 30 messages across 15 people destroys context. Drop to 10.

  • Variety 3: Keyword Router


    Avoids spam entirely — no @mention needed, but the bot only reacts to specific keywords. This is the cleanest production setup for group commands.


    How it works:

  • Replace the single agent node with a Switch node — each branch checks for a different keyword (@order, @help, @status, etc.)
  • Each branch triggers a different workflow or prompt tailored to that command
  • Always add a fallback branch that replies with the list of valid keywords the group can use

  • Why this avoids spam:

  • No @mention required — clean UX
  • Bot stays silent unless it sees a valid keyword
  • Switch node routes to the right agent in seconds

  • The Workflow JSON


    Copy the JSON below → In n8n: Workflows → three dots menu → Import from JSON → paste → import. Then re-select credentials in every node with a key icon.


    
    {
      "name": "WhatsApp AI Bot: personal chat + group @agent (OpenWA + Ollama)",
      "nodes": [
        {
          "parameters": {
            "content": "## Reply to WhatsApp messages with a local AI agent using OpenWA and Ollama\n\n**Who it's for:** anyone who wants a WhatsApp AI assistant without paying for the Meta Cloud API, and without sending chats to a cloud LLM.\n\n**How it works**\n1. [OpenWA](https://github.com/rmyndharis/OpenWA), a free self-hosted WhatsApp API gateway, posts every incoming message to the webhook.\n2. **Should the bot reply?** passes only two kinds of message: a direct message from the contact you name, or a group message that contains your mention keyword (default `@agent`). Everything else is ignored, so the bot never floods a group.\n3. An AI Agent answers with a local Ollama model and remembers the last 30 messages per chat.\n4. The reply goes back to the same chat through OpenWA's `send-text` endpoint.\n\n**Setup**\n1. Run OpenWA and connect a WhatsApp session (scan the QR code).\n2. Run Ollama and pull a model: `ollama pull llama3.2:3b`.\n3. Fill in **Bot settings**: OpenWA URL, the contact's WhatsApp profile name (`pushName`, not the name saved in your phone), the mention keyword and the system prompt.\n4. Create a **Header Auth** credential: name `X-API-Key`, value = your OpenWA API key. Select it in **Send reply via OpenWA**. Select your Ollama credential in **Ollama chat model**.\n5. In OpenWA \u2192 Webhooks, add this workflow's production webhook URL for the `message.received` event, then activate the workflow.\n\nFull step-by-step guide (Docker, tunnel, webhooks): [abhishekrajpurohit.in](https://abhishekrajpurohit.in/blog/complete-guide-self-hosting-n8n-openwa-whatsapp-api)",
            "height": 820,
            "width": 460,
            "color": 1
          },
          "id": "8b095b9c-9890-4a10-af04-24997d00b4bd",
          "name": "Overview",
          "type": "n8n-nodes-base.stickyNote",
          "typeVersion": 1,
          "position": [
            -480,
            -80
          ]
        },
        {
          "parameters": {
            "content": "## 1. Receive and filter\nWebhook from OpenWA, your settings, and the reply gate.",
            "height": 420,
            "width": 660,
            "color": 7
          },
          "id": "58764b41-3b84-4e3b-a3cf-dc8a1153b2be",
          "name": "Step 1",
          "type": "n8n-nodes-base.stickyNote",
          "typeVersion": 1,
          "position": [
            0,
            160
          ]
        },
        {
          "parameters": {
            "content": "## 2. Generate the reply\nLocal Ollama model with per-chat memory.",
            "height": 560,
            "width": 420,
            "color": 7
          },
          "id": "248f5cd2-78bb-49d1-9d71-f6f5bd03bd42",
          "name": "Step 2",
          "type": "n8n-nodes-base.stickyNote",
          "typeVersion": 1,
          "position": [
            700,
            160
          ]
        },
        {
          "parameters": {
            "content": "## 3. Send it back\nPOST to OpenWA send-text.",
            "height": 420,
            "width": 300,
            "color": 7
          },
          "id": "54fce74c-c9c1-4fa4-9ea5-9d60eccd77c9",
          "name": "Step 3",
          "type": "n8n-nodes-base.stickyNote",
          "typeVersion": 1,
          "position": [
            1160,
            160
          ]
        },
        {
          "parameters": {
            "httpMethod": "POST",
            "path": "wa-webhook",
            "options": {}
          },
          "id": "e27fd98d-e8f1-4485-9a54-832d531a723f",
          "name": "Receive WhatsApp message",
          "type": "n8n-nodes-base.webhook",
          "typeVersion": 2.1,
          "position": [
            60,
            340
          ],
          "webhookId": "191913a8-511e-4cd0-9418-1db18069c22b"
        },
        {
          "parameters": {
            "assignments": {
              "assignments": [
                {
                  "id": "76da82cf-df57-4552-990b-04e6da77a558",
                  "name": "openwaBaseUrl",
                  "value": "http://openwa-api:2785",
                  "type": "string"
                },
                {
                  "id": "6a30d48f-01b3-448b-b675-216446439b81",
                  "name": "allowedContactName",
                  "value": "YourContactName",
                  "type": "string"
                },
                {
                  "id": "573736ee-8c63-422c-95c8-862cc30d8bcb",
                  "name": "mentionKeyword",
                  "value": "@agent",
                  "type": "string"
                },
                {
                  "id": "33dae449-4f9f-42d1-8470-0b3304af59ba",
                  "name": "systemPrompt",
                  "value": "You are a helpful assistant replying on WhatsApp. Keep answers short and direct. Use numbered lists for steps. If you are unsure, say so.",
                  "type": "string"
                }
              ]
            },
            "includeOtherFields": true,
            "options": {}
          },
          "id": "ad52ad92-858d-4057-a6bc-eff3edc183b4",
          "name": "Bot settings",
          "type": "n8n-nodes-base.set",
          "typeVersion": 3.4,
          "position": [
            260,
            340
          ]
        },
        {
          "parameters": {
            "conditions": {
              "options": {
                "caseSensitive": true,
                "leftValue": "",
                "typeValidation": "loose",
                "version": 2
              },
              "conditions": [
                {
                  "id": "254e0a11-59c1-4855-b343-596d716e7626",
                  "leftValue": "={{ $json.body.data.isGroup !== true && $json.body.data.contact?.pushName === $json.allowedContactName }}",
                  "rightValue": "",
                  "operator": {
                    "type": "boolean",
                    "operation": "true",
                    "singleValue": true
                  }
                },
                {
                  "id": "fc87d657-3596-430c-9a34-09e0b643cf13",
                  "leftValue": "={{ $json.body.data.isGroup === true && String($json.body.data.body || '').includes($json.mentionKeyword) }}",
                  "rightValue": "",
                  "operator": {
                    "type": "boolean",
                    "operation": "true",
                    "singleValue": true
                  }
                }
              ],
              "combinator": "or"
            },
            "looseTypeValidation": true,
            "options": {}
          },
          "id": "03b18476-46f0-4245-809b-1c856e1cc7e2",
          "name": "Should the bot reply?",
          "type": "n8n-nodes-base.if",
          "typeVersion": 2.2,
          "position": [
            460,
            340
          ]
        },
        {
          "parameters": {
            "promptType": "define",
            "text": "={{ $json.body.data.body }}",
            "options": {
              "systemMessage": "={{ $json.systemPrompt }}"
            }
          },
          "id": "05816bd5-2b36-400a-a3ad-e16abc6f97ab",
          "name": "AI agent",
          "type": "@n8n/n8n-nodes-langchain.agent",
          "typeVersion": 3.1,
          "position": [
            760,
            340
          ]
        },
        {
          "parameters": {
            "model": "llama3.2:3b",
            "options": {}
          },
          "id": "ea821e70-dd40-49c9-8369-b375b74ba86a",
          "name": "Ollama chat model",
          "type": "@n8n/n8n-nodes-langchain.lmChatOllama",
          "typeVersion": 1,
          "position": [
            740,
            580
          ]
        },
        {
          "parameters": {
            "sessionIdType": "customKey",
            "sessionKey": "={{ $('Receive WhatsApp message').item.json.body.data.chatId }}",
            "contextWindowLength": 30
          },
          "id": "b74115f2-29b2-4ac1-b722-4e670b95331d",
          "name": "Chat memory",
          "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
          "typeVersion": 1.3,
          "position": [
            920,
            580
          ]
        },
        {
          "parameters": {
            "method": "POST",
            "url": "={{ $('Bot settings').item.json.openwaBaseUrl }}/api/sessions/{{ $('Receive WhatsApp message').item.json.body.sessionId }}/messages/send-text",
            "authentication": "genericCredentialType",
            "genericAuthType": "httpHeaderAuth",
            "sendBody": true,
            "specifyBody": "json",
            "jsonBody": "={{ JSON.stringify({ chatId: $('Receive WhatsApp message').item.json.body.data.chatId, text: $json.output }) }}",
            "options": {}
          },
          "id": "3e214463-c8c9-4e22-83b9-3d68d9f7b651",
          "name": "Send reply via OpenWA",
          "type": "n8n-nodes-base.httpRequest",
          "typeVersion": 4.2,
          "position": [
            1240,
            340
          ]
        }
      ],
      "connections": {
        "Receive WhatsApp message": {
          "main": [
            [
              {
                "node": "Bot settings",
                "type": "main",
                "index": 0
              }
            ]
          ]
        },
        "Bot settings": {
          "main": [
            [
              {
                "node": "Should the bot reply?",
                "type": "main",
                "index": 0
              }
            ]
          ]
        },
        "Should the bot reply?": {
          "main": [
            [
              {
                "node": "AI agent",
                "type": "main",
                "index": 0
              }
            ],
            []
          ]
        },
        "AI agent": {
          "main": [
            [
              {
                "node": "Send reply via OpenWA",
                "type": "main",
                "index": 0
              }
            ]
          ]
        },
        "Ollama chat model": {
          "ai_languageModel": [
            [
              {
                "node": "AI agent",
                "type": "ai_languageModel",
                "index": 0
              }
            ]
          ]
        },
        "Chat memory": {
          "ai_memory": [
            [
              {
                "node": "AI agent",
                "type": "ai_memory",
                "index": 0
              }
            ]
          ]
        }
      },
      "pinData": {},
      "settings": {
        "executionOrder": "v1"
      },
      "meta": {
        "templateCredsSetupCompleted": false
      }
    }
    

    This covers Variety 1 and Variety 2 with one Should the bot reply? gate; add a Switch after it for Variety 3. After importing: select a Header Auth credential (X-API-Key = your OpenWA key) in Send reply via OpenWA and your Ollama credential in Ollama chat model. In Bot settings, change YourContactName to the actual pushName from your webhook payload. Activate the workflow.




    You're Done


    At this point you have:


  • n8n running at https://n8n.yourdomain.com behind a Cloudflare Tunnel with zero open firewall ports
  • OpenWA running locally, WhatsApp session authenticated and ready
  • A management script to start/stop/monitor the whole stack
  • Backups of all OpenWA data on a 7-day rotation
  • A working WhatsApp AI workflow ready to extend

  • The stack is not the hard part. The hard part is the system prompt and deciding what to actually automate. Start simple — pick one variety, ship it, let people use it, fix what breaks.


    Looking for the OpenWA API reference? → OpenWA API Reference for n8n Workflows — every endpoint with exact n8n HTTP Request node configuration.

    Rather have this built for you?

    I set up WhatsApp and n8n automation for small businesses: reply bots, order updates and lead capture, handed over with backups and a known monthly cost. Fixed packages from ₹15,000.

    See packages and pricing

    Also built on WhatsApp: WhatsApp CRM · AI receptionist · lead management · real estate CRM

    Built something similar or want to talk through the architecture? Get in touch.