How to read node parameter in jsCode for code node?

Here workflow_id is the node parameter but that workflow_id I’m not able to access in jsCode: in same node

{
                "parameters": {
                "mode": "runOnceForAllItems",
                "language": "python",
                "workflow_id": workflow_id,
                "jsCode": "// JS version\nconst workflow_id_val = $parameter.workflow_id;\nlet results = [];\n\n// Helper to format into Python's expected format\nfunction formatToApiDate(d) {\n    const yyyy = d.getUTCFullYear();\n    const mm = String(d.getUTCMonth() + 1).padStart(2, '0');\n    const dd = String(d.getUTCDate()).padStart(2, '0');\n    const hh = String(d.getUTCHours()).padStart(2, '0');\n    const min = String(d.getUTCMinutes()).padStart(2, '0');\n    const ss = String(d.getUTCSeconds()).padStart(2, '0');\n    const ms = String(d.getUTCMilliseconds()).padStart(3, '0'); // 3-digit\n    return `${yyyy}-${mm}-${dd} ${hh}:${min}:${ss}.${ms}000`;   // pad to microseconds\n}\n\nfor (const item of $input.all()) {\n    try {\n        const input_data = item.json || item;\n        let exit_code = 0;\n        let stderr = null;\n\n        if (input_data.error) {\n            exit_code = 1;\n            stderr = input_data.error;\n        } else if (input_data.stderr) {\n            exit_code = 1;\n            stderr = input_data.stderr;\n        } else if (input_data.exitCode && input_data.exitCode !== 0) {\n            exit_code = input_data.exitCode;\n            stderr = input_data.stderr || 'Command failed with non-zero exit code';\n        }\n\n        const result = {\n            dag_id: workflow_id_val,\n            status: exit_code === 0 ? 'success' : 'failed',\n            last_run_time: formatToApiDate(new Date()),\n            error: stderr\n        };\n\n        results.push({ json: result });\n\n    } catch (e) {\n        const result = {\n            dag_id: workflow_id_val,\n            status: 'failed',\n            last_run_time: formatToApiDate(new Date()),\n            error: `Exception: ${e.message}`,\n            debug_items: JSON.stringify(item)\n        };\n        results.push({ json: result });\n    }\n}\n\nreturn results;",
                "pythonCode": "from datetime import datetime\n\nworkflow_id_val = workflow_id\nresults = []\n\nfor item in items:\n    try:\n        input_data = item.get('json', item)\n        exit_code = 0\n        stderr = None\n\n        if 'error' in input_data and input_data['error']:\n            exit_code = 1\n            stderr = input_data['error']\n        elif 'stderr' in input_data and input_data['stderr']:\n            exit_code = 1\n            stderr = input_data['stderr']\n        elif 'exitCode' in input_data and input_data['exitCode'] != 0:\n            exit_code = input_data['exitCode']\n            stderr = input_data.get('stderr', 'Command failed with non-zero exit code')\n\n        result = {\n            'dag_id': workflow_id_val,\n            'status': 'success' if exit_code == 0 else 'failed',\n            'last_run_time': datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'),\n            'error': stderr\n        }\n\n    except Exception as e:\n        result = {\n            'dag_id': workflow_id_val,\n            'status': 'failed',\n            'last_run_time': datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'),\n            'error': f'Exception: {str(e)}',\n            'debug_items': str(item)\n        }\n\n    results.append({'json': result})\n\nreturn results"
            },
            "type": "n8n-nodes-base.code",
            "typeVersion": 1,
            "position": [600, -200],
            "id": "your-build-payload-node-id",
            "name": "Build Payload"
        }

Share the output returned by the last node

[
{
“dag_id”:
“{workflow_id}”,
“status”:
“failed”,
“last_run_time”:
“2025-09-25 10:55:07.431000”,
“error”:
“The connection cannot be established, this usually occurs due to an incorrect host (domain) value”
}
]

Hey, can you share your workflow again?

Here is my complete workflow json
workflow_json = {
“name”: f"{task_name} - {testcase_name} Workflow",
“nodes”: [
{
“parameters”: {
“rule”: {
“interval”: [
{
“field”: “cronExpression”,
“expression”: cron_expression
}
]
}
},
“type”: “n8n-nodes-base.scheduleTrigger”,
“typeVersion”: 1.2,
“position”: [0, 0],
“id”: schedule_trigger_id,
“name”: “Schedule Trigger”,
},
{
“parameters”: {
“conditions”: {
“options”: {
“caseSensitive”: True,
“leftValue”: “”,
“typeValidation”: “strict”,
“version”: 2
},
“conditions”: [
{
“id”: str(uuid.uuid4()),
“leftValue”: “={{ new Date() }}”,
“rightValue”: (end_dt_n8n + timedelta(minutes=2)).strftime(“%Y-%m-%dT%H:%M:%S”),
“operator”: {
“type”: “dateTime”,
“operation”: “beforeOrEquals”
}
}
],
“combinator”: “and”
},
“options”: {}
},
“type”: “n8n-nodes-base.if”,
“typeVersion”: 2.2,
“position”: [208, 0],
“id”: if_node_id,
“name”: “If”
},
{
“parameters”: {
“command”: (
f’python “{windows_script_path}” “{testcase_name}” “{user_id}” “{client_id}” ’
f’“{workflow_id}” “{schedule_platform}” “{task_name}” ’
f’“{(end_dt_n8n + timedelta(minutes=2)).strftime(”%Y-%m-%d %H:%M:%S")}"’
)
},
“type”: “n8n-nodes-base.executeCommand”,
“typeVersion”: 1,
“position”: [416, -96],
“id”: execute_command_id,
“name”: “Execute Command”,
“continueOnFail”: True,
“alwaysOutputData”: True ,
“onError”: “continueRegularOutput”
},
{
“parameters”: {
“errorMessage”: “Condition not met - current time is after end date.”
},
“type”: “n8n-nodes-base.stopAndError”,
“typeVersion”: 1,
“position”: [416, 96],
“id”: stop_error_id,
“name”: “Stop and Error”
},
{
“parameters”: {
“mode”: “runOnceForAllItems”,
“language”: “python”,
“workflow_id”: workflow_id,
“jsCode”: “// JS version\nconst workflow_id_val = $parameter.workflow_id;\nlet results = ;\n\n// Helper to format into Python’s expected format\nfunction formatToApiDate(d) {\n const yyyy = d.getUTCFullYear();\n const mm = String(d.getUTCMonth() + 1).padStart(2, ‘0’);\n const dd = String(d.getUTCDate()).padStart(2, ‘0’);\n const hh = String(d.getUTCHours()).padStart(2, ‘0’);\n const min = String(d.getUTCMinutes()).padStart(2, ‘0’);\n const ss = String(d.getUTCSeconds()).padStart(2, ‘0’);\n const ms = String(d.getUTCMilliseconds()).padStart(3, ‘0’); // 3-digit\n return ${yyyy}-${mm}-${dd} ${hh}:${min}:${ss}.${ms}000; // pad to microseconds\n}\n\nfor (const item of $input.all()) {\n try {\n const input_data = item.json || item;\n let exit_code = 0;\n let stderr = null;\n\n if (input_data.error) {\n exit_code = 1;\n stderr = input_data.error;\n } else if (input_data.stderr) {\n exit_code = 1;\n stderr = input_data.stderr;\n } else if (input_data.exitCode && input_data.exitCode !== 0) {\n exit_code = input_data.exitCode;\n stderr = input_data.stderr || ‘Command failed with non-zero exit code’;\n }\n\n const result = {\n dag_id: workflow_id_val,\n status: exit_code === 0 ? ‘success’ : ‘failed’,\n last_run_time: formatToApiDate(new Date()),\n error: stderr\n };\n\n results.push({ json: result });\n\n } catch (e) {\n const result = {\n dag_id: workflow_id_val,\n status: ‘failed’,\n last_run_time: formatToApiDate(new Date()),\n error: Exception: ${e.message},\n debug_items: JSON.stringify(item)\n };\n results.push({ json: result });\n }\n}\n\nreturn results;”,
“pythonCode”: “from datetime import datetime\n\nworkflow_id_val = workflow_id\nresults = \n\nfor item in items:\n try:\n input_data = item.get(‘json’, item)\n exit_code = 0\n stderr = None\n\n if ‘error’ in input_data and input_data[‘error’]:\n exit_code = 1\n stderr = input_data[‘error’]\n elif ‘stderr’ in input_data and input_data[‘stderr’]:\n exit_code = 1\n stderr = input_data[‘stderr’]\n elif ‘exitCode’ in input_data and input_data[‘exitCode’] != 0:\n exit_code = input_data[‘exitCode’]\n stderr = input_data.get(‘stderr’, ‘Command failed with non-zero exit code’)\n\n result = {\n ‘dag_id’: workflow_id_val,\n ‘status’: ‘success’ if exit_code == 0 else ‘failed’,\n ‘last_run_time’: datetime.utcnow().strftime(‘%Y-%m-%d %H:%M:%S’),\n ‘error’: stderr\n }\n\n except Exception as e:\n result = {\n ‘dag_id’: workflow_id_val,\n ‘status’: ‘failed’,\n ‘last_run_time’: datetime.utcnow().strftime(‘%Y-%m-%d %H:%M:%S’),\n ‘error’: f’Exception: {str(e)}',\n ‘debug_items’: str(item)\n }\n\n results.append({‘json’: result})\n\nreturn results”
},
“type”: “n8n-nodes-base.code”,
“typeVersion”: 1,
“position”: [600, -200],
“id”: “your-build-payload-node-id”,
“name”: “Build Payload”
},
],
“connections”: {
“Schedule Trigger”: {
“main”: [
[
{
“node”: “If”,
“type”: “main”,
“index”: 0
}
]
]
},
“If”: {
“main”: [
[
{
“node”: “Execute Command”,
“type”: “main”,
“index”: 0
}
],
[
{
“node”: “Stop and Error”,
“type”: “main”,
“index”: 0
}
]
]
},
“Execute Command”: {
“main”: [
[
{
“node”: “Build Payload”,
“type”: “main”,
“index”: 0
}
]
]
}
},
“settings”: {}
}

It’s still not in a code box so the quotes are broken. Could you try exporting the json and uploading it to G Drive?

please check this drive link and try to help me ASAP, I’m in hurry. Thanks

Hey, you are using old versions of the code node. Are you on a very old version of n8n or do you generate the workflow via AI?

If you can, add new code nodes from the UI (latest version is 2, visible in the settings tab for each node). Then, you can access the values like so:

  • JS: $workflow.id
  • Python: _workflow.id

Feel free to mark as solution if this helps

1 Like

Did I understand correctly - you are trying to define a variable in a code node and later access the same variable from another code node without defining it first?

Or are you having issues and can’t reference a value in the code node, that is arriving as input?