n8n loops official
Use when working with multi-item data, batches, paginated APIs, rate-limited APIs, fan-out across multiple branches, anything that needs to "do this for each", or any time the user mentions looping, iterating, batching, paging, parallelism, or "loop over items". Triggers on "loop", "iterate", "for each", "batch", "page through", "paginate", "rate limit", "process all", "fan-out", "parallel branches", "concurrency", or any node that should run once vs once-per-item.
By- name:
- n8n-loops-official
- description:
- Use when working with multi-item data, batches, paginated APIs, rate-limited APIs, fan-out across multiple branches, anything that needs to "do this for each", or any time the user mentions looping, iterating, batching, paging, parallelism, or "loop over items". Triggers on "loop", "iterate", "for each", "batch", "page through", "paginate", "rate limit", "process all", "fan-out", "parallel branches", "concurrency", or any node that should run once vs once-per-item.
n8n Loops
Three meanings of "loop" map to three mechanisms:
- "Run this node for every item." Default. Most nodes loop automatically, so do nothing.
- "Run this node once with all items, not once per item." The
executeOncesetting (single boolean). - "Process items in explicit batches with control flow between iterations." The
Loop Over Itemsnode (formerlySplit In Batches).
For paginated APIs, the HTTP Request node has built-in pagination. Almost always preferable to a hand-built page-counting loop.
The model: items are an array
Data flows between nodes as an array of items, each { json: {...}, binary?: {...} }. 50 items = 50-entry array.
Default: a node runs once per item. An HTTP Request with 50 input items fires 50 requests and outputs 50 result items. This is the implicit loop most workflows rely on.
The input array is the loop. Control iteration by controlling the array.
Non-negotiable
executeOnce: true whenever a node should fire once-per-run, not once-per-item. Includes any expression aggregating across the dataset via $input.all() / $('Node').all() plus .map() / .filter() / .reduce() (without it, the aggregate computes N times for N upstream items, often producing N duplicates downstream). Also includes single notifications, aggregate writes, summary messages.
Counter-case: .all() combined with another node's .item (a per-item lookup, e.g., $('Get Tags').all().filter(tag => $('Search Posts').item.json.tag_ids.includes(tag.json.id))) is real per-item work and should keep executeOnce off. See the n8n-expressions-official skill's executeOnce section for the full distinction.
Strong defaults
- Don't build a loop when default iteration suffices. Most nodes (HTTP Request, native service nodes, Set, IF/Switch) run once per input item automatically: N items in, N runs. To make N HTTP calls or create N records, just connect the source to the node. Don't reach for
Loop Over Itemsunless you need per-iteration control. (Note:Execute Workflowis the exception. It defaults to a single all-items batch. Seen8n-subworkflows-officialformode: 'each'.) - For paginated APIs, use HTTP Request's built-in pagination. Don't reinvent with
Loop Over Items+ manual$pageCountunless the API is genuinely odd. Seereferences/HTTP_PAGINATION.md. Loop Over Itemsis for explicit batching or per-iteration control (rate limiting, per-batch error recovery, stateful chunks, polling). Seereferences/LOOP_OVER_ITEMS.md.- Per-item iteration is sequential, not parallel. Each item completes before the next starts, even on parallel looking branches. For a real concurrency pattern, see
n8n-subworkflows-official.
Decision tree: which mechanism do I need?
Need to do something for each item?
├── Default per-item iteration is enough
│ └── Just connect the node. Done.
│
├── The node should run once total, not once per item?
│ └── Set executeOnce: true on the node
│
├── Paginated API (multiple HTTP calls to fetch all pages)?
│ └── Use HTTP Request's Pagination option (see references/HTTP_PAGINATION.md)
│
├── Need explicit batching (rate limit, chunk size, per-batch error handling)?
│ └── Use Loop Over Items node (see references/LOOP_OVER_ITEMS.md)
│
└── Need to recurse / repeat with state until a condition is met?
└── Loop Over Items with Reset, OR a sub-workflow that calls itself.
Both are advanced patterns; see references/LOOP_OVER_ITEMS.md.
executeOnce: the single-fire setting
Every node's Settings tab has an Execute Once toggle. When on, the node runs once using only the first input item. In SDK code, set executeOnce: true as shown; on an existing workflow, apply it via update_workflow setNodeSettings (n8n 2.24.0+).
{
name: 'Aggregate Slack',
type: 'n8n-nodes-base.slack',
parameters: { /* ... */ },
executeOnce: true,
}
When to use it:
- Notifications and aggregate writes. A "summary message" shouldn't fire 100 times because 100 items came in.
- Counters, totals, reports. Anything computing
$input.all().lengthetc. should run once. - Expressions aggregating across the full array via
$input.all()/$('Node').all(). Otherwise the aggregate runs per upstream item. (Per-item lookups using.all()filtered by another node's.itemare the counter-case, seen8n-expressions-official.)
When NOT to use it:
- Per-item operations. One notification per item is the default and usually correct.
- HTTP requests fanning out per item. You want one call per item.
Most common mistake: forgetting executeOnce on an aggregate node, then seeing the same message fire 50 times after a fan-out.
When the implicit loop bites you
Default per-item iteration is great until it isn't. Common surprises:
A "single" config node fires per item
A Set node after a fan-out runs once per item, producing N copies of the same constants. Usually fine, but expensive expressions (long JSON.stringify, Luxon parse) run N times. Move the Set above the fan-out, or set executeOnce: true.
An aggregate Code node runs N times
A Code node reading $input.all() to compute a sum runs once per upstream item without executeOnce: true, producing N identical items. Set executeOnce: true.
A respond-to-webhook fires twice
Most painful version. Respond-to-Webhook fires per input item, and two branches converging without a merge fire it twice: first response wins, the rest log errors. Merge first, or ensure only one branch reaches the responder. See n8n-node-configuration-official references/MERGE_NODE.md.
An LLM call fires N times when you wanted one summary
Same shape as the aggregate Code node. An LLM node with $input.all() in its prompt makes N identical calls, costs N tokens, returns N identical answers without executeOnce: true.
When to reach for Loop Over Items
Default iteration handles most cases. Use Loop Over Items for:
- Rate limiting. "Process 10 at a time, 1s wait between batches."
- Batched API calls with array bodies. "Send 50-item chunks to /bulk."
- Per-batch error handling. "If a batch fails, log and continue."
- Stateful iteration. "Each iteration depends on the previous output."
- Polling a long-running job. "Start, check status every 30s until done or capped." Uses
reset: trueplus a$runIndexceiling. - Per-item multi-branch with aggregation. "For each input, run transforms in parallel, merge, then aggregate." The done output (index 0) carries the result.
For wiring details, the output-index gotcha (output 0 = done, output 1 = loop), and worked examples, see references/LOOP_OVER_ITEMS.md.
When NOT to reach for Loop Over Items
The most common rationalization: "I need to wait for all items to finish before the next step, so I'll add Loop Over Items and use the done output." You don't need Loop Over Items for that. Default per-item iteration already waits: each item flows through the full downstream chain before the next item starts, and the post-loop node never fires "early."
The cure for that mistake is almost always: delete the Loop Over Items node, change nothing else, ship. That is Scenario 1 below, and it covers the majority of cases.
The four scenarios are independent. Read them as separate decisions, not as alternatives that all "replace" Loop Over Items. Most builds hit Scenario 1 and are done. Scenarios 2 and 3 only enter the picture when their specific goal applies. Scenario 4 is the narrow case where Loop Over Items actually earns its place.
Scenario 1: default per-item iteration (the default, most common)
Source emits N items, per-item processor runs N times, downstream chain follows. No Loop Over Items, no executeOnce, no Aggregate. Just connect the nodes.
[Source: 20 items]
→ [Per-item processor] # default iter, runs 20 times
→ [Next step] # runs after each item, in order
If a Loop Over Items + done was added here "to wait for all items" or "to make the next node run for each item," delete the Loop Over Items node and wire source straight to processor. Do not replace it with anything. Default iteration already does the job. The exception is Execute Workflow (sub-workflow): it defaults to a single all-items batch, so per-item invocation needs mode: 'each' on that node, not a Loop. See n8n-subworkflows-official.
Scenario 2: a downstream node should fire once total (executeOnce: true)
Independent of Scenario 1. Triggered only when there is a SPECIFIC downstream node whose job is once-per-run, not once-per-item: one digest email after 20 papers process, one summary write after the loop, one final Slack notification.
Set executeOnce: true on that node. The node receives all upstream items but runs once. This is a per-node setting, not a Loop replacement: the per-item processor in Scenario 1 still runs N times, and only this one downstream node collapses.
Scenario 3: a node needs the items as a single array (Aggregate)
Independent of Scenario 1. Triggered only when a downstream node's input contract is a list, not per-item invocations (e.g., a node taking a JSON array body, an LLM prompt that needs the whole list).
Use the Aggregate node to collapse the per-item stream into one item containing the array. Again, not a Loop replacement.
Scenario 4: genuine batching (the only time Loop Over Items earns its place)
Rate limiting (process N at a time with a Wait between batches), chunked bulk API calls (POST 50-item arrays to /bulk), per-batch error handling, polling a long-running job with reset: true and a $runIndex ceiling, stateful iteration where each batch depends on the previous output.
"Wait for items to finish" does not qualify. Default iteration already does that.
Quick disambiguation
If your only reason for the Loop is "wait for items / run for each item," you are in Scenario 1. Delete the Loop. Do not add executeOnce or Aggregate as a substitute. They solve different problems and are only added when their own scenario applies.
When to reach for HTTP pagination
Three common page shapes:
- Next-URL in response. Each response includes a
nextlink. - Page number/cursor parameter. Bump
?page=Nor?cursor=...each call. - Stop on empty page or specific status.
HTTP Request handles all natively via its Pagination option: set the mode, give a next-page expression, and the node loops internally, returning a single output array of all pages' items.
Don't reinvent with Loop Over Items + manual $pageCount unless the API does something the built-in modes can't express.
See references/HTTP_PAGINATION.md.
Sub-workflow recursion
For genuinely recursive work (tree walking, retry-with-backoff, "process this and its children"), a self-calling sub-workflow is cleaner than Loop Over Items with Reset. Input parameters carry recursion state.
Sub-workflow: Walk Tree
inputs: { node_id, depth }
body: process node, look up children, for each child call self with depth+1
Watch recursion depth. n8n has nested-execution limits. For deep recursion, a queue + flat loop beats true recursion.
Reference files
| File | Read when |
|---|---|
references/LOOP_OVER_ITEMS.md |
Configuring the Loop Over Items node, batching, rate limiting, stateful iteration |
references/HTTP_PAGINATION.md |
Calling a paginated API, configuring HTTP Request pagination modes |
Anti-patterns
| Anti-pattern | What goes wrong | Fix |
|---|---|---|
Adding Loop Over Items to "make it loop" when default iteration already does |
Workflow harder to read for no benefit, and loop output vs done output gets miswired | Just connect the node directly and let default iteration handle it |
Aggregate Code node without executeOnce |
Same aggregate computed N times, output has N identical items | Set executeOnce: true |
Manual pagination loop with Loop Over Items + $pageCount |
Reinvents what HTTP Request does natively, with brittle stop conditions | Use HTTP Request's Pagination option |
| Sending one Slack message per item when you wanted a summary | Slack channel floods, rate limits hit, embarrassment | executeOnce: true on the Slack node, build the summary upstream |
Two branches both reach Respond to Webhook |
Responds twice, downstream callers see errors | Merge before the responder, or ensure only one branch reaches it |
Loop Over Items with Reset and no clear termination |
Infinite loop, n8n eats memory until the execution is killed | Always have a clear termination condition. Prefer HTTP pagination for paged APIs |
Nesting one Loop Over Items inside another in the same workflow |
Broken at runtime, validation passes | Move the inner loop into a sub-workflow called per outer iteration. See n8n-subworkflows-official mode: 'each' |
Open this reference as its own page
HTTP Request pagination
The HTTP Request node has built-in pagination. Most reinvent it with Loop Over Items and manual $pageCount. The built-in version is simpler, more robust, and yields a single output array of all pages' items.
Use it for any paginated API.
Where to find it
HTTP Request config: Add Option → Pagination.
In SDK terms, under options.pagination:
{
type: 'n8n-nodes-base.httpRequest',
parameters: {
method: 'GET',
url: 'https://api.example.com/items',
options: {
pagination: {
pagination: {
paginationMode: 'updateAParameterInEachRequest',
// ...mode-specific config
},
},
},
},
}
The three pagination modes
Mode 1: Update a Parameter in Each Request
For APIs using a page number, offset, or cursor as a query/body/header parameter.
{
paginationMode: 'updateAParameterInEachRequest',
parameters: {
parameters: [
{
type: 'qs', // 'qs' (query string) | 'body' | 'headers'.
// UI label is "Query" but the internal value is 'qs'.
name: 'page',
value: '={{ $pageCount + 1 }}',
},
],
},
}
Key points:
$pageCountis 0-indexed. Most APIs page from 1, so use$pageCount + 1. If yours pages from 0, use$pageCountdirectly.- Paginate multiple parameters together if needed (e.g.,
offset+limit). - For cursor-based APIs, use
$response.body.<cursor_field>as the value.
Mode 2: Response Contains Next URL
For responses with a next link (Link header, _links.next.href, nextPageUrl, etc.).
{
paginationMode: 'responseContainsNextURL',
nextURL: '={{ $response.body.next_page_url }}',
}
Point nextURL at the response field via expression. The node calls that URL next.
Termination still goes through paginationCompleteWhen (default responseIsEmpty). For APIs whose final page has an empty body, the default works without extra config. For APIs that always return a populated body but drop the next field on the last page, set paginationCompleteWhen: 'other' with a completeExpression checking for the absent field. If nextURL evaluates to an empty string, the node throws an "invalid URL" error rather than stopping cleanly.
Mode 3: Off
Default. One request, one response.
Page size
Page size is a normal query parameter, not inside the pagination block. Add via Send Query Parameters:
queryParameters: {
parameters: [
{ name: 'limit', value: '100' },
],
}
The pagination block bumps the page param while limit stays constant.
Termination conditions
Pagination Complete When option:
responseIsEmpty(default): stops on empty response body.receiveSpecificStatusCodes: stops on listed status codes (e.g.,[404]).other: provide acompleteExpressionthat's true when done.
Custom completion example:
{
paginationMode: 'updateAParameterInEachRequest',
completeExpression: '={{ $response.body.items.length === 0 }}',
// ...
}
Next-URL mode terminates naturally when the expression returns falsy. No extra config needed in most cases.
Limits and safety
limitPagesFetched(boolean) +maxRequests(number): hard cap. Set this in production. A misbehaving API (returning the samenextURL) without a cap = infinite requests.requestInterval(ms): delay between requests. Use for rate-limited APIs (e.g.,100= 10/s,500= 2/s).
Reasonable defaults for unknown APIs:
{
paginationMode: 'updateAParameterInEachRequest',
parameters: { /* ... */ },
limitPagesFetched: true,
maxRequests: 50, // hard ceiling
requestInterval: 200, // 5 req/s
}
50 pages × 100 items = 5,000 items, enough for most workflows. Adjust as needed.
Built-in expression variables
$pageCount: pages already fetched (0 on first request).$request: the request that just went out (URL, headers, body, query).$response: previous call's response.$response.body,$response.headers,$response.statusCode.
$response is the workhorse for non-trivial pagination expressions.
Output shape
The HTTP Request node with pagination returns a single output array of all pages' items, concatenated. No flatten/merge needed.
If items are wrapped in an envelope ({ data: [...], meta: {...} }), each page's response is one output item. For a flat list, flatten with a downstream Split Out node or an Edit Fields expression that pulls $json.data. (V3 of the HTTP Request node has no built-in splitIntoItems option, that was V1/V2 only.)
Response Format (relevant when paginating non-JSON content)
Separate from the Pagination block, the Response > Response Format option controls how the body is parsed:
options: {
response: {
response: {
responseFormat: 'autodetect', // 'autodetect' | 'json' | 'text' | 'file'
outputPropertyName: 'data', // required when responseFormat is 'text' or 'file'
},
},
}
'autodetect'(default): node infers fromContent-Type.'json': forces JSON parse.'text': returns the raw body as a string in the field named byoutputPropertyName(default'data'). Useful when paginating an HTML site for scraping, or any non-JSON paginated source.'file': writes the body to binary, typically for downloading paged file ranges.
Pagination expressions still see $response.body either way, so a text-formatted response works with regex-based nextURL extraction (e.g., parsing a Link header or scraping a "next" anchor from HTML).
Examples
Github-style: page parameter, stops on empty
{
method: 'GET',
url: 'https://api.github.com/repos/{owner}/{repo}/issues',
sendQuery: true,
queryParameters: {
parameters: [
{ name: 'per_page', value: '100' },
],
},
options: {
pagination: {
pagination: {
paginationMode: 'updateAParameterInEachRequest',
parameters: {
parameters: [
{ type: 'qs', name: 'page', value: '={{ $pageCount + 1 }}' },
],
},
paginationCompleteWhen: 'responseIsEmpty',
limitPagesFetched: true,
maxRequests: 100,
},
},
},
}
Stripe-style: cursor in response, fetched via starting_after
{
method: 'GET',
url: 'https://api.stripe.com/v1/customers',
sendQuery: true,
queryParameters: {
parameters: [{ name: 'limit', value: '100' }],
},
options: {
pagination: {
pagination: {
paginationMode: 'updateAParameterInEachRequest',
parameters: {
parameters: [
{
type: 'qs',
name: 'starting_after',
value: '={{ $response.body.data[$response.body.data.length - 1].id }}',
},
],
},
paginationCompleteWhen: 'other',
completeExpression: '={{ !$response.body.has_more }}',
},
},
},
}
Reads the last item's id from the previous response as starting_after. Stops when has_more is false.
Link header (RFC 5988)
{
options: {
pagination: {
pagination: {
paginationMode: 'responseContainsNextURL',
nextURL: `={{
(() => {
const link = $response.headers.link ?? '';
const match = link.match(/<([^>]+)>;\\s*rel="next"/);
return match ? match[1] : null;
})()
}}`,
},
},
},
}
Returns null when there's no next rel, and pagination stops.
Common mistakes
Hand-rolling pagination with Loop Over Items and $pageCount
If the API has a page parameter or next URL, the built-in is simpler and less error-prone. Use Loop Over Items only when the API does something genuinely odd (multi-step requests per page, dynamic auth refresh between pages).
Forgetting limitPagesFetched
A misconfigured next-URL expression returning the same URL = infinite requests. Always set a max in production.
$pageCount off by one
$pageCount is 0 on the first call. APIs paging from 1 need $pageCount + 1. Easy to miss: page 1 works, page 2 returns page 1's response.
Not splitting items
{ data: [...] } envelopes make each page one output item. Most downstream code wants a flat array. Flatten with a downstream Split Out node or an Edit Fields expression. (V3's HTTP Request has no built-in split option.)
Pagination without a stop condition
Default "response is empty" works for most APIs. For non-empty envelopes with empty data on the last page, use paginationCompleteWhen: 'other' with completeExpression checking data.length === 0.
Cross-references
- For non-HTTP looping (rate-limited fan-out, batched bulk writes), see
LOOP_OVER_ITEMS.md. - For default per-item iteration and
executeOnce, see the parentSKILL.md. - For general HTTP node config (auth, body, headers), see
n8n-node-configuration-officialHTTP_NODES.md.
Open this reference as its own page
Loop Over Items node (formerly Split In Batches)
The explicit-batching loop. Use when default per-item iteration isn't enough: rate limiting, chunked API calls, per-batch error handling, polling, or stateful iteration.
See the parent SKILL.md decision tree for "should I use this." This file assumes yes.
What it does
Splits the input array into batches of batchSize and exposes two outputs.
Output indexes (typeVersion 3):
output(0)(done): fires once after all iterations complete, with the aggregated result. Wire your post-loop step here.output(1)(loop): fires once per batch. Wire per-batch processing here and route the tail back into the Loop Over Items node.
The index order trips people up: "done" is index 0 even though it fires last. Verify via get_workflow_details after wiring.
Wiring shape:
[Source]
│
▼
[Loop Over Items] ──output(0) (done)──▶ [Final step]
│
└──output(1) (loop)──▶ [Process batch] ──▶ (back into Loop Over Items)
The "back into Loop Over Items" arrow makes it a loop. After per-batch processing runs, its tail flows back into the loop node, which either issues the next batch (loop output) or finishes (done output).
Configuration
{
name: 'Loop Over Customers',
type: 'n8n-nodes-base.splitInBatches',
parameters: {
batchSize: 50,
options: {
reset: false,
},
},
}
Key parameters:
batchSize(number): items per iteration. Default 1. Higher values trade granularity for fewer iterations.options.reset(boolean): whentrue, treats input as fresh on every iteration. For indeterminate-length loops (see below).
Pattern 1: per-item processing with multi-branch convergence
The canonical "do several things to each item, then collect" pattern. Each iteration runs multiple things in parallel that converge before flowing back into the loop. The done output yields the aggregated result.
Example (a workflow-signing utility processing each input workflow's nodes, connections, and ID independently, then signing):
Sub-workflow Trigger
→ Split Out (expand input array into items)
→ Loop Over Items
├──output(0, done)──→ Sort by ID → Sign (executeOnce) → Set Output (final result)
└──output(1, loop)──┬──→ Extract Id ────────────→ Pass1 ──┐
├──→ Split Out → Filter → Aggregate ──┼──→ Merge ──→ Merge1 ──→ back to Loop Over Items
└──→ Code: normalize connections ─→ Pass ──┘
Five things to notice:
Split Outexpands the input array into items before the loop. Without it, Loop Over Items receives one mega-item and iterates once.- The loop body fans out to parallel branches that converge via
Mergenodes. Branches recombine before the feedback edge. - Named NoOp nodes (
Pass,Pass1) anchor convergence points so downstream Merges can reference them cleanly. Pern8n-expressions-officialnon-negotiables. - The aggregate node on the done branch uses
executeOnce: true. Its.all().map(...)would otherwise execute per item, doing the aggregate N times. - Per-iteration outputs feed
Merge(combineAll). The merged shape becomes one item flowing back into the loop, so the next iteration sees one well-formed item.
The structure scales to any "for each input, run a workflow internally, then aggregate" task: signing, validation, transforming, classifying, etc.
Pattern 2: rate-limited / chunked processing
"Send these emails 5 at a time, with a 1-second pause between batches."
const loop = splitInBatches({
config: {
parameters: {
batchSize: 5,
options: {},
},
},
})
const send = node({ type: 'n8n-nodes-base.emailSend', config: { parameters: { /* ... */ } } })
const wait = node({ type: 'n8n-nodes-base.wait', config: { parameters: { amount: 1, unit: 'seconds' } } })
const summarize = node({
type: 'n8n-nodes-base.set',
config: {
executeOnce: true,
parameters: {
values: { string: [{ name: 'message', value: '={{ $input.all().length }} emails sent' }] },
},
},
})
workflow
.add(source.output(0).to(loop))
.add(loop.output(1).to(send)) // loop output: process batch
.add(send.output(0).to(wait))
.add(wait.output(0).to(loop)) // back into Loop Over Items
.add(loop.output(0).to(summarize)) // done output: final step
Three things to notice:
- The loop output (index 1) flows through processing then back into the loop node. Feedback edge = iteration.
- The done output (index 0) wires to a different downstream. Don't merge done and loop. They fire at different times.
- The summarize node uses
executeOnce: truesince it reads$input.all().
Pattern 3: chunked bulk API call
"Send items to a /bulk endpoint accepting arrays up to 100."
const loop = splitInBatches({
config: {
parameters: {
batchSize: 100,
options: {},
},
},
})
const bulkPost = node({
type: 'n8n-nodes-base.httpRequest',
config: {
executeOnce: true, // run once per batch with the full batch as one body
parameters: {
method: 'POST',
url: 'https://api.example.com/bulk',
sendBody: true,
bodyParameters: {
parameters: [
{ name: 'items', value: '={{ $input.all().map(item => item.json) }}' },
],
},
},
},
})
executeOnce: true is critical: without it, the HTTP node fires once per item within the batch (100 individual POSTs), defeating the bulk endpoint. With it, one POST per batch carries all 100 items.
Pattern 4: poll a long-running job (reset: true)
For jobs taking minutes or hours: start, poll status until done. reset: true makes the loop treat each iteration's input as fresh. Use the iteration index plus a status check to break out.
[Start long-running job]
│
▼
[Loop Over Items, reset: true]
│ output(0, done)──▶ (unused; reset:true means we never reach "done" naturally)
│
└─output(1, loop)──▶ [Wait 30s] ──▶ [Check job status]
│
▼
[IF: status.isDone OR $runIndex >= 10]
│
├── true ──▶ [Continue workflow (NoOp)]
└── false ──▶ (back to Loop Over Items)
Configuration:
const loop = splitInBatches({
config: {
parameters: {
options: { reset: true },
},
},
})
const wait = node({ type: 'n8n-nodes-base.wait', config: { parameters: { amount: 30 } } })
const checkStatus = node({
type: 'n8n-nodes-base.httpRequest',
config: {
parameters: {
url: '=https://api.example.com/jobs/{{ $("Start Job").item.json.job_id }}',
},
},
})
const decide = ifElse({
config: {
parameters: {
conditions: {
combinator: 'or',
conditions: [
{
leftValue: '={{ $("Check Job Status").item.json.isDone }}',
operator: { type: 'boolean', operation: 'true', singleValue: true },
},
{
leftValue: '={{ $runIndex }}',
rightValue: 10,
operator: { type: 'number', operation: 'gte' },
},
],
},
},
},
})
Key points:
$runIndex(or$('Loop Over Items').context.currentRunIndex) is the iteration counter and the safety fallback. Without it, a stuck job loops forever.- The IF combinator is
or: upstream reports done OR iteration cap hit. - "True" goes to the continue-workflow node, "false" feeds back for the next poll cycle.
- The done output (index 0) is unused since
reset: truenever reaches the "ran out of items" state. Termination is the IF's job.
In practice, prefer a Switch over an IF, with a separate branch for "too many iterations" so a stuck upstream surfaces as an explicit error. See n8n-error-handling-official.
Reset mode in general
reset is for indeterminate-length loops. The polling pattern above is one case. Others:
- Scraping pages until empty (though HTTP pagination is usually cleaner, see
HTTP_PAGINATION.md). - Recursive scraping/BFS where each iteration's input comes from the previous output.
{
batchSize: 1,
options: { reset: true },
}
With reset: true:
- Each iteration treats its input as the new "original" array.
- Usually feed the loop one item at a time (the next thing to process).
- Termination is your responsibility (an
IForSwitchthat breaks out).
Genuinely advanced. For paginated HTTP, use built-in pagination. For most "loop until done" cases, a self-calling sub-workflow or HTTP pagination is cleaner. Reach for reset: true only when those don't fit.
Useful expressions inside the loop
{{ $runIndex }}: current iteration (0-based). Short form. References the current node's run count, which inside a loop body equals the loop iteration.{{ $('Loop Over Items').context.currentRunIndex }}: explicit form for disambiguating multiple loops.{{ $('Loop Over Items').context.maxRunIndex }}: total iterations expected (Math.ceil(items.length / batchSize)at start). Useful for progress reporting.{{ $('Loop Over Items').context.noItemsLeft }}: boolean, true once the queue is drained. Becomes true on the iteration emitting the final batch, useful for "is this the last batch" branching inside the loop body.{{ $('Loop Over Items').item.json }}: current item from the current batch.
context answers "where are we?" without breaking per-item iteration.
Common mistakes
Wiring the wrong output index
Output 0 is done, output 1 is loop. Easy to flip. Symptoms: post-loop step never fires, or processing fires once with the full input.
Verify via get_workflow_details after wiring.
Wiring the done output back into the loop
Done fires once, at the end. Wiring it back does nothing because the loop is finished. Done goes to the post-loop step.
Forgetting the feedback edge
Without the per-batch tail connecting back to Loop Over Items, the loop fires the first batch and stops.
Forgetting to Split Out before the loop
A single item containing an array ({ items: [...] }) makes the loop iterate once. Use Split Out (or Set with =$json.items) upstream.
Using Loop Over Items for default iteration
To send 50 items through a sub-workflow, connect the source to Execute Workflow. Default iteration handles it.
Per-batch HTTP without executeOnce
If the HTTP node should send the whole batch as one request, set executeOnce: true. Otherwise it fires once per item inside the batch.
Reset loop with no termination
reset: true without a stop condition is an infinite loop. n8n eats memory until killed. Always have explicit termination (IF/Switch breaking out on stop) AND a $runIndex ceiling.
Nesting Loop Over Items inside Loop Over Items
Doesn't work. Validation passes, breaks at runtime. Extract the inner loop into a sub-workflow and call it from the outer iteration via Execute Workflow with mode: 'each'.
Verification before publishing
After wiring a Loop Over Items node, pull via get_workflow_details and verify:
- Loop output (index 1) flows into per-batch processing AND back into the loop node.
- Done output (index 0) flows into the post-loop step (or is unused for
reset: truepolling). - Aggregate nodes inside the loop or on the done branch have
executeOnce: trueif they should fire once. - Clear termination: bounded input array, or a stop branch with a
$runIndexfallback.
More in this playbook
Safe to turn on
Use this skill when an agent or person is about to create, change or enable an automation inside someone else's account or a shared environment: "create this workflow", "build it in the customer's account", "turn it on", "go live", "deploy this automation". Produces a proposal the human approves, an automation created in the off state, and a short list of what only the human can finish.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.


