Tips > Building Workflows

Debug Workflows by Logging Intermediate Data

When a workflow produces unexpected output and the execution log is not detailed enough, use a Code node to write intermediate data to a JSON file on disk.

TipIntermediate2 min read

When a workflow produces unexpected output and the execution log is not detailed enough, use a Code node to write intermediate data to a JSON file on disk. This is invaluable for debugging production issues where you cannot use the manual execution UI.

Real-world example: A data pipeline transforms records through 8 nodes and the final output is wrong, but you cannot tell which node introduced the problem.

// Mode: Run Once for All Items
const fs = require('fs');
const path = require('path');

const debugDir = '/tmp/n8n-debug';
if (!fs.existsSync(debugDir)) {
  fs.mkdirSync(debugDir, { recursive: true });
}

const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filename = path.join(
  debugDir,
  `debug_${$workflow.name.replace(/\s+/g, '_')}_${timestamp}.json`
);

const debugPayload = {
  executionId: $execution.id,
  workflowName: $workflow.name,
  timestamp: new Date().toISOString(),
  itemCount: $input.all().length,
  items: $input.all().map((item, idx) => ({
    index: idx,
    jsonKeys: Object.keys(item.json),
    json: item.json,
    hasBinary: !!item.binary && Object.keys(item.binary).length > 0,
    binaryKeys: item.binary ? Object.keys(item.binary) : [],
  })),
};

fs.writeFileSync(filename, JSON.stringify(debugPayload, null, 2));

// Pass items through unchanged so the workflow is not affected
const items = $input.all();

// Add debug metadata to first item
items[0].json._debugFile = filename;

return items;
```text
> **Danger: Remove Before Production**
>
> Always remove or disable debug Code nodes before deploying to production. Writing to disk on every execution will consume storage and potentially expose sensitive data. Use n8n's built-in [Execution Data](https://docs.n8n.io/workflows/executions/) features for long-term monitoring instead.

| Debug Method | When to Use |
|:------------|:------------|
| Debug Code node (this tip) | Complex data issues in production pipelines |
| Manual execution with pin data | Developing and testing individual nodes |
| `console.log` in Code node | Quick checks visible in Docker/server logs |
| Execution history inspection | Reviewing past runs after the fact |

**Related:** [Use Edit Fields in "Map Each" Mode for Simple Renames](../data-transformation/01-use-edit-fields-in-map-each-mode-for-simple-renames.md) | [Configure Payload Size and Binary Data Mode for Large Files](../performance-and-large-files/01-configure-payload-size-and-binary-data-mode-for-large-files.md)

Want this running in your stack?

I build production n8n and Cloudflare automation for teams — the same engineering behind HarperFlow. Fixed-price, escrow-protected, US-based.