Back to Blog
n8ncode nodetutorialjavascriptguide

n8n Code Node: A Complete Guide to Custom Logic in 2026

n8nautomation TeamApril 17, 2026
TL;DR: The n8n Code Node allows you to run custom JavaScript within your workflows. It's the ultimate tool for handling complex data transformations, custom logic, or interacting with APIs that don't have a dedicated node, giving you complete control over your automation.

The n8n Code Node is one of the most powerful features in your automation toolkit, acting as a "Swiss Army knife" when you need to solve problems that pre-built nodes can't handle. While n8n offers over 400 integrations, you'll inevitably encounter a unique challenge, a legacy system, or a complex data structure that requires custom logic. This is where the Code Node shines, letting you write JavaScript directly inside your workflow.

What Is the n8n Code Node?

The Code Node is a special n8n node that executes custom JavaScript (server-side, via Node.js). It exists to bridge gaps, add flexibility, and give you granular control over your data and workflow execution. You don't need to be a full-stack developer to use it, but a basic understanding of JavaScript a day will unlock immense potential.

You should use the Code Node when:

  • You need to perform a complex data transformation that's difficult with other nodes.
  • You want to implement custom conditional logic or loops that go beyond the If and Switch nodes.
  • You need to make a request to an API that doesn't have a dedicated n8n node.
  • You want to perform calculations or manipulate strings and arrays in a specific way.

Essentially, if you find yourself thinking, "I wish there was a node that did X," the Code Node is often the answer.

Getting Started: Your First Code Node

Let's start with the basics. Adding and running a Code Node is straightforward. For this example, we'll create a simple workflow that just runs a single Code Node.

  1. In your n8n canvas, click the + icon to add a new node.
  2. Search for "Code" and select it.
  3. The node editor will open, showing a simple JavaScript editor.
  4. By default, it contains some example code. You can delete it for now.
  5. Enter the following code into the editor:
    
    const message = "Hello, n8nautomation.cloud!";
    return {
      json: {
        greeting: message
      }
    };
    
  6. Click the "Execute Node" button.

After executing, inspect the output in the right-hand panel. You'll see a single item with a JSON object containing the `greeting` property. You've successfully executed custom code and returned a structured result!

Accessing and Manipulating Input Data

A Code Node is most useful when it interacts with data from previous nodes. The n8n Code Node makes all incoming data available through a special variable called items.

The items variable is an array of n8n data objects. Each object in the array represents an item passed from the preceding node and has several properties, but the one you will use 99% of the time is json. To access the data for the first incoming item, you would use items[0].json.

Let's try an example. Imagine a webhook passes the following JSON data to your workflow:


{
  "user": {
    "firstName": "Jane",
    "lastName": "Doe",
    "email": "jane.doe@example.com"
  },
  "orderId": "ORD-12345"
}

Your Code Node can access and reformat this data. Connect your Code Node to the node providing this data (like a Webhook node or another Code node for simulation) and use the following script:


// The 'items' variable holds all input data
const inputData = items[0].json;

// Extract and transform the data
const fullName = `${inputData.user.firstName} ${inputData.user.lastName}`;
const contact = `Email: ${inputData.user.email}`;

// Return a new, cleaner object
return {
  json: {
    orderReference: inputData.orderId,
    customerName: fullName,
    customerContact: contact,
    processedAt: new Date().toISOString()
  }
};

When you execute this node, it will transform the raw input into a clean, structured object ready for the next step in your workflow, like adding a row to a Google Sheet or sending a formatted email.

Tip: The Code Node editor has an "Inputs" panel on the left. Click it to see the exact structure of incoming data. You can even click on a data path to automatically generate the code snippet to access it, like items[0].json.user.firstName.

Returning Data for Downstream Nodes

How you return data from the Code Node determines what subsequent nodes receive. The structure must be an object (or an array of objects) containing a json property.

  • Returning a single item: To output one item, return a single object as shown in previous examples. The workflow will run once for this item.
    
    return {
      json: { data: 'My single item' }
    };
    
  • Returning multiple items: To output multiple items, which causes downstream nodes to execute for each item, return an array of objects.
    
    const results = [
      { json: { id: 1, status: 'processed' } },
      { json: { id: 2, status: 'processed' } },
      { json: { id: 3, status: 'pending' } }
    ];
    
    return results;
    
  • Passing through existing data: Sometimes you just want to add a field without losing the original data. You can easily merge the original data with your new fields.
    
    // Get the first input item's data
    const originalData = items[0].json;
    
    // Return the original data plus a new property
    return {
      json: {
        ...originalData,
        customField: 'This was added by the Code Node'
      }
    };
    

Always ensure your return statement is correct, as an improperly formatted output will stop the workflow execution path.

Practical Code Node Use Cases

Let's explore some real-world scenarios where the n8n Code Node is invaluable.

1. Custom Data Transformation

Scenario: An API provides a date as a UNIX timestamp (e.g., 1737139200), but you need to display it in a human-readable format in a Slack message.

Code:


const timestamp = items[0].json.event_time;

// JavaScript's Date constructor handles UNIX timestamps (in milliseconds)
const readableDate = new Date(timestamp * 1000).toUTCString();

return {
  json: {
    ...items[0].json,
    formattedDate: readableDate
  }
};

2. Dynamic API Requests with `fetch`

Scenario: You need to call a third-party API that doesn't have an official n8n node. You can use Node.js's built-in fetch function right inside the Code Node.

Code:


// IMPORTANT: Store API keys in n8n credentials, not in the code!
// Here we assume a credential named 'My Weather API' with a key 'apiKey'.
const apiKey = $credentials.apiKey;

const city = items[0].json.city;
const response = await fetch(`https://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${city}`);

if (!response.ok) {
  throw new Error(`API request failed with status ${response.status}`);
}

const weatherData = await response.json();

return {
  json: weatherData
};
Note: Using await for promises like fetch is fully supported. This makes handling asynchronous operations simple and clean. Never hardcode credentials; always use the credentials pane.

3. Complex Filtering and Looping

Scenario: You have a list of users, and you need to filter for users who have a Gmail address and are older than 30.

Code:


const users = items.map(item => item.json);
const filteredUsers = [];

const thirtyYearsAgo = new Date();
thirtyYearsAgo.setFullYear(thirtyYearsAgo.getFullYear() - 30);

for (const user of users) {
  const birthDate = new Date(user.dateOfBirth);
  if (user.email.endsWith('@gmail.com') && birthDate < thirtyYearsAgo) {
    filteredUsers.push({ json: user });
  }
}

return filteredUsers;

Advanced Techniques and Best Practices

Ready to level up your Code Node skills? Here are some tips for writing robust and maintainable code.

  • Use `try...catch` for Reliability: When dealing with external APIs or complex logic, wrap your code in a `try...catch` block to handle potential errors gracefully without halting the entire workflow.
  • Keep Code Clean: Add comments to explain complex parts of your script. Use meaningful variable names to make your code easy to understand when you revisit it months later.
  • Manage Environment Variables: For self-hosted and dedicated instances like those on n8nautomation.cloud, you can configure environment variables for the Code Node (e.g., to allow external npm modules), offering even greater flexibility.
  • Don't Hardcode Secrets: As mentioned, always use n8n's built-in credential management for API keys, tokens, and other secrets. Access them via the $credentials variable.
  • Break Down Complex Logic: If a Code Node script becomes very long (e.g., 100+ lines), consider if the logic can be split into multiple, smaller Code Nodes. This improves readability and makes debugging easier.

The Code Node is a testament to n8n's flexibility, empowering you to build truly bespoke automations. By mastering this single node, you can overcome countless obstacles and create workflows that are perfectly tuned to your operational needs.

Ready to automate with n8n?

Get affordable managed n8n hosting with 24/7 support.