
Step by Step Guide to solve n8n Code Node Runtime Error
Who this is for: n8n developers who use the Code node for custom logic and need a fast, reliable way to debug runtime failures. We cover this in detail in the n8n Node Specific Errors Guide.
Quick Diagnosis
Symptom: The Code node stops with “Runtime error: …” (e.g., ReferenceError, TypeError, unhandled promise rejection).
Quick fix (≈30 s):
| Step | Action |
|---|---|
| 1 | Open Execute Workflow → Console (top‑right ▶️). |
| 2 | Wrap the whole script in a try { … } catch (err) { console.error(err); throw err; } block. |
| 3 | Ensure every await lives inside an async function. |
| 4 | If using TypeScript, set "sourceMap": true in tsconfig.json and rebuild (npm run build). |
| 5 | Re‑run the node – the console now shows the exact line/stack; fix the highlighted code. |
Result: The node executes without the runtime exception.
Note: For persistent errors, follow the detailed debugging workflow below.
1. Why Code Nodes Throw Runtime Errors
If you encounter any n8n execute command node invalid command resolve them before continuing with the setup.
The Code node evaluates user‑supplied JavaScript/TypeScript at runtime inside n8n’s sandbox. Errors that would normally be caught at compile time appear only when the node runs.
| Category | Typical Exception | Example |
|---|---|---|
| Undefined / Misspelled Variables | ReferenceError: xyz is not defined | return data.map(item => item.idd); |
| Invalid Types | TypeError: Cannot read property ‘length’ of undefined | if (input.length > 0) … |
| Promise Mis‑handling | UnhandledPromiseRejectionWarning | await fetch(url); without async |
| TypeScript Transpilation Issues | SyntaxError: Unexpected token | Using ?. without proper target ES version |
| Missing Imports / Packages | Error: Cannot find module ‘lodash’ | import _ from 'lodash'; without installing it |
Because the sandbox isolates each node, global state leaks are impossible, but the original stack trace is hidden unless source maps are enabled.
2. Prerequisites – Set Up a Debug‑Friendly Environment
If you encounter any n8n if node conditional evaluation error resolve them before continuing with the setup.
| Requirement | How to Enable |
|---|---|
| Console output | Click Execute Workflow → Console tab. |
| Source maps for TypeScript | Add a tsconfig.json at the workflow root:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"sourceMap": true
}
}
Then run |
| Strict mode | Insert "use strict"; as the first line of the script. |
| Node version parity | n8n runs on Node 18 (2024). Use only features supported by this version. |
3. Step‑by‑Step Debugging Workflow (Code‑Node Focus)
3.1 Isolate & Log
- Comment out everything except a single line that reproduces the failure.
- Add a
console.logbefore the suspect line to view its value.
3.2 Capture the Stack Trace
Wrap the script in a try/catch so the sandbox prints a full stack trace.
try {
// Your original logic goes here
} catch (err) {
console.error('Runtime error in Code node:', err);
throw err; // Let n8n mark the node as failed
}
3.3 Validate Async Flow
await is only allowed inside an async function. Convert top‑level awaits accordingly.
async function run() {
const data = await fetch(url);
return data;
}
return await run(); // Return the resolved value to n8n
3.4 Compile TypeScript
If you write TS, run the built‑in compile step (n8n ts-compile or UI **Compile**). Fix any compile‑time errors before re‑executing.
3.5 Install Missing Packages
Use the **“Install npm package”** node to add dependencies, then require them.
const _ = require('lodash'); // Works after installing lodash via the package node
3.6 Re‑run & Iterate
After the above adjustments, the console will display a **file‑line** reference (thanks to source maps). Fix the highlighted line, repeat until the node succeeds.
4. Common Runtime Error Patterns & Fixes
If you encounter any n8n error node catch all failure resolve them before continuing.
| Error Message | Root Cause | Fix |
|---|---|---|
| ReferenceError: foo is not defined | Variable typo or missing declaration. | Declare the variable (let foo = …) or correct the name. |
| TypeError: Cannot read property ‘xxx’ of undefined | Accessing a property on a possibly null/undefined object. |
Guard with if (obj && obj.xxx) … or use optional chaining obj?.xxx. |
| SyntaxError: Unexpected token ‘?.’ | Optional chaining used without ES2020 target. | Set "target": "ES2020" (or later) in tsconfig.json. |
| UnhandledPromiseRejectionWarning | Missing await or uncaught promise rejection. |
Add await inside an async function and wrap with try/catch. |
| Error: Cannot find module ‘axios’ | Dependency not installed in the workflow environment. | Add an **npm Install** node for axios or switch to the built‑in HTTP Request node. |
Example: Fixing an Unhandled Promise
Problematic code (returns a Promise, not data):
const response = fetch('https://api.example.com/data');
return response.json();
Corrected version (await the fetch and handle errors):
async function getData() {
const res = await fetch('https://api.example.com/data');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
}
return await getData();
5. Troubleshooting Checklist
| ✅ | Item |
|---|---|
| ☐ | Confirm the node’s language mode (JavaScript vs. TypeScript). |
| ☐ | Enable source maps ("sourceMap": true). |
| ☐ | Wrap the entire script in a try/catch block that re‑throws. |
| ☐ | Verify every await lives inside an async function. |
| ☐ | Add console.log before each risky operation. |
| ☐ | Look for undefined variables or misspelled identifiers. |
| ☐ | Install any imported npm packages via an **npm Install** node. |
| ☐ | Ensure tsconfig.json target matches the syntax you use. |
| ☐ | Re‑run the node and read the exact line/stack from the console. |
| ☐ | After fixing, remove temporary logs and keep only essential error handling. |
6. EEFA (Experience, Expertise, Authority, Trust) Notes
- Production safety: Never swallow errors with a blanket
try { … } catch {}. Always log and re‑throw so downstream error handling works. - Performance: Excessive
console.login high‑throughput workflows can degrade throughput. Keep logs concise and prune them after debugging. - Security: Avoid logging secrets (API keys, passwords). Use environment variables (
process.env.MY_SECRET) and never print them. - Version lock: If your workflow relies on a specific Node feature (e.g., optional chaining), pin the n8n Docker image to a version that bundles the required Node runtime.
8. Next Steps
- Advanced: Using the n8n Debugger Extension – attach VS Code to the sandbox for breakpoint debugging.
- Security hardening: Sanitizing user input in Code nodes to prevent injection attacks.
- Performance tuning: Offloading heavy computations to external services instead of the Code node.
Conclusion
Runtime errors in n8n’s Code node stem from undefined variables, type mismatches, improper async handling, missing dependencies, or TypeScript compilation gaps. By enabling source maps, wrapping scripts in a try/catch, enforcing async/await discipline, and installing required packages, you gain immediate visibility into the exact failing line. Apply the checklist, clean up temporary logs, and keep error handling explicit so your workflows remain robust, performant, and secure in production.



