n8n Automation

n8n Workflow Security: Protecting Integrations

Petru Constantin
••12 min read
#n8n#workflow-security#automation#integration-security#credentials

Petru Constantin is the founder of DeviDevs and designed the multi-agent platform the company runs on, with guardrails enforced in code. Code examples are written against the n8n 2.47 (stable 2.47.7) documentation.

n8n Workflow Automation Security Guide: Protecting Your Integration Pipelines

n8n has become a powerful tool for building workflow automations that connect various services and APIs. However, with great power comes great responsibility - these workflows often handle sensitive data and credentials that require careful security consideration.

This guide covers essential security practices for n8n deployments.

Understanding n8n Security Architecture

n8n workflows operate at the intersection of multiple systems, making security critical:

External Services ←→ n8n Instance ←→ Internal Systems
       ↓                  ↓                  ↓
   API Keys         Credentials        Database Access
   OAuth Tokens     Workflow Data      Internal APIs
   Webhooks         Execution Logs     User Data

Key Security Concerns

  1. Credential exposure - Workflows contain sensitive API keys and tokens
  2. Data leakage - Workflow data may contain PII or business secrets
  3. Unauthorized access - Who can create, modify, or execute workflows
  4. Injection attacks - Malicious input through webhooks or triggers
  5. Supply chain risks - Community nodes may contain vulnerabilities

Secure n8n Deployment

Environment Configuration

# docker-compose.yml for an n8n deployment behind a reverse proxy
 
services:
  n8n:
    image: n8nio/n8n:2.47.7   # pin a version; read the release notes before upgrading
    restart: always
    ports:
      - "127.0.0.1:5678:5678"  # Only localhost, the reverse proxy is the public entry point
    environment:
      # Database (PostgreSQL for production)
      - DB_TYPE=postgresdb
      - DB_POSTGRESDB_HOST=postgres
      - DB_POSTGRESDB_PORT=5432
      - DB_POSTGRESDB_DATABASE=n8n
      - DB_POSTGRESDB_USER=${DB_USER}
      - DB_POSTGRESDB_PASSWORD=${DB_PASSWORD}
 
      # Encrypts credentials in the database; in queue mode every worker needs the same key
      - N8N_ENCRYPTION_KEY=${N8N_ENCRYPTION_KEY}
 
      # Public URL behind the proxy
      - N8N_HOST=n8n.yourdomain.com
      - N8N_PROTOCOL=https
      - WEBHOOK_URL=https://n8n.yourdomain.com/
      - N8N_PROXY_HOPS=1
 
      # Sign-in: n8n user management (owner account). Basic auth env vars no longer exist.
      # Environment variable access from Code nodes and expressions. The signature check
      # below reads its secret with $env, so this is false; set it explicitly either way,
      # because the n8n 2.0 breaking changes guide lists true as the new default.
      - N8N_BLOCK_ENV_ACCESS_IN_NODE=false
 
      # Execution data: keep failures, drop successful payloads, prune old data
      - EXECUTIONS_DATA_SAVE_ON_ERROR=all
      - EXECUTIONS_DATA_SAVE_ON_SUCCESS=none
      - EXECUTIONS_DATA_PRUNE=true
      - EXECUTIONS_DATA_MAX_AGE=336   # hours
 
      # Disable anonymous telemetry (also disables Ask AI in the Code node)
      - N8N_DIAGNOSTICS_ENABLED=false
 
      # Logging (N8N_LOG_FILE_LOCATION is a file path)
      - N8N_LOG_LEVEL=info
      - N8N_LOG_OUTPUT=console,file
      - N8N_LOG_FILE_LOCATION=/home/node/.n8n/logs/n8n.log
 
    volumes:
      - n8n_data:/home/node/.n8n
 
    networks:
      - n8n_network
 
    deploy:
      resources:
        limits:
          memory: 2G
          cpus: '1.0'
 
  postgres:
    image: postgres:15-alpine
    restart: always
    environment:
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}
      - POSTGRES_DB=n8n
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - n8n_network
 
networks:
  n8n_network:
    driver: bridge
 
volumes:
  n8n_data:
  postgres_data:

Nginx Reverse Proxy with Security Headers

# /etc/nginx/conf.d/n8n-ratelimit.conf
# limit_req_zone is only valid in the http context, so it lives outside the server block
limit_req_zone $binary_remote_addr zone=n8n_limit:10m rate=10r/s;
 
# /etc/nginx/sites-available/n8n
server {
    listen 443 ssl;
    http2 on;   # nginx 1.25.1+; on older versions use "listen 443 ssl http2;"
    server_name n8n.yourdomain.com;
 
    # SSL Configuration
    ssl_certificate /etc/letsencrypt/live/n8n.yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/n8n.yourdomain.com/privkey.pem;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;
 
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;
 
    # Security headers. n8n sends its own Content-Security-Policy for the editor
    # (N8N_CONTENT_SECURITY_POLICY), so don't add a second one here.
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
 
    location / {
        limit_req zone=n8n_limit burst=20 nodelay;
 
        proxy_pass http://127.0.0.1:5678;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
 
        # Timeouts for long-running workflows
        proxy_read_timeout 300s;
        proxy_connect_timeout 75s;
    }
 
    # Production webhooks
    location /webhook/ {
        limit_req zone=n8n_limit burst=50 nodelay;
 
        # Optional: IP allowlist for webhooks
        # allow 192.168.1.0/24;
        # deny all;
 
        proxy_pass http://127.0.0.1:5678;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Credential Management

Secure Credential Storage

n8n encrypts credentials at rest, but additional precautions are essential:

Credential Rotation Workflow

A daily workflow built on the n8n security audit covers the part of rotation that n8n can see:

  1. Schedule Trigger, once a day.
  2. n8n node, Resource Audit, Operation Generate. The audit endpoint requires the instance owner, so the n8n API credential must belong to the owner. The Credentials section of the report lists credentials not used in active or recently active workflows, which are the first candidates for deletion.
  3. Code node that keeps the credentials and instance sections of the report and formats a short summary.
  4. Slack node that posts the summary to your security channel.

The n8n node's Credential resource only creates, deletes and reads schemas, so it can't list credential ages. Keep rotation dates in your secrets manager or in a Data table, and compare them with today's date in a second branch of the same workflow.

OAuth Token Security

For OAuth, use the n8n OAuth2 credential type of the service (or the generic OAuth2 API credential) instead of handling tokens in Code nodes. Credentials are encrypted with N8N_ENCRYPTION_KEY before n8n saves them to the database; a token copied into a Code node, workflow static data or a Set node ends up in workflow or execution data instead, outside that encryption. Request only the scopes the workflow needs, and keep the same encryption key on every worker in queue mode.

Webhook Security

Webhook Validation

// Code node (Run Once for All Items) after a Webhook node that receives signed requests.
// For simple shared secrets, the Webhook node's Header Auth or JWT auth is enough;
// use this when the sender signs the body with HMAC-SHA256 (x-hub-signature-256 style).
//
// - Turn on the Webhook node's "Raw Body" option: the HMAC is over the exact bytes sent,
//   not over JSON.stringify of the parsed body. Set RAW_BODY_PROPERTY to the binary
//   property name you see in the Webhook node's output.
// - Self-hosted: allow crypto with NODE_FUNCTION_ALLOW_BUILTIN=crypto
//   (on the task runners if you use them). n8n Cloud provides crypto.
// - The secret is read with $env, which needs N8N_BLOCK_ENV_ACCESS_IN_NODE=false.
const crypto = require('crypto');
 
const RAW_BODY_PROPERTY = 'data';
const secret = $env.WEBHOOK_SIGNING_SECRET;
if (!secret) {
  throw new Error('WEBHOOK_SIGNING_SECRET is not set');
}
 
const items = $input.all();
 
for (let i = 0; i < items.length; i++) {
  // The Webhook node output holds the request as body, headers, params and query
  const received = String(items[i].json.headers?.['x-hub-signature-256'] ?? '');
  const rawBody = await this.helpers.getBinaryDataBuffer(i, RAW_BODY_PROPERTY);
 
  const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
 
  // Timing-safe comparison (lengths must match first)
  const a = Buffer.from(received, 'utf8');
  const b = Buffer.from(expected, 'utf8');
  if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
    throw new Error('Invalid webhook signature');
  }
}
 
return items;

Webhook Rate Limiting

Rate limiting doesn't work inside a Code node: a Map or any other in-memory object starts empty on every execution, so it never counts past one request. Limit webhook traffic in front of n8n, as in the limit_req zone of the nginx configuration above, and narrow who can call a webhook with the Webhook node's IP(s) Allowlist option (other addresses get a 403) and its authentication setting (Basic, Header or JWT auth).

Input Validation

Sanitizing Workflow Inputs

// Code node (Run Once for All Items) right after the Webhook node.
// Validate structure, types and lengths, and reject what doesn't match.
// Don't try to "clean" input with regexes; escape values where you use them
// (HTML below, query parameters in SQL nodes, escaping for Slack).
const SCHEMA = {
  email: { required: true, type: 'string', maxLength: 254, pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ },
  name: { required: true, type: 'string', maxLength: 100 },
  message: { required: false, type: 'string', maxLength: 1000 }
};
 
function validate(payload, schema) {
  if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
    return ['Body must be a JSON object'];
  }
 
  const errors = [];
 
  for (const key of Object.keys(payload)) {
    if (!(key in schema)) errors.push(`Unexpected field: ${key.slice(0, 50)}`);
  }
 
  for (const [field, rules] of Object.entries(schema)) {
    const value = payload[field];
 
    if (value === undefined || value === null) {
      if (rules.required) errors.push(`Missing required field: ${field}`);
      continue;
    }
    if (typeof value !== rules.type) {
      errors.push(`Invalid type for ${field}: expected ${rules.type}`);
      continue;
    }
    if (rules.maxLength && value.length > rules.maxLength) {
      errors.push(`${field} exceeds maximum length of ${rules.maxLength}`);
    }
    if (rules.pattern && !rules.pattern.test(value)) {
      errors.push(`${field} doesn't match required pattern`);
    }
  }
 
  return errors;
}
 
const escapeHtml = (value) => String(value ?? '')
  .replace(/&/g, '&amp;')
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;')
  .replace(/"/g, '&quot;')
  .replace(/'/g, '&#39;');
 
return $input.all().map(({ json }) => {
  // The Webhook node puts the request in body, headers, params and query
  const payload = json.body;
  const errors = validate(payload, SCHEMA);
 
  if (errors.length > 0) {
    throw new Error(`Validation failed: ${errors.join(', ')}`);
  }
 
  const clean = {
    email: payload.email.trim().toLowerCase(),
    name: payload.name.trim(),
    message: (payload.message ?? '').trim()
  };
 
  // Escaped copies for HTML emails or pages built later in the workflow
  return {
    json: {
      ...clean,
      nameHtml: escapeHtml(clean.name),
      messageHtml: escapeHtml(clean.message)
    }
  };
});

Access Control

Role-Based Workflow Access

Access control belongs to n8n itself, not to a Code node: a permission check inside a workflow can't stop a user from opening and editing that workflow. Put production workflows and their credentials in a separate project and give people project roles. A Project Admin manages the project's settings and members; a Project Editor can view, create, edit and delete workflows, credentials and executions, and run workflows, but can't manage members; a Project Viewer has read-only access and can't run workflows manually. The Editor role is available on n8n Cloud Pro and self-hosted Enterprise, and the Viewer role on Cloud Enterprise and self-hosted Enterprise, so check your plan before you design around them.

Monitoring and Auditing

Workflow Execution Logging

// Code node (Run Once for All Items) in an error workflow, right after the Error Trigger.
// Set this workflow as "Error workflow" in the settings of each production workflow.
// Builds one structured log entry per failed execution; an HTTP Request node then
// sends it to your log platform. No credential values or payloads are copied.
return $input.all().map(({ json }) => {
  const { execution = {}, workflow = {} } = json;
  // Error messages can echo input data; keep them short
  const message = String(execution.error?.message ?? 'Unknown error').slice(0, 500);
 
  return {
    json: {
      timestamp: $now.toISO(),
      level: 'error',
      event: 'n8n.workflow.failed',
      workflowId: workflow.id ?? null,
      workflowName: workflow.name ?? null,
      executionId: execution.id ?? null,
      executionUrl: execution.url ?? null,
      mode: execution.mode ?? null,
      retryOf: execution.retryOf ?? null,
      lastNodeExecuted: execution.lastNodeExecuted ?? null,
      errorMessage: message
    }
  };
});

Security Monitoring Dashboard

An hourly monitoring workflow needs only built-in nodes:

  1. Schedule Trigger, every hour.
  2. n8n node named "Failed executions": Resource Execution, Operation Get Many, Status Error.
  3. A second n8n node named "Successful executions": same operation, Status Success.
  4. Code node that counts both with $('Failed executions').all().length and $('Successful executions').all().length and computes the failure rate.
  5. If node that passes the item when the failure rate is above your threshold.
  6. Slack node that posts the counts and a link to the executions list.

Add a weekly branch with the n8n node's Audit resource: the report flags unprotected webhooks, risky and community nodes, unused credentials and an outdated instance.

Best Practices Summary

## n8n Security Checklist
 
### Deployment
- [ ] Use PostgreSQL for production
- [ ] Set a strong N8N_ENCRYPTION_KEY and back it up (same key on every worker in queue mode)
- [ ] Set up the owner account; invite users instead of sharing logins
- [ ] Use a reverse proxy with TLS and set N8N_PROXY_HOPS
- [ ] Apply security headers without overriding n8n's own CSP
- [ ] Implement rate limiting at the proxy
- [ ] Decide on N8N_BLOCK_ENV_ACCESS_IN_NODE and set it explicitly
- [ ] Disable telemetry if required (N8N_DIAGNOSTICS_ENABLED=false)
- [ ] Pin the n8n version and read the release notes before upgrading
 
### Credentials
- [ ] Keep secrets in n8n credentials, never in Code nodes or static data
- [ ] Track rotation dates outside n8n and rotate on schedule
- [ ] Remove credentials the security audit reports as unused
- [ ] Use OAuth2 credentials where the service supports them
- [ ] Never log credential values
 
### Webhooks
- [ ] Set authentication on every Webhook node (Basic, Header or JWT auth)
- [ ] Validate HMAC signatures over the raw body where the sender signs requests
- [ ] Use the IP(s) Allowlist option for sensitive webhooks
- [ ] Validate all inputs against an expected schema
- [ ] Rate limit at the proxy
 
### Access Control
- [ ] Separate production workflows into their own project
- [ ] Give project roles by need (Admin, Editor, Viewer)
- [ ] Review project members regularly
 
### Monitoring
- [ ] Set an error workflow on every production workflow
- [ ] Keep failed execution data and prune old data
- [ ] Alert on failure rate
- [ ] Run n8n audit after every upgrade

Conclusion

n8n security requires attention at multiple layers - from deployment configuration to workflow design to credential management. By implementing these practices, you can build secure automations that protect your data and systems.

Run n8n audit, or the n8n node's Audit resource, after every upgrade and before you expose a new webhook. The report covers credentials, database expressions, file system access, risky nodes and instance settings, including unprotected webhooks and an outdated version.


Official references

Related on this site: n8n Slack Integration: Workflow Automations, AI Automation: Zapier vs Make vs n8n - Which One to Choose?, n8n CRM Automation: HubSpot & Salesforce Patterns. More articles in the n8n Automation category.

Want AI agents and automations your business can actually run on?

We ship production AI in fixed two-week sprints, then secure them. Book a 30-minute call to scope yours.

Book a Call

Before you book, you can see what we build, how a sprint works, how our pricing works, what we have already built, or write to us directly.

Weekly AI Agents, Automation & Security Digest

How we build AI agents and automations with Claude Code, plus practical AI security, integrations, and platform notes, delivered weekly.

No spam. Unsubscribe anytime.