> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/EvolutionAPI/evolution-api/llms.txt
> Use this file to discover all available pages before exploring further.

# N8N Integration

> Connect N8N workflow automation to WhatsApp through Evolution API for powerful automation

# N8N Integration

N8N is a powerful open-source workflow automation platform that connects various apps and services. You can integrate N8N with Evolution API to create sophisticated WhatsApp automation workflows.

## What is N8N?

N8N provides:

* Visual workflow builder with 400+ integrations
* Custom code execution (JavaScript/Python)
* Webhook triggers and actions
* Database connectors
* API integrations
* Conditional logic and branching
* Error handling and retry logic
* Scheduled workflows

## Enable N8N Integration

Add this environment variable to your `.env` file:

```bash theme={null}
# Enable N8N integration
N8N_ENABLED=true
```

## Configuration Settings

### Create Default Settings

Before creating N8N bots, configure default behavior settings for your instance.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://your-api.com/n8n/settings/{instance} \
    -H "apikey: your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "expire": 300,
      "keywordFinish": "#EXIT",
      "delayMessage": 1000,
      "unknownMessage": "I did not understand your message.",
      "listeningFromMe": false,
      "stopBotFromMe": false,
      "keepOpen": false,
      "debounceTime": 10,
      "ignoreJids": []
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://your-api.com/n8n/settings/{instance}', {
    method: 'POST',
    headers: {
      'apikey': 'your-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      expire: 300,
      keywordFinish: '#EXIT',
      delayMessage: 1000,
      unknownMessage: 'I did not understand your message.',
      listeningFromMe: false,
      stopBotFromMe: false,
      keepOpen: false,
      debounceTime: 10,
      ignoreJids: []
    })
  });
  ```
</CodeGroup>

#### Settings Parameters

<ResponseField name="expire" type="number" required>
  Session expiration time in seconds. Default: 300 (5 minutes)
</ResponseField>

<ResponseField name="keywordFinish" type="string" required>
  Keyword to terminate the bot session. Example: "#EXIT", "bye"
</ResponseField>

<ResponseField name="delayMessage" type="number" required>
  Delay in milliseconds between messages. Default: 1000
</ResponseField>

<ResponseField name="unknownMessage" type="string" required>
  Message sent when bot encounters an error or cannot respond
</ResponseField>

<ResponseField name="listeningFromMe" type="boolean" required>
  Whether bot responds to messages sent by the instance owner
</ResponseField>

<ResponseField name="stopBotFromMe" type="boolean" required>
  Whether instance owner can stop the bot session
</ResponseField>

<ResponseField name="keepOpen" type="boolean" required>
  Keep session open after completion. Default: false
</ResponseField>

<ResponseField name="debounceTime" type="number" required>
  Seconds to wait before processing rapid messages. Default: 10
</ResponseField>

<ResponseField name="ignoreJids" type="array" required>
  List of JIDs (phone numbers) to ignore
</ResponseField>

## Create an N8N Bot

<Steps>
  <Step title="Create N8N Workflow">
    Build your automation workflow in N8N with a Webhook node as the trigger.
  </Step>

  <Step title="Get webhook URL">
    Copy the production webhook URL from your N8N workflow.
  </Step>

  <Step title="Configure authentication (optional)">
    If using Basic Auth in N8N, note your username and password.
  </Step>

  <Step title="Create bot in Evolution API">
    Register the N8N webhook with Evolution API.
  </Step>

  <Step title="Test the integration">
    Send a message matching your trigger to invoke the N8N workflow.
  </Step>
</Steps>

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://your-api.com/n8n/create/{instance} \
    -H "apikey: your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "enabled": true,
      "description": "Order Processing Workflow",
      "webhookUrl": "https://n8n.yourdomain.com/webhook/order-process",
      "basicAuthUser": "n8n-user",
      "basicAuthPass": "secure-password",
      "triggerType": "keyword",
      "triggerOperator": "startsWith",
      "triggerValue": "order",
      "expire": 300,
      "keywordFinish": "#EXIT",
      "delayMessage": 1000,
      "unknownMessage": "Sorry, something went wrong.",
      "listeningFromMe": false,
      "stopBotFromMe": false,
      "keepOpen": false,
      "debounceTime": 10
    }'
  ```

  ```javascript JavaScript theme={null}
  const n8nBot = await fetch('https://your-api.com/n8n/create/{instance}', {
    method: 'POST',
    headers: {
      'apikey': 'your-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      enabled: true,
      description: 'Order Processing Workflow',
      webhookUrl: 'https://n8n.yourdomain.com/webhook/order-process',
      basicAuthUser: 'n8n-user',
      basicAuthPass: 'secure-password',
      triggerType: 'keyword',
      triggerOperator: 'startsWith',
      triggerValue: 'order',
      expire: 300,
      keywordFinish: '#EXIT',
      delayMessage: 1000,
      unknownMessage: 'Sorry, something went wrong.',
      listeningFromMe: false,
      stopBotFromMe: false,
      keepOpen: false,
      debounceTime: 10
    })
  });
  ```
</CodeGroup>

### Request Parameters

<ResponseField name="enabled" type="boolean" required>
  Enable or disable this bot
</ResponseField>

<ResponseField name="description" type="string" required>
  Description of the bot purpose
</ResponseField>

<ResponseField name="webhookUrl" type="string" required>
  N8N webhook URL (production URL from your workflow)
</ResponseField>

<ResponseField name="basicAuthUser" type="string">
  Basic authentication username (if webhook is protected)
</ResponseField>

<ResponseField name="basicAuthPass" type="string">
  Basic authentication password (if webhook is protected)
</ResponseField>

<ResponseField name="triggerType" type="string" required>
  Trigger type: "all", "keyword", or "advanced"
</ResponseField>

<ResponseField name="triggerOperator" type="string">
  For keyword triggers: "equals", "contains", "startsWith", "endsWith", "regex"
</ResponseField>

<ResponseField name="triggerValue" type="string">
  The keyword or regex pattern to trigger this bot
</ResponseField>

## Webhook Payload

When a trigger is matched, Evolution API sends this payload to your N8N webhook:

```json theme={null}
{
  "chatInput": "user message content",
  "sessionId": "unique-session-id",
  "remoteJid": "5511999999999@s.whatsapp.net",
  "pushName": "User Name",
  "instanceName": "my-instance",
  "messageType": "conversation",
  "message": {
    "key": {
      "remoteJid": "5511999999999@s.whatsapp.net",
      "fromMe": false,
      "id": "message-id"
    },
    "message": {
      "conversation": "user message"
    },
    "messageTimestamp": 1234567890
  }
}
```

### Payload Fields

<ResponseField name="chatInput" type="string">
  The text content of the user's message
</ResponseField>

<ResponseField name="sessionId" type="string">
  Unique session identifier for tracking conversation context
</ResponseField>

<ResponseField name="remoteJid" type="string">
  WhatsApp JID of the sender
</ResponseField>

<ResponseField name="pushName" type="string">
  Display name of the sender
</ResponseField>

<ResponseField name="instanceName" type="string">
  Name of the Evolution API instance
</ResponseField>

<ResponseField name="messageType" type="string">
  Type of message: "conversation", "imageMessage", "audioMessage", etc.
</ResponseField>

<ResponseField name="message" type="object">
  Complete WhatsApp message object with metadata
</ResponseField>

## N8N Response Format

Your N8N workflow should return a response in this format:

```json theme={null}
{
  "messages": [
    {
      "type": "text",
      "content": "Thank you for your order! Your order number is #12345."
    },
    {
      "type": "image",
      "content": "https://example.com/order-confirmation.png",
      "caption": "Order Confirmation"
    }
  ]
}
```

### Message Types

**Text Message:**

```json theme={null}
{
  "type": "text",
  "content": "Your message here"
}
```

**Image Message:**

```json theme={null}
{
  "type": "image",
  "content": "https://example.com/image.jpg",
  "caption": "Optional caption"
}
```

**Audio Message:**

```json theme={null}
{
  "type": "audio",
  "content": "https://example.com/audio.mp3"
}
```

**Document Message:**

```json theme={null}
{
  "type": "document",
  "content": "https://example.com/document.pdf",
  "fileName": "invoice.pdf"
}
```

## Trigger Types

### All Messages

Respond to every message (only one "all" trigger allowed per instance):

```json theme={null}
{
  "triggerType": "all"
}
```

### Keyword Trigger

Trigger based on specific keywords:

```json theme={null}
{
  "triggerType": "keyword",
  "triggerOperator": "startsWith",
  "triggerValue": "order"
}
```

**Available operators:**

* `equals` - Exact match
* `contains` - Contains the keyword
* `startsWith` - Message starts with keyword
* `endsWith` - Message ends with keyword
* `regex` - Regular expression match

### Advanced Trigger

Use regex for complex pattern matching:

```json theme={null}
{
  "triggerType": "advanced",
  "triggerValue": "^order\\s+(\\d+)$"
}
```

## Update N8N Bot

Modify an existing N8N bot configuration:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PUT https://your-api.com/n8n/update/{instance}/{botId} \
    -H "apikey: your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "enabled": true,
      "description": "Updated Workflow",
      "webhookUrl": "https://n8n.yourdomain.com/webhook/new-workflow"
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch('https://your-api.com/n8n/update/{instance}/{botId}', {
    method: 'PUT',
    headers: {
      'apikey': 'your-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      enabled: true,
      description: 'Updated Workflow',
      webhookUrl: 'https://n8n.yourdomain.com/webhook/new-workflow'
    })
  });
  ```
</CodeGroup>

## Delete N8N Bot

Remove an N8N bot from your instance:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X DELETE https://your-api.com/n8n/delete/{instance}/{botId} \
    -H "apikey: your-api-key"
  ```

  ```javascript JavaScript theme={null}
  await fetch('https://your-api.com/n8n/delete/{instance}/{botId}', {
    method: 'DELETE',
    headers: {
      'apikey': 'your-api-key'
    }
  });
  ```
</CodeGroup>

## Fetch N8N Bots

Retrieve all N8N bots configured for your instance:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET https://your-api.com/n8n/fetch/{instance} \
    -H "apikey: your-api-key"
  ```

  ```javascript JavaScript theme={null}
  const bots = await fetch('https://your-api.com/n8n/fetch/{instance}', {
    headers: {
      'apikey': 'your-api-key'
    }
  }).then(res => res.json());
  ```
</CodeGroup>

## Session Management

### Change Session Status

Update the status of an active N8N session:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://your-api.com/n8n/changeStatus/{instance} \
    -H "apikey: your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "remoteJid": "5511999999999@s.whatsapp.net",
      "status": "closed"
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch('https://your-api.com/n8n/changeStatus/{instance}', {
    method: 'POST',
    headers: {
      'apikey': 'your-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      remoteJid: '5511999999999@s.whatsapp.net',
      status: 'closed'
    })
  });
  ```
</CodeGroup>

### Fetch Sessions

Get all active N8N sessions:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET https://your-api.com/n8n/fetchSessions/{instance} \
    -H "apikey: your-api-key"
  ```

  ```javascript JavaScript theme={null}
  const sessions = await fetch('https://your-api.com/n8n/fetchSessions/{instance}', {
    headers: {
      'apikey': 'your-api-key'
    }
  }).then(res => res.json());
  ```
</CodeGroup>

## N8N Workflow Examples

### Order Processing

1. Webhook trigger receives order message
2. Parse order details with code node
3. Create order in database (PostgreSQL/MySQL node)
4. Send confirmation email (Email node)
5. Update inventory (HTTP Request node)
6. Return confirmation message to WhatsApp

### CRM Integration

1. Webhook receives customer message
2. Search for contact in CRM (Salesforce/HubSpot node)
3. Create or update contact record
4. Log interaction in CRM
5. Check for open tickets
6. Return personalized response

### Support Ticket Creation

1. Webhook receives support request
2. Extract issue details with AI (OpenAI node)
3. Create ticket in system (Jira/Zendesk node)
4. Assign to team member
5. Send ticket number to customer
6. Set up follow-up reminder (Schedule Trigger)

## Use Cases

<Accordion title="E-commerce Automation">
  Automate sales processes:

  * Order placement and confirmation
  * Inventory checks and updates
  * Payment processing
  * Shipping notifications
  * Order status tracking
</Accordion>

<Accordion title="CRM Integration">
  Connect WhatsApp to your CRM:

  * Auto-create/update contacts
  * Log all interactions
  * Trigger sales workflows
  * Update deal stages
  * Sync customer data
</Accordion>

<Accordion title="Support Ticketing">
  Streamline customer support:

  * Auto-create support tickets
  * Route to appropriate teams
  * Update ticket status
  * Send notifications
  * Gather customer feedback
</Accordion>

<Accordion title="Multi-System Orchestration">
  Connect multiple platforms:

  * Database operations
  * API integrations
  * File processing
  * Data transformation
  * Cross-system synchronization
</Accordion>

## Best Practices

<Note>
  Always activate your N8N workflows before testing with Evolution API. Use production webhook URLs, not test URLs.
</Note>

<Warning>
  Protect your N8N webhooks with Basic Authentication to prevent unauthorized access.
</Warning>

* **Use error handling**: Add error catch nodes in N8N workflows
* **Validate inputs**: Check and sanitize data from WhatsApp messages
* **Implement timeouts**: Set reasonable timeout values for external API calls
* **Log executions**: Enable execution logging in N8N for debugging
* **Test workflows**: Thoroughly test in N8N before connecting to WhatsApp
* **Secure webhooks**: Always use HTTPS and authentication
* **Handle async operations**: Use webhooks or callbacks for long-running tasks

## Troubleshooting

<Accordion title="Workflow not triggered">
  * Verify `N8N_ENABLED=true` in environment
  * Check that bot is enabled (`enabled: true`)
  * Ensure trigger conditions match incoming messages
  * Verify N8N workflow is activated (not in draft)
  * Check webhook URL is correct and accessible
  * Test webhook manually with curl or Postman
</Accordion>

<Accordion title="Authentication errors">
  * Verify Basic Auth credentials are correct
  * Check that credentials match N8N webhook settings
  * Ensure webhook has authentication enabled if using credentials
  * Test authentication with curl
</Accordion>

<Accordion title="No response from workflow">
  * Check N8N execution logs for errors
  * Verify workflow returns proper response format
  * Ensure all nodes execute successfully
  * Check for timeout issues in long-running workflows
  * Verify network connectivity between Evolution API and N8N
</Accordion>

<Accordion title="Session not maintained">
  * Increase `expire` time if sessions timeout too quickly
  * Set `keepOpen: true` for longer conversations
  * Use sessionId in N8N workflow for context tracking
  * Store session data in N8N database for persistence
</Accordion>

## Advanced Configuration

### Multiple Workflows

Deploy different workflows for different purposes:

```javascript theme={null}
// Sales workflow
{
  webhookUrl: 'https://n8n.example.com/webhook/sales',
  triggerType: 'keyword',
  triggerValue: 'buy'
}

// Support workflow
{
  webhookUrl: 'https://n8n.example.com/webhook/support',
  triggerType: 'keyword',
  triggerValue: 'help'
}

// General automation (fallback)
{
  webhookUrl: 'https://n8n.example.com/webhook/general',
  triggerType: 'all'
}
```

### Self-Hosted N8N

For self-hosted N8N installations:

```json theme={null}
{
  "webhookUrl": "https://n8n.yourcompany.com/webhook/whatsapp",
  "basicAuthUser": "your-user",
  "basicAuthPass": "your-password"
}
```

Ensure your N8N instance is accessible from Evolution API server.

## Related Integrations

* [Flowise](/integrations/flowise) - LLM workflow automation
* [Dify](/integrations/dify) - AI application platform
* [Typebot](/integrations/typebot) - Chatbot builder
* [Chatwoot](/integrations/chatwoot) - Customer support platform
