HƯỚNG DẪN

Cách thêm heartbeat ping vào workflow n8n một cách an toàn

Ngày đăng · Cập nhật

Mã

Script này dựng một workflow nhỏ có hai ping, kiểm tra các quy tắc trên, rồi in ra JSON để import vào n8n.

js
// Build an n8n workflow with heartbeat pings on side branches.
const PING_URL = "https://example.com/ping"; // replace with your monitor URL

const link = (node) => ({ node, type: "main", index: 0 });

function ping(name, position, event, countExpr) {
  return {
    name, position,
    type: "n8n-nodes-base.httpRequest",
    typeVersion: 4.2,                 // always explicit
    executeOnce: true,                // one ping per run, not one per item
    onError: "continueRegularOutput", // a monitor outage cannot fail the run
    parameters: {
      method: "POST",
      url: PING_URL,
      sendBody: true,
      bodyParameters: { parameters: [
        { name: "event", value: event },
        { name: "count", value: countExpr },
      ] },
      options: { timeout: 5000 },
    },
  };
}

function code(name, position, jsCode) {
  return { name, position, type: "n8n-nodes-base.code", typeVersion: 2, parameters: { jsCode } };
}

const workflow = {
  name: "Heartbeat example",
  nodes: [
    { name: "Start", position: [0, 0], type: "n8n-nodes-base.manualTrigger", typeVersion: 1, parameters: {} },
    code("Work", [220, 0], "return [{ json: { n: 1 } }, { json: { n: 2 } }];"),
    code("Use data", [440, 0], "return $input.all();"),
    ping("Ping start", [220, 200], "start", "0"),
    ping("Ping finish", [440, 200], "finish", "={{ $input.all().length }}"),
  ],
  // Each ping is a second target of the same output, with nothing after it.
  connections: {
    Start: { main: [[link("Work"), link("Ping start")]] },
    Work: { main: [[link("Use data"), link("Ping finish")]] },
  },
  settings: {},
};

function checkWorkflow(wf) {
  const problems = [];
  const names = new Set();
  for (const { name } of wf.nodes) names.add(name);
  for (const { name, typeVersion, executeOnce, onError, parameters } of wf.nodes) {
    if (typeof typeVersion !== "number") problems.push(`${name}: missing typeVersion`);
    if (parameters.url !== PING_URL) continue; // rules below are for ping nodes only
    if (wf.connections[name]) problems.push(`${name}: ping must be a dead end`);
    if (executeOnce !== true) problems.push(`${name}: executeOnce must be true`);
    if (onError !== "continueRegularOutput") problems.push(`${name}: onError must continue`);
  }
  for (const [from, { main }] of Object.entries(wf.connections))
    for (const outputs of main)
      for (const { node } of outputs)
        if (!names.has(node)) problems.push(`${from}: unknown target ${node}`);
  return problems;
}

const problems = checkWorkflow(workflow);
if (problems.length) {
  console.error(problems.join("\n"));
  process.exitCode = 1;
} else {
  console.log(JSON.stringify(workflow, null, 2));
}

Vì sao xảy ra

Node HTTP Request trả ra phản hồi nó nhận được, không phải các item đi vào. Nếu ping nằm giữa hai node, node phía sau nhận câu trả lời của máy chủ giám sát thay vì dữ liệu của bạn. Lần chạy vẫn có thể xanh trong khi nó xử lý sai dữ liệu.

Bẫy thứ hai nằm ở JSON khi import. Theo bài gốc, node thiếu typeVersion bị import thành một phiên bản khác. Node Code hiện lại đoạn mã mẫu mặc định, và lần chạy lỗi với "Problem in node – Unknown error".

Các bước

  1. Thay PING_URL bằng địa chỉ endpoint giám sát của bạn.
  2. Chạy script bằng Node 22 và lưu JSON in ra vào một tệp.
  3. Trong n8n, mở một workflow mới và chọn Import from File.
  4. Kiểm tra rằng mỗi node ping nằm trên nhánh phụ, không có node nào phía sau.
  5. Thay node "Work" và "Use data" bằng các node thật của bạn, giữ nguyên các nhánh ping.

Lưu ý

  • Các phiên bản ở đây (Code node 2, HTTP Request 4.2) lấy từ một báo cáo trên n8n 2.49. Để xác nhận bản của bạn, hãy thêm node trong trình soạn thảo, export và đọc typeVersion.
  • Nếu không bật Execute Once, một lần chạy có 12 item sẽ gửi 12 ping.
  • Nếu máy chủ giám sát cần token, hãy lưu nó trong credential của n8n, không đặt trong URL hay tệp JSON.
  • Bài gốc cũng cho biết việc retry một execution lỗi đã chạy lại bước ghi bị lỗi và tạo bản ghi trùng. Lần retry có execution id mới, nên đừng dùng id đó làm khóa idempotency.

Thấy trên: n8n Community ·

Dịch vụ liên quan: Workflow tự động n8n, Make, Zapier