# Error Patterns - JavaScript Code Node Complete guide to avoiding the most common Code node errors. --- ## Overview This guide covers the **top 5 error patterns** encountered in n8n Code nodes. Understanding and avoiding these errors will save you significant debugging time. **Error Frequency**: 1. Empty Code / Missing Return - **38% of failures** 2. Expression Syntax Confusion - **8% of failures** 3. Incorrect Return Wrapper - **5% of failures** 4. Unmatched Expression Brackets - **6% of failures** 5. Missing Null Checks - **Common runtime error** --- ## Error #1: Empty Code or Missing Return Statement **Frequency**: Most common error (38% of all validation failures) **What Happens**: - Workflow execution fails - Next nodes receive no data - Error: "Code cannot be empty" or "Code must return data" ### The Problem ```javascript // ❌ ERROR: No code at all // (Empty code field) ``` ```javascript // ❌ ERROR: Code executes but doesn't return anything const items = $input.all(); // Process items for (const item of items) { console.log(item.json.name); } // Forgot to return! ``` ```javascript // ❌ ERROR: Early return path exists, but not all paths return const items = $input.all(); if (items.length === 0) { return []; // ✅ This path returns } // Process items const processed = items.map(item => ({json: item.json})); // ❌ Forgot to return processed! ``` ### The Solution ```javascript // ✅ CORRECT: Always return data const items = $input.all(); // Process items const processed = items.map(item => ({ json: { ...item.json, processed: true } })); return processed; // ✅ Return statement present ``` ```javascript // ✅ CORRECT: Return empty array if no items const items = $input.all(); if (items.length === 0) { return []; // Valid: empty array when no data } // Process and return return items.map(item => ({json: item.json})); ``` ```javascript // ✅ CORRECT: All code paths return const items = $input.all(); if (items.length === 0) { return []; } else if (items.length === 1) { return [{json: {single: true, data: items[0].json}}]; } else { return items.map(item => ({json: item.json})); } // All paths covered ``` ### Checklist - [ ] Code field is not empty - [ ] Return statement exists - [ ] ALL code paths return data (if/else branches) - [ ] Return format is correct (`[{json: {...}}]`) - [ ] Return happens even on errors (use try-catch) --- ## Error #2: Expression Syntax Confusion **Frequency**: 8% of validation failures **What Happens**: - Syntax error in code execution - Error: "Unexpected token" or "Expression syntax is not valid in Code nodes" - Template variables not evaluated ### The Problem n8n has TWO distinct syntaxes: 1. **Expression syntax** `{{ }}` - Used in OTHER nodes (Set, IF, HTTP Request) 2. **JavaScript** - Used in CODE nodes (no `{{ }}`) Many developers mistakenly use expression syntax inside Code nodes. ```javascript // ❌ WRONG: Using n8n expression syntax in Code node const userName = "{{ $json.name }}"; const userEmail = "{{ $json.body.email }}"; return [{ json: { name: userName, email: userEmail } }]; // Result: Literal string "{{ $json.name }}", NOT the value! ``` ```javascript // ❌ WRONG: Trying to evaluate expressions const value = "{{ $now.toFormat('yyyy-MM-dd') }}"; ``` ### The Solution ```javascript // ✅ CORRECT: Use JavaScript directly (no {{ }}) const userName = $json.name; const userEmail = $json.body.email; return [{ json: { name: userName, email: userEmail } }]; ``` ```javascript // ✅ CORRECT: JavaScript template literals (use backticks) const message = `Hello, ${$json.name}! Your email is ${$json.email}`; return [{ json: { greeting: message } }]; ``` ```javascript // ✅ CORRECT: Direct variable access const item = $input.first().json; return [{ json: { name: item.name, email: item.email, timestamp: new Date().toISOString() // JavaScript Date, not {{ }} } }]; ``` ### Comparison Table | Context | Syntax | Example | |---------|--------|---------| | Set node | `{{ }}` expressions | `{{ $json.name }}` | | IF node | `{{ }}` expressions | `{{ $json.age > 18 }}` | | HTTP Request URL | `{{ }}` expressions | `{{ $json.userId }}` | | **Code node** | **JavaScript** | `$json.name` | | **Code node strings** | **Template literals** | `` `Hello ${$json.name}` `` | ### Quick Fix Guide ```javascript // WRONG → RIGHT conversions // ❌ "{{ $json.field }}" // ✅ $json.field // ❌ "{{ $now }}" // ✅ new Date().toISOString() // ❌ "{{ $node['HTTP Request'].json.data }}" // ✅ $node["HTTP Request"].json.data // ❌ `{{ $json.firstName }} {{ $json.lastName }}` // ✅ `${$json.firstName} ${$json.lastName}` ``` --- ## Error #3: Incorrect Return Wrapper Format **Frequency**: 5% of validation failures **What Happens**: - Error: "Return value must be an array of objects" - Error: "Each item must have a json property" - Next nodes receive malformed data ### The Problem Code nodes MUST return: - **Array** of objects - Each object MUST have a **`json` property** ```javascript // ❌ WRONG: Returning object instead of array return { json: { result: 'success' } }; // Missing array wrapper [] ``` ```javascript // ❌ WRONG: Returning array without json wrapper return [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'} ]; // Missing json property ``` ```javascript // ❌ WRONG: Returning plain value return "processed"; ``` ```javascript // ❌ WRONG: Returning items without mapping return $input.all(); // Works if items already have json property, but not guaranteed ``` ```javascript // ❌ WRONG: Incomplete structure return [{data: {result: 'success'}}]; // Should be {json: {...}}, not {data: {...}} ``` ### The Solution ```javascript // ✅ CORRECT: Single result return [{ json: { result: 'success', timestamp: new Date().toISOString() } }]; ``` ```javascript // ✅ CORRECT: Multiple results return [ {json: {id: 1, name: 'Alice'}}, {json: {id: 2, name: 'Bob'}}, {json: {id: 3, name: 'Carol'}} ]; ``` ```javascript // ✅ CORRECT: Transforming array const items = $input.all(); return items.map(item => ({ json: { id: item.json.id, name: item.json.name, processed: true } })); ``` ```javascript // ✅ CORRECT: Empty result return []; // Valid when no data to return ``` ```javascript // ✅ CORRECT: Conditional returns if (shouldProcess) { return [{json: {result: 'processed'}}]; } else { return []; } ``` ### Return Format Checklist - [ ] Return value is an **array** `[...]` - [ ] Each array element has **`json` property** - [ ] Structure is `[{json: {...}}]` or `[{json: {...}}, {json: {...}}]` - [ ] NOT `{json: {...}}` (missing array wrapper) - [ ] NOT `[{...}]` (missing json property) ### Common Scenarios ```javascript // Scenario 1: Single object from API const response = $input.first().json; // ✅ CORRECT return [{json: response}]; // ❌ WRONG return {json: response}; // Scenario 2: Array of objects const users = $input.all(); // ✅ CORRECT return users.map(user => ({json: user.json})); // ❌ WRONG return users; // Risky - depends on existing structure // Scenario 3: Computed result const total = $input.all().reduce((sum, item) => sum + item.json.amount, 0); // ✅ CORRECT return [{json: {total}}]; // ❌ WRONG return {total}; // Scenario 4: No results // ✅ CORRECT return []; // ❌ WRONG return null; ``` --- ## Error #4: Unmatched Expression Brackets **Frequency**: 6% of validation failures **What Happens**: - Parsing error during save - Error: "Unmatched expression brackets" - Code appears correct but fails validation ### The Problem This error typically occurs when: 1. Strings contain unbalanced quotes 2. Multi-line strings with special characters 3. Template literals with nested brackets ```javascript // ❌ WRONG: Unescaped quote in string const message = "It's a nice day"; // Single quote breaks string ``` ```javascript // ❌ WRONG: Unbalanced brackets in regex const pattern = /\{(\w+)\}/; // JSON storage issue ``` ```javascript // ❌ WRONG: Multi-line string with quotes const html = "
Hello
Hello
${content}