Skip to content
TheAgent Ecosystem
Automation

n8n Code Node in AI Workflows: When the Built-In Nodes Are Not Enough

Five places where a Code node belongs in an AI workflow, with working JavaScript snippets for each.

Muhammad Qasim HammadAI-assisted8 min read1,519 words

AI-drafted, reviewed by Muhammad Qasim Hammad on July 21, 2026. See our AI disclosure.

Code Node + AI: When Built-In Nodes Hit a Wall
Table of contents
  1. Where does a Code node fit in an AI workflow?
  2. How do you reshape data before the model sees it?
  3. How do you post-process the model's output with code?
  4. How do you build dynamic prompts from variable-length data?
  5. When should you reach for a Code node versus a built-in node?

The built-in AI nodes in n8n cover the common cases: a prompt goes in, a response comes out, and a parser turns it into JSON. But the moment you need to batch 50 rows through a model, reshape an API response before the agent sees it, or build a custom scoring function the model cannot handle, the visual nodes hit a wall. The n8n Code node lets you drop into JavaScript wherever the built-in nodes cannot reach, and in AI workflows that gap shows up more often than you expect.

This guide covers the five places where a Code node belongs in an AI workflow, with working snippets for each one. If you have built a few n8n AI workflows and hit a moment where you wished you could "just write a function," this is the reference.

Where does a Code node fit in an AI workflow?#

A Code node belongs anywhere you need logic the visual nodes cannot express: reshaping data before the model sees it, post-processing the model's output into a format downstream nodes expect, building dynamic prompts from variable-length input, scoring or filtering results with rules too specific for an IF node, or calling an API that has no native n8n integration.

The key distinction is deterministic versus generative. The AI Agent and LLM Chain nodes are for generative work: classification, summarization, drafting. The Code node is for deterministic work: string manipulation, math, filtering, reformatting, API calls with exact parameters. Mixing the two is where AI workflows get reliable, because you keep the AI on the creative side and the Code node on the mechanical side.

A common mistake is trying to make the model do what a function should. Asking an LLM to calculate a percentage, reformat a date, or deduplicate a list wastes tokens and introduces randomness. A 3-line Code node does those jobs faster, cheaper, and without the variance.

TaskRight toolWhy
Classify a support ticketAI Agent or LLM ChainRequires language understanding
Reformat a date from US to ISOCode nodeDeterministic string operation
Score a lead from 1-10 on 3 criteriaCode nodeRule-based math, no model needed
Summarize a 2,000-word documentLLM ChainRequires compression and judgment
Deduplicate rows by emailCode nodeExact match logic
Draft a personalized replyAI AgentRequires tone and context
Comparison of when to use a Code node versus an AI node in n8n workflowsDeterministic tasks belong in a Code node; generative tasks belong in an AI node. Mixing the two is how AI workflows get reliable.

How do you reshape data before the model sees it?#

Write a Code node between your data source and the AI node to clean, merge, or truncate the input so the model gets exactly what it needs. Strip HTML tags, merge fields into a single prompt string, and cap the character count so you stay inside the context window and stop paying for tokens the model ignores anyway.

Here is a working pattern. Your data source returns an item with body (HTML), subject, and sender fields. The AI node needs a single clean text prompt:

javascript
const items = $input.all();
return items.map(item => {
  const body = item.json.body
    .replace(/<[^>]+>/g, '')
    .replace(/\s+/g, ' ')
    .trim()
    .slice(0, 4000);
  return {
    json: {
      prompt: `From: ${item.json.sender}\nSubject: ${item.json.subject}\n\n${body}`
    }
  };
});

The strip-and-truncate pattern saves real money at scale. A 10,000-character HTML email with headers, footers, and styling carries roughly 6,000 characters of noise. Stripping that before the model sees it cuts token cost by 40-60% per item without losing any information the model needs. Across 100 items a day, that adds up.

Three-step pattern for cleaning and reshaping data in a Code node before sending it to an AI nodeStrip the noise, merge the fields, and cap the length so the model gets clean input and you pay for fewer tokens.

How do you post-process the model's output with code?#

Place a Code node after the AI node to validate, transform, or enrich the model's response before downstream nodes consume it. Parse a JSON string the model returned inside markdown fences, normalize scores to a consistent scale, extract specific fields from free text, or merge the model's output with the original input for a complete record.

The most common post-processing need is extracting JSON from the model's response. Even with a Structured Output Parser, models sometimes wrap the JSON in markdown fences or add commentary. A Code node handles that reliably:

javascript
const items = $input.all();
return items.map(item => {
  let text = item.json.text || '';
  const match = text.match(/```(?:json)?\s*([\s\S]*?)```/);
  if (match) text = match[1];
  const parsed = JSON.parse(text.trim());
  return { json: { ...item.json, parsed } };
});

Another pattern is enriching the model's output with data it did not have. The model classifies a ticket; the Code node looks up the SLA for that category and attaches a deadline. The model scores a lead; the Code node converts the score into a routing label. Keep the model on the creative side and the Code node on the mechanical side.

Flow showing a Code node for pre-processing, an AI node for generation, and a Code node for post-processingPre-process, generate, post-process. The deterministic layers contain the nondeterministic step so each part is testable on its own.

How do you build dynamic prompts from variable-length data?#

Use a Code node to assemble a prompt from data that varies in shape or length, like a list of items or a conversation history that needs trimming. The Code node builds the prompt string with logic the Set or Edit Fields nodes cannot express, then passes it to the AI node as a single input.

A practical case: you want the model to compare 3 to 8 products from a database query. The prompt needs a numbered list of products with their specs, but the count varies per run. A Code node builds it:

javascript
const products = $input.all();
const list = products.map((p, i) =>
  `${i + 1}. ${p.json.name}, $${p.json.price}/mo, ${p.json.features}`
).join('\n');
return [{
  json: {
    prompt: `Compare these products and recommend the best fit:\n\n${list}`
  }
}];

The same pattern works for trimming conversation memory to fit a context window. If your memory buffer grows past 8,000 tokens, a Code node can drop the oldest messages until it fits, or summarize the early turns into a single paragraph before passing the trimmed history to the agent.

Checklist of best practices for using Code nodes in n8n AI workflowsFollow these rules to keep Code nodes maintainable and debuggable as the workflow grows.

When should you reach for a Code node versus a built-in node?#

Reach for the Code node when the task is deterministic and the visual nodes would need more effort than writing the function. If the task needs language understanding or judgment, use an AI node. If it needs exact string manipulation, math, or an API call without a native n8n node, reach for code.

A good rule of thumb: if you catch yourself writing a prompt that says "reformat this date" or "calculate the percentage," stop and use a Code node instead. The model will get it right most of the time, but a function gets it right every time, runs in milliseconds, and costs zero tokens.

The pattern scales cleanly. Pre-process with a Code node, generate with an AI node, post-process with another Code node. That three-node sandwich is the backbone of reliable AI workflows because it keeps the nondeterministic step contained between two deterministic ones, and you can test and debug each layer independently.

Decision flowchart for whether to use a Code node or an AI node for a given task in an n8n workflowIf the task needs language understanding, use an AI node. If it needs exact logic, use a Code node. Ask whether the answer should be identical every run.

Frequently asked questions

When should I use a Code node instead of an AI node in n8n?
Use a Code node when the task is deterministic: string manipulation, math, date formatting, deduplication, or filtering. Use an AI node when the task requires language understanding, classification, summarization, or judgment. If you catch yourself writing a prompt that says 'reformat this date,' use a Code node instead.
Can the n8n Code node call external APIs?
Yes. The Code node has access to fetch for making HTTP requests. You can call any external API, parse the response, and return transformed items to the next node. This is useful for services that do not have a native n8n integration.
How do I parse JSON from an LLM response in a Code node?
Use a regex to extract the JSON from markdown fences if the model wraps its output that way, then parse it with JSON.parse inside a try-catch. Return a fallback object with an error flag on parse failure so error handling downstream can route bad responses instead of crashing the run.
Does the Code node support Python in n8n?
Recent n8n versions support Python in the Code node alongside JavaScript. Both languages have full access to the incoming items and can return transformed items. Choose whichever language you are more comfortable with for the specific transformation.
How many lines of code should an n8n Code node have?
Keep each Code node under 50 lines. If the logic grows larger, move it into a sub-workflow or split it across multiple Code nodes with clear responsibilities. Short Code nodes are easier to debug in the n8n execution log and easier for teammates to understand.

Sources

Primary references and vendor documentation used while drafting and reviewing this article.

  1. n8n Code node documentation
  2. n8n AI Agent (Tools Agent) documentation
  3. n8n Basic LLM Chain documentation
  4. n8n Structured Output Parser documentation
  5. n8n expressions and data structure reference

Written by

Muhammad Qasim Hammad
Muhammad Qasim Hammad
AI agents & automationFounder · Cart Gaze LLCPMP-certified PM

Muhammad Qasim Hammad is an AI agent and automation expert and the founder of Cart Gaze LLC (cartgaze.com). He builds product for the love of it: when an idea lands, a working prototype is usually running within hours, built with the same AI agents and automations he sells. He puts his own output at roughly 20× what it was before agents, and the Agentic OS behind this site is the working proof, documented in public with the tools he actually ran and what they really cost.

AI & Automation Services

Want a pipeline like this running in your business?

I'm Qasim — I design and ship AI agents and n8n automations for solo operators and small teams. Tell me what's eating your team's week, and I'll scope a fix.

Related reading