n8n Integration with Claude Code

Combine the power of n8n’s visual workflow automation with Claude Code’s AI capabilities to create intelligent, self-improving automation systems. This integration enables you to trigger Claude Code operations from n8n workflows and orchestrate complex AI-driven processes.

🎯 Overview

n8n is a fair-code workflow automation platform that provides:

  • 400+ integrations out of the box
  • Visual workflow builder with code flexibility
  • AI-native capabilities with support for all major LLMs
  • Self-hosting options for complete control
  • Webhook triggers for real-time automation

When combined with Claude Code, you can:

  • Trigger code generation and analysis from n8n workflows
  • Process webhook data through Claude’s intelligence
  • Automate development tasks across your entire stack
  • Build self-improving systems that learn from feedback

πŸš€ Quick Start

Prerequisites

  • n8n instance (self-hosted or cloud)
  • Claude Code installed locally or on a server
  • Anthropic API key

Option 1: Webhook-Based Integration

1. Set Up Claude Code Webhook Server

# Create a simple webhook server for Claude Code
cat > claude-webhook-server.js << 'EOF'
const express = require('express');
const { exec } = require('child_process');
const app = express();
 
app.use(express.json());
 
app.post('/claude-execute', async (req, res) => {
  const { prompt, workingDirectory, timeout = 300000 } = req.body;
  
  try {
    // Execute Claude Code with the prompt
    const command = `claude "${prompt.replace(/"/g, '\\"')}"`;
    
    exec(command, {
      cwd: workingDirectory || process.cwd(),
      timeout
    }, (error, stdout, stderr) => {
      if (error) {
        return res.status(500).json({ error: stderr || error.message });
      }
      res.json({ 
        success: true, 
        output: stdout,
        timestamp: new Date().toISOString()
      });
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
 
app.listen(3000, () => {
  console.log('Claude webhook server running on port 3000');
});
EOF
 
# Start the server
node claude-webhook-server.js

2. Configure n8n Webhook Workflow

{
  "nodes": [
    {
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [250, 300],
      "webhookId": "claude-trigger",
      "parameters": {
        "httpMethod": "POST",
        "path": "claude-automation",
        "responseMode": "onReceived",
        "responseData": "allEntries"
      }
    },
    {
      "name": "HTTP Request",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 3,
      "position": [450, 300],
      "parameters": {
        "method": "POST",
        "url": "http://localhost:3000/claude-execute",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "prompt",
              "value": "={{ $json.prompt }}"
            },
            {
              "name": "workingDirectory",
              "value": "={{ $json.workingDirectory }}"
            }
          ]
        }
      }
    }
  ]
}

Option 2: Direct API Integration

Create n8n Custom Node for Claude Code

// n8n-nodes-claude-code/nodes/ClaudeCode/ClaudeCode.node.ts
import {
  IExecuteFunctions,
  INodeExecutionData,
  INodeType,
  INodeTypeDescription,
} from 'n8n-workflow';
 
export class ClaudeCode implements INodeType {
  description: INodeTypeDescription = {
    displayName: 'Claude Code',
    name: 'claudeCode',
    icon: 'file:claude.svg',
    group: ['transform'],
    version: 1,
    description: 'Execute Claude Code commands',
    defaults: {
      name: 'Claude Code',
    },
    inputs: ['main'],
    outputs: ['main'],
    properties: [
      {
        displayName: 'Prompt',
        name: 'prompt',
        type: 'string',
        typeOptions: {
          rows: 4,
        },
        default: '',
        placeholder: 'e.g., Generate a TypeScript function to...',
        description: 'The prompt to send to Claude Code',
      },
      {
        displayName: 'Working Directory',
        name: 'workingDirectory',
        type: 'string',
        default: '',
        placeholder: '/path/to/project',
        description: 'Directory where Claude Code should execute',
      },
      {
        displayName: 'Operation Mode',
        name: 'mode',
        type: 'options',
        options: [
          {
            name: 'Generate Code',
            value: 'generate',
          },
          {
            name: 'Analyze Code',
            value: 'analyze',
          },
          {
            name: 'Fix Issues',
            value: 'fix',
          },
          {
            name: 'Run Tests',
            value: 'test',
          },
        ],
        default: 'generate',
      },
    ],
  };
 
  async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
    const items = this.getInputData();
    const returnData: INodeExecutionData[] = [];
 
    for (let i = 0; i < items.length; i++) {
      const prompt = this.getNodeParameter('prompt', i) as string;
      const workingDirectory = this.getNodeParameter('workingDirectory', i) as string;
      const mode = this.getNodeParameter('mode', i) as string;
 
      // Execute Claude Code via API or CLI
      const result = await this.helpers.executeCommand(
        `claude "${prompt}"`,
        { cwd: workingDirectory }
      );
 
      returnData.push({
        json: {
          prompt,
          mode,
          output: result,
          timestamp: new Date().toISOString(),
        },
      });
    }
 
    return [returnData];
  }
}

πŸ”§ Practical Workflows

1. Automated Code Review Pipeline

Workflow: GitHub PR β†’ n8n β†’ Claude Code β†’ GitHub Comment
 
Nodes:
1. GitHub Trigger (PR opened/updated)
2. Fetch PR Diff
3. Claude Code Analysis
4. Format Review Comments
5. Post to GitHub PR

n8n Workflow JSON:

{
  "name": "Automated Code Review",
  "nodes": [
    {
      "name": "GitHub PR Trigger",
      "type": "n8n-nodes-base.githubTrigger",
      "parameters": {
        "events": ["pull_request"],
        "repository": "owner/repo"
      }
    },
    {
      "name": "Claude Review",
      "type": "n8n-nodes-base.httpRequest",
      "parameters": {
        "url": "http://localhost:3000/claude-execute",
        "method": "POST",
        "body": {
          "prompt": "Review this PR diff for bugs, security issues, and style: {{ $json.pull_request.diff_url }}"
        }
      }
    }
  ]
}

2. Intelligent Bug Fix Automation

Workflow: Jira Bug β†’ n8n β†’ Claude Code β†’ Git Commit β†’ PR
 
Nodes:
1. Jira Trigger (bug created)
2. Analyze Bug Description
3. Claude Code Fix Generation
4. Create Branch & Commit
5. Open Pull Request

3. Documentation Generation Pipeline

Workflow: Code Push β†’ n8n β†’ Claude Analysis β†’ Update Docs
 
Nodes:
1. Git Push Trigger
2. Detect Changed Files
3. Claude Generate Docs
4. Update README/Wiki
5. Notify Slack

4. Test Generation Workflow

Workflow: New Function β†’ n8n β†’ Claude Test Gen β†’ Run Tests
 
Nodes:
1. File Watcher Trigger
2. Extract New Functions
3. Claude Generate Tests
4. Execute Test Suite
5. Report Results

πŸ“Š Advanced Integration Patterns

Pattern 1: Self-Improving Automation

// n8n Function Node
const previousResults = await $getWorkflowStaticData('global');
const successRate = previousResults.successRate || 0;
 
if (successRate < 0.8) {
  // Trigger Claude to analyze and improve the workflow
  return {
    json: {
      action: 'improve',
      prompt: `Analyze these failed automations and suggest improvements: ${JSON.stringify(previousResults.failures)}`,
      context: 'self-improvement'
    }
  };
}

Pattern 2: Multi-Stage AI Pipeline

{
  "stages": [
    {
      "name": "Understand Requirements",
      "claude_prompt": "Analyze these user requirements and create a technical specification"
    },
    {
      "name": "Generate Implementation",
      "claude_prompt": "Based on the spec, generate the implementation with tests"
    },
    {
      "name": "Review & Refine",
      "claude_prompt": "Review the implementation for best practices and optimize"
    }
  ]
}

Pattern 3: Conditional Claude Routing

// Route to different Claude operations based on input
const taskType = $input.first().json.taskType;
 
const routingMap = {
  'bug': 'Analyze and fix this bug: ',
  'feature': 'Implement this feature with tests: ',
  'refactor': 'Refactor this code for better performance: ',
  'security': 'Audit this code for security vulnerabilities: '
};
 
return {
  json: {
    prompt: routingMap[taskType] + $input.first().json.description
  }
};

πŸ”Œ MCP Integration Bridge

Connect n8n to Claude Code MCP Servers

// Bridge n8n to MCP servers
const mcpBridge = {
  async callMCP(server, method, params) {
    const response = await $http.request({
      method: 'POST',
      url: 'http://localhost:5000/mcp-bridge',
      body: {
        server,
        method,
        params
      }
    });
    return response.data;
  }
};
 
// Example: Query GitHub via MCP
const issues = await mcpBridge.callMCP('github', 'getIssues', {
  repo: 'owner/repo',
  state: 'open'
});
 
// Process with Claude
return {
  json: {
    prompt: `Prioritize these GitHub issues: ${JSON.stringify(issues)}`,
    mcpContext: issues
  }
};

πŸš€ Performance Optimization

1. Batch Processing

// n8n Function Node for batching
const items = $input.all();
const batchSize = 10;
const batches = [];
 
for (let i = 0; i < items.length; i += batchSize) {
  batches.push(items.slice(i, i + batchSize));
}
 
// Process batches with Claude
for (const batch of batches) {
  await $workflow.pause(1000); // Rate limiting
  // Process batch with Claude
}

2. Caching Strategy

// Implement caching for repeated Claude calls
const cacheKey = $input.first().json.cacheKey;
const cached = await $getWorkflowStaticData('cache')[cacheKey];
 
if (cached && Date.now() - cached.timestamp < 3600000) {
  return cached.result;
}
 
// Call Claude and cache result
const result = await callClaude($input.first().json.prompt);
await $setWorkflowStaticData('cache', {
  ...await $getWorkflowStaticData('cache'),
  [cacheKey]: {
    result,
    timestamp: Date.now()
  }
});

3. Parallel Processing

{
  "nodes": [
    {
      "name": "Split Into Parallel",
      "type": "n8n-nodes-base.splitInBatches",
      "parameters": {
        "batchSize": 1,
        "options": {
          "reset": false
        }
      }
    },
    {
      "name": "Parallel Claude Processing",
      "type": "n8n-nodes-base.httpRequest",
      "parameters": {
        "url": "{{ $env.CLAUDE_ENDPOINT }}",
        "method": "POST"
      }
    }
  ]
}

πŸ” Security Best Practices

1. API Key Management

// Use n8n credentials instead of hardcoding
const apiKey = await this.getCredentials('anthropicApi');
 
// Never log sensitive data
const sanitizedRequest = {
  ...request,
  apiKey: '[REDACTED]'
};

2. Input Validation

// Validate inputs before sending to Claude
const validateInput = (input) => {
  const maxLength = 10000;
  const allowedChars = /^[a-zA-Z0-9\s\-_.,!?]+$/;
  
  if (input.length > maxLength) {
    throw new Error('Input too long');
  }
  
  if (!allowedChars.test(input)) {
    throw new Error('Invalid characters in input');
  }
  
  return input;
};

3. Rate Limiting

// Implement rate limiting for Claude calls
const rateLimiter = {
  calls: 0,
  resetTime: Date.now() + 60000,
  
  async checkLimit() {
    if (Date.now() > this.resetTime) {
      this.calls = 0;
      this.resetTime = Date.now() + 60000;
    }
    
    if (this.calls >= 50) {
      throw new Error('Rate limit exceeded');
    }
    
    this.calls++;
  }
};

πŸ“ˆ Monitoring & Analytics

Track Claude Code Performance

// n8n workflow for monitoring
const metrics = {
  startTime: Date.now(),
  promptLength: $input.first().json.prompt.length,
  workflowId: $workflow.id,
  executionId: $execution.id
};
 
// Execute Claude operation
const result = await executeClaudeCode($input.first().json);
 
// Log metrics
await $http.request({
  method: 'POST',
  url: 'http://localhost:9090/metrics',
  body: {
    ...metrics,
    duration: Date.now() - metrics.startTime,
    success: !!result,
    outputLength: result?.length || 0
  }
});

πŸ› οΈ Troubleshooting

Common Issues

  1. Connection Timeouts

    • Increase timeout in HTTP Request node
    • Implement retry logic with exponential backoff
    • Check Claude Code server resources
  2. Large Response Handling

    • Use streaming for large outputs
    • Implement pagination for results
    • Store results in external storage
  3. Webhook Reliability

    • Implement webhook signature validation
    • Add request queuing for high volume
    • Use dead letter queues for failed requests

🎯 Use Case Examples

1. Smart Customer Support

Flow: Support Ticket β†’ Analyze with Claude β†’ Generate Response β†’ Review β†’ Send
 
Benefits:
- 80% faster response time
- Consistent quality
- Learning from feedback

2. Automated DevOps

Flow: Alert β†’ Claude Diagnosis β†’ Generate Fix β†’ Test β†’ Deploy
 
Benefits:
- 24/7 incident response
- Self-healing infrastructure
- Reduced MTTR

3. Content Generation Pipeline

Flow: Topic β†’ Research β†’ Claude Write β†’ Edit β†’ Publish
 
Benefits:
- Scalable content creation
- SEO optimization
- Multi-channel publishing

πŸ“š Resources

πŸ”— n8n Integration Guides


Source: https://n8n.io/integrations/webhook/and/claude/ Source: https://docs.n8n.io/ Last Updated: 2025-07-21