Back to blog
November 6, 2026•53 views

Build a Scheduled Automation with n8n and Claude Code: A Cron-to-Webhook Pipeline for Business Ops

n8nClaude CodeAI automationDockerwebhookscronbusiness opsautomation developer
Build a Scheduled Automation with n8n and Claude Code: A Cron-to-Webhook Pipeline for Business Ops

Most "n8n plus AI" tutorials stop at the HTTP Request node. You paste an API key, call a model, get a paragraph back, and call it automation. That works for summarising a support ticket. It falls apart the moment the job needs to read a repo, edit files, run tests, or produce a deliverable that has to be correct.

This n8n Claude Code automation tutorial goes the other way. We will build a pipeline where n8n owns the schedule and the orchestration, and Claude Code does the actual work as a headless worker on your own box. Cron fires, a webhook receives the payload, Claude Code runs against a real project directory, and the result comes back to n8n for logging and notification.

The pattern is deliberately boring: one synchronous request, one worker, one response path. That is exactly what you want from something running unattended at 3am.

Why put n8n in front of Claude Code at all

You could just run claude -p "do the thing" from crontab. That works until you want retries, alerting, a run history you can eyeball, and a place to store per-client configuration. Rebuilding all of that in bash is a waste of a week.

n8n gives you the scheduler, the queue, the credential store, and a UI your non-technical ops lead can look at without SSHing into anything. Claude Code gives you an agent that can actually touch files and run commands. Together they cover the gap between "chatbot that drafts text" and "system that ships work."

Here is the shape of what we are building:

  • Schedule Trigger in n8n fires every weekday morning.
  • HTTP Request node calls a webhook endpoint on your worker server, synchronously, with a generous timeout.
  • Worker server (a small Node/Express service) receives the job and spawns Claude Code headless.
  • Claude Code runs in a sandboxed project folder, does the work, writes output files.
  • Response flows back to n8n in the same request, which logs to Postgres and pings Slack.

Prerequisites before you touch a terminal

Be honest about what you need installed. This is not a no-code exercise.

  • A Linux VPS or your own server (a 2 vCPU / 4GB box handles light jobs; 4 vCPU / 8GB when the agent runs builds).
  • Docker and Docker Compose.
  • Node.js 20 or newer on the host if you are writing the small worker yourself. (n8n's current self-hosted images ship on Node 20+; check the n8n docs for the exact supported version of your image.)
  • An Anthropic API key with Claude Code access. Claude Code is installed via npm (@anthropic-ai/claude-code) or the native installer; see the official Claude Code docs for current install steps and CLI flags.
  • A domain or at least a stable IP for the webhook, plus a shared secret.

One thing people miss: Claude Code needs a writable working directory with a real git repo inside it. If the job is "review last night's commits," the repo has to be cloned and authenticated on the worker. Plan for that up front.

Step 1: Self-hosted n8n with Docker

I run n8n in Docker because upgrades are a single pull and I never fight with Node version drift again. Here is a compose file close to what I actually deploy.

services:
  n8n:
    image: n8nio/n8n:latest
    restart: unless-stopped
    ports:
      - "5678:5678"
    environment:
      - N8N_HOST=n8n.yourdomain.com
      - N8N_PROTOCOL=https
      - WEBHOOK_URL=https://n8n.yourdomain.com/
      - N8N_ENCRYPTION_KEY=${N8N_ENCRYPTION_KEY}
      - DB_TYPE=postgresdb
      - DB_POSTGRESDB_HOST=postgres
      - DB_POSTGRESDB_DATABASE=n8n
      - DB_POSTGRESDB_USER=n8n
      - DB_POSTGRESDB_PASSWORD=${DB_PASSWORD}
      - GENERIC_TIMEZONE=Asia/Dhaka
    volumes:
      - n8n_data:/home/node/.n8n
    depends_on:
      - postgres

  postgres:
    image: postgres:16
    restart: unless-stopped
    environment:
      - POSTGRES_DB=n8n
      - POSTGRES_USER=n8n
      - POSTGRES_PASSWORD=${DB_PASSWORD}
    volumes:
      - pg_data:/var/lib/postgresql/data

volumes:
  n8n_data:
  pg_data:

Set GENERIC_TIMEZONE to your operating timezone. A "daily" report firing at 6am local because the container defaulted to UTC is a classic and annoying failure. Small thing, worth checking.

Put n8n behind a reverse proxy with TLS. Caddy is the shortest path, nginx if you already run it. Do not expose port 5678 to the open internet without auth.

Step 2: Build the cron schedule trigger

In the n8n editor, start a new workflow and add a Schedule Trigger node. Set it to trigger at a specific hour, weekdays only. For a reporting job, 07:00 is a reasonable default.

The trigger itself is trivial. The interesting part is what you pass downstream. Give each run a stable identifier so you can trace it end to end.

{
  "run_id": "{{ $now.toFormat('yyyyLLdd-HHmmss') }}",
  "job": "weekly-client-report",
  "requested_at": "{{ $now.toISO() }}"
}

Attach that as a Set node output, or build it inline in the HTTP Request body. When something fails at 3am, run_id is the string you grep for.

Step 3: Call the webhook with an HTTP Request node

Add an HTTP Request node after the trigger. Method POST, URL pointing at your worker endpoint, body as JSON, and a header carrying your shared secret.

{
  "method": "POST",
  "url": "https://worker.yourdomain.com/jobs/run",
  "headers": {
    "Content-Type": "application/json",
    "X-Job-Secret": "{{ $credentials.jobSecret }}"
  },
  "body": {
    "run_id": "{{ $json.run_id }}",
    "job": "{{ $json.job }}",
    "prompt_file": "prompts/weekly-report.md"
  }
}

Two rules I follow without exception:

  1. The secret lives in an n8n credential (a Header Auth credential works well here), never hardcoded in the node and never read from $env. Reading environment variables from expressions in n8n requires explicitly enabling the N8N_BLOCK_ENV_ACCESS_IN_NODE=false setting, and that flag opens the door to every env var in the container, not just the one you wanted. Credentials are scoped and encrypted; use them.
  2. The worker verifies the secret before doing anything. A public webhook that spawns a shell command is a remote code execution bug waiting for a scanner to find it.

Set a generous timeout on the HTTP node. Agent runs take minutes, not milliseconds. Use a single synchronous pattern: set the node timeout to 600 seconds and design the worker to respond within it. Do not mix in a "fire and forget, post results back to a second webhook" pattern on top; half-async pipelines are where duplicate runs and lost results breed. If a job genuinely cannot finish in ten minutes, split it into smaller jobs rather than adding a callback.

Step 4: A small worker that runs Claude Code headless

This is the part that does not exist in most tutorials, so here is the whole thing. A tiny Express server that shells out to the Claude Code CLI in non-interactive mode.

import express from "express";
import { spawn } from "node:child_process";
import { readFile } from "node:fs/promises";
import path from "node:path";

const app = express();
app.use(express.json({ limit: "256kb" }));

const SECRET = process.env.JOB_SECRET;
const WORKDIR = process.env.WORKDIR || "/srv/jobs/workspace";
const PROMPTS_DIR = path.resolve(WORKDIR, "prompts");

// Naive in-memory rate limiter: max 10 requests per minute per IP.
const hits = new Map();
app.use((req, res, next) => {
  const ip = req.ip;
  const now = Date.now();
  const window = (hits.get(ip) || []).filter(t => now - t < 60_000);
  if (window.length >= 10) return res.status(429).json({ error: "rate limited" });
  window.push(now);
  hits.set(ip, window);
  next();
});

app.post("/jobs/run", async (req, res) => {
  if (req.headers["x-job-secret"] !== SECRET) {
    return res.status(401).json({ error: "unauthorized" });
  }

  const { run_id, prompt_file } = req.body;

  // Resolve the prompt file inside WORKDIR and reject anything that escapes it.
  const resolved = path.resolve(WORKDIR, prompt_file);
  if (!resolved.startsWith(PROMPTS_DIR + path.sep)) {
    return res.status(400).json({ error: "invalid prompt_file" });
  }
  const prompt = await readFile(resolved, "utf8");

  const child = spawn("claude", [
    "-p", prompt,
    "--output-format", "json",
    "--allowedTools", "Read,Write,Edit,Bash(git status),Bash(git diff),Bash(git log)"
  ], {
    cwd: WORKDIR,
    env: { ...process.env, ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY }
  });

  let out = "";
  let err = "";
  child.stdout.on("data", d => (out += d));
  child.stderr.on("data", d => (err += d));

  child.on("close", code => {
    if (code !== 0) {
      return res.status(500).json({ run_id, ok: false, stderr: err.slice(-2000) });
    }
    res.json({ run_id, ok: true, result: out.slice(-8000) });
  });
});

app.listen(8080, () => console.log("worker up on :8080"));

A few deliberate choices here.

Validate the prompt file path. The prompt_file value comes over the wire, so treat it as untrusted. path.resolve plus a startsWith check against your prompts directory stops ../../etc/passwd-style inputs from being read. If you prefer a stricter model, keep an allowlist of known job names and map each to a fixed filename.

Limit the request body and rate limit the endpoint. express.json({ limit: "256kb" }) keeps a malformed or hostile request from buffering megabytes in memory, and the tiny limiter above caps how often a single IP can hit the endpoint. If the worker only ever talks to your n8n instance, an IP allowlist at the reverse proxy or firewall is even simpler and stronger.

The --allowedTools flag is not decoration. Restricting the agent to read, write, edit, and a handful of specific git subcommands means a prompt injection buried in a document cannot ask it to rm -rf, push to a remote, or curl an external URL. Do not grant bare Bash; enumerate the subcommands you actually need. If your job needs network access, add it explicitly and know why. (Flag names and accepted tool identifiers can change between CLI releases; confirm against the Claude Code CLI reference before you deploy.)

The --output-format json gives you a parseable result instead of a wall of prose. That matters when n8n needs to branch on success or failure.

The cwd points at a dedicated workspace, not your home directory. Claude Code writes files relative to where it runs. Give it a room to make a mess in.

Run the worker as non-root

The worker spawns an agent that writes files and runs git. Do not run it as root. In the compose file, pin a non-root user and make sure the workspace volume is owned by that user:

services:
  worker:
    build: .
    user: "1000:1000"
    restart: unless-stopped
    environment:
      - JOB_SECRET=${JOB_SECRET}
      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
      - WORKDIR=/srv/jobs/workspace
    volumes:
      - ./workspace:/srv/jobs/workspace

Create the host directory with mkdir -p ./workspace && sudo chown -R 1000:1000 ./workspace so the container user can write to it. If you run the worker under systemd instead of Docker, set User= and Group= in the unit file for the same reason.

Prompt files beat inline prompts

Keep prompts in version-controlled markdown files, one per job. prompts/weekly-report.md might say: read the CSVs in data/, produce reports/summary.md with a table of the top five accounts by revenue change, and write a short paragraph explaining anomalies.

When the output is wrong, edit the prompt file and re-run. No redeploying the worker, no editing nodes in the UI at midnight. This is the single biggest quality-of-life improvement in the whole setup.

Step 5: Close the loop back in n8n

The worker's JSON response lands in the HTTP Request node output. From there:

  • Add an IF node on {{ $json.ok }}.
  • On true, write the result to Postgres with a Postgres node, keyed on run_id.
  • On false, send a Slack message with the stderr tail so you can debug without logging into the server.
  • Either way, log a row with start time, finish time, and status.

That run log becomes your audit trail. When a client asks why last Tuesday's report was missing, you have an answer in ten seconds instead of a forensic expedition.

Claude API as an HTTP node vs Claude Code CLI

This is the decision people get stuck on, so here is the honest comparison.

Factor Claude API via HTTP node Claude Code CLI worker
Setup effort Minutes An afternoon
Can read and edit files No Yes
Can run commands and tests No Yes, within allowed tools
Cost profile Pay per token, predictable Pay per token plus agent overhead (more turns)
Best for Drafting, classification, summarising Repo work, report generation, multi-step builds
Security surface Small Larger, needs sandboxing and tool restrictions
Debugging Straightforward Needs logs and a workspace you can inspect

My rule: if the job is "turn this text into that text," use the API node. If the job is "make this folder contain the correct files," use Claude Code. Most business ops jobs that sound like the first are actually the second once you are honest about what "done" means.

Hosting notes for readers outside the US

Latency matters less than you think here, because these jobs run on a schedule and nobody is watching. What matters is where your data sits and whether the box is reliable.

  • Bangladesh: a local VPS is fine for n8n, but run the Claude Code worker in a region close to Anthropic's endpoints. Singapore and Mumbai regions are sensible choices. Keep backups off the same provider.
  • Australia and New Zealand: Sydney region for both containers keeps round trips short. Watch out for providers that bill egress aggressively.
  • USA and Canada: pick the region closest to your users for n8n, and do not overthink the worker location.

Whatever you pick, put the workspace on its own volume. Rebuilding a container should never wipe the folder the agent has been writing to.

Troubleshooting the things that actually break

This table covers the failures that come up most often.

Symptom Likely cause Fix
Worker returns 401 Secret mismatch between n8n credential and server env Rotate both, redeploy worker
Worker returns 400 on prompt_file Path escaped the prompts directory Pass a bare filename, not a path
claude: command not found CLI not on PATH inside container or service Install globally or use absolute path in spawn
Job hangs past timeout Agent waiting on interactive prompt Ensure -p non-interactive flag is set
Empty or malformed output Output truncated by slice, or agent errored Log full stdout to a file, inspect --output-format json
Files written to wrong place cwd misconfigured Pin absolute WORKDIR, check permissions
Permission denied writing files Worker running as wrong user Set user: "1000:1000" and chown the workspace
Works manually, fails on cron Environment variables not loaded for the service Use systemd EnvironmentFile or compose env_file
Repeated duplicate runs n8n retry plus slow worker Make jobs idempotent, key writes on run_id

The duplicate-run row has cost more sleep than any other. If your worker takes four minutes and n8n's timeout is two, you get a retry, two agents editing the same files, and a corrupted output. Set the timeout higher than your worst-case run (600 seconds is a good default) and make writes idempotent.

Cost and security, briefly but seriously

Agent runs burn more tokens than a single API call because the model reads files, plans, and iterates. A report job that touches ten files might use several times the tokens of a one-shot summary. Budget for that, and cap it: the Claude Code CLI exposes budget and turn controls (for example --max-turns and a max-budget flag), and you should set them. Check the CLI reference for the exact flags in your version.

For a rough sizing: a one-shot API summary of a few thousand tokens costs a fraction of a cent at current Sonnet pricing, while a multi-turn agent run that reads ten files and iterates a few times might land in the low cents per run. Run it daily for a month and you are talking about a dollar or two versus pennies. Anthropic publishes current per-token rates on its pricing page; plug your own token counts in before you promise a client a number.

On security, three non-negotiables.

  1. The webhook requires a secret and rejects everything else.
  2. Claude Code runs with an explicit allowlist of tools, never full shell.
  3. The workspace is a container or a locked-down non-root user, not root on the host.

A "quick internal automation" that becomes a public endpoint with no auth is a common and avoidable mistake. Do not be that story.

When to just hire someone for this

This pipeline is buildable by a competent developer in a day or two. If you are a founder reading this and thinking "I do not have a day or two," that is a real answer, not a cop-out. The tricky parts are not the happy path, they are the retries, the sandboxing, the logging, and the prompt files that keep output correct six months later.

If you want this built properly, or you have a pile of manual ops work you suspect is automatable, that is the kind of thing I do. I lead web engineering and AI automation at AKIJ iBOS and build these systems for clients across Bangladesh, the US, and Australia. You can reach out through the contact page and we can talk about what is worth automating first.

Frequently asked questions

Do I need to self-host n8n to use Claude Code with it?

No, but self-hosting is the simpler setup. n8n Cloud works fine for the scheduling and webhook side, but Claude Code needs to run somewhere with filesystem access and a shell, which means your own server or container regardless. Self-hosting n8n keeps everything in one place and avoids sending job payloads through a third party you do not control.

Is running Claude Code headless from a webhook safe?

It is safe if you treat it like any other privileged process. Require a shared secret on the endpoint, restrict the agent to an explicit tool allowlist (specific git subcommands, not bare Bash), run it as a non-root user in a dedicated workspace, validate any file paths that come in over the wire, and keep the workspace isolated in a container. Skip any of those and you have built a remote code execution endpoint with extra steps.

How is this different from just calling the Claude API in an HTTP Request node?

The API node turns text into text. Claude Code can read files, edit them, run commands, and produce actual deliverables in a folder. If your job is classification or drafting, use the API node. If the job is "make this directory contain the correct output," you want the CLI worker.

Can I use this for multiple clients from one n8n instance?

Yes, and that is where it earns its keep. Give each client a prompt file and a workspace folder, pass a client identifier through the webhook, and let the worker pick the right directory. Keep credentials in n8n's credential store per client and log every run against its run_id so billing and debugging stay clean.

Share this post

Native Web Share is available on mobile, so that share sheet includes Instagram and any other app you have installed.

Let's Connect

Get In Touch

Let's build something premium together.

Contact info

Follow me
Chat on WhatsApp