The Function node excels at data transformation, allowing you to manipulate information flowing between other nodes in your workflow. Whether you need to restructure data formats, perform calculations, or apply custom business logic, this node serves as your primary tool for implementing bespoke functionality.
Examples
Get property value from a previous node
for (const [index, item] of items.entries()) {
item.json.myVar =
$item(index).$node["node name"].json.myVar;
}let myVar = items[0].json.myVar;Check if the previous node returns an empty item
return [
{
json: {
empty: items.length == 1 && Object.keys(items[0].json).length == 0,
},
},
];
The safe way to get node data
// Helper function to safely get node data
function safeGetNodeData(nodeName) {
try {
return $(nodeName).all() || [];
} catch (error) {
console.log(`Node ${nodeName} was not executed or has no data`);
return [];
}
}
const extractClaimData = safeGetNodeData('node_name_here');Access all items from the previous node output
return $items("node name");Get Data From an IF node based on the branch
$("IF node name").all(0) // 0 = true branch (first output)
$("IF node name").all(1) // 1 = false branch (second output)Concatenate 2 Nodes and Sort
// Get data from both input nodes
const data1 = $("node name").all();
const data2 = $('Is True?').all(1);
// Concatenate both arrays
const combinedData = [...data1 , ...data2];
// Sort by json.index
const sortedData = combinedData.sort((a, b) => a.json.index - b.json.index);
// Return the sorted combined data
return sortedData;Execution Context Variables
// Current execution ID
$executionId
// Current workflow ID
$workflowId
// Current node name
$node.name
// Current node type
$node.type
// Current node parameters
$node.parameters
// Current run index (useful for loops)
$runIndex
// Total number of runs
$execution.resumeUrl // For webhook resumptionItem Navigation & Data Access
// Current item data
$json // Current item's JSON data
$binary // Current item's binary data
// Access data from specific nodes
$items("Node Name") // All items from a node
$items("Node Name")[0] // First item from a node
$items("Node Name", 0, 0) // Specific item (node, run, item index)
// Previous node data
$input.all() // All items from previous node
$input.first() // First item from previous node
$input.last() // Last item from previous node
$input.item // Current item being processed
// Access specific item properties
$('Node Name').all() // Alternative syntax
$('Node Name').first()
$('Node Name').last()
$('Node Name').item
$('Node Name').itemMatching(0) // Item at specific indexEnvironment & Workflow Info
// Environment variables
$env.VARIABLE_NAME
// Workflow execution mode
$execution.mode // "manual", "trigger", "webhook", etc.
// Resume information (for waiting nodes)
$execution.resumeUrl
$execution.resumeFormUrl
// Workflow metadata
$workflow.id
$workflow.name
$workflow.active
// Current date/time
$now // Current timestamp
$today // Today's date
$timezone // Workflow timezoneError Handling & Flow Control
// Error information (in error workflows)
$error.message
$error.stack
$error.node
$error.execution
// Execution state
$execution.mode
$execution.id
// For IF/Switch nodes
$resumeWebhookUrl // Resume webhook URLUtility Functions
// Date functions
$now.format('YYYY-MM-DD')
$today.format('YYYY-MM-DD')
// Math functions
$min(array)
$max(array)
$sum(array)
// String functions
$length(string)
$upper(string)
$lower(string)
// Array functions
$first(array)
$last(array)
$unique(array)Advanced/Less Common but Useful
// Access all executions data
$executions // Historical execution data
// Node parameters
$parameter.parameterName // Access node parameters
// Loop information
$itemIndex // Current item index in loop
$runIndex // Current run index
// Binary data helpers
$binary.propertyName.fileSize
$binary.propertyName.mimeType
$binary.propertyName.fileName
// Webhook-specific
$request.headers
$request.query
$request.body
$request.params
// For HTTP Request nodes
$response.headers
$response.statusCode
$response.bodyCode Node Specific
// In Function/Function Item nodes
items // Input items array
item // Current item (Function Item node)
// Access other node data
$items("Node Name")
$input.all()
// Return format
return items; // Return modified items arrayBuilt-in Error Output
// Throw errors to see debug info
if (someCondition) {
throw new Error(`Debug: transformedIndex = ${transformedIndex}, found ${matchingItems.length} matches`);
}Practical Examples
// Get data from specific node
const userData = $items("Get User Data")[0].json;
// Access environment variable
const apiKey = $env.API_KEY;
// Format current date
const today = $now.format('YYYY-MM-DD');
// Get execution info
console.log(`Execution ID: ${$executionId}`);
console.log(`Workflow: ${$workflow.name}`);
console.log(`Node: ${$node.name}`);
// Access binary file info
const fileName = $binary.data.fileName;
const fileSize = $binary.data.fileSize;
// Loop through previous node items
for (const item of $input.all()) {
console.log(item.json);
}Pro Tips
- Use
$items("Node Name")for explicit data access instead of assuming item order - Always check for data existence before accessing:
$items("Node Name")[0]?.json - Use
$envfor sensitive data like API keys instead of hardcoding - Leverage
$runIndexfor tracking iterations in loops - Use
$execution.modeto handle different execution contexts - Access
$errorvariables in error workflow branches
These variables make n8n workflows much more dynamic and powerful! The most commonly used ones are $items(), $json, $binary, $env, and $now.