DEV Community

anassBld
anassBld

Posted on

n8n lead-to-CRM workflow with error alerts

This is a lead form to CRM workflow in n8n. Two things go wrong with most n8n lead workflows. The same person ends up in the CRM three times, and when a node fails nobody notices until a sales rep asks where the leads went.

So I built a small one that handles both and ran it on my laptop so I could break it on purpose. n8n 2.42.5 in Docker, Mailpit catching the emails, and an n8n Data Table standing in for the CRM. You can swap in HubSpot or Pipedrive later, the logic stays the same. Everything below is fake test data.

For the break I used a common one. There's a Code node right after the webhook that does b.email.trim() and the run fails with "Cannot read properties of undefined (reading 'trim')". In the execution the webhook node has a green check, the Code node is red, and the lead never makes it to the CRM. The reason is that the Webhook node puts the form fields inside body (headers and query are next to it), and the code was reading json instead of json.body. One line to fix, but you have to know the run failed first.

So the error workflow is the part I'd add first to any lead flow. When my broken copy failed, ops got an email with the workflow name, the failed node, the error and a link to the execution. I opened the link, the webhook output showed the fields under body, I changed the line and sent the same lead again and it went through.

Duplicates were the other thing I wanted to test. I sent Dana's lead twice, the second time with "Following up, still urgent" in the message. If you write to the CRM without checking first, you get two contacts and Dana gets two auto-replies. I look the email up first and upsert on it, so the second submission updated the same row, the submissions count went to 2 and no new emails were sent.

The scoring is plain rules, no LLM. Budget, business email or free mail, a company name, and a few buying words in the message. Every point gets written into a reasons column, so when someone asks why a lead is hot you can show them.

Below is each node with its settings and the code from the two Code nodes, in the order the lead goes through them.

Webhook and validation

The Webhook node takes POST /webhook/lead with response mode "Using Respond to Webhook node", so the form gets its answer after the CRM write.

The Code node after it reads from body, lowercases the email (the lookup later matches exact strings, so Dana@BrightPath.com and dana@brightpath.com would be two people) and throws if there's no usable email or name:

// Form fields arrive under body. Reject anything we can't follow up on.
const b = $input.first().json.body || {};
const email = String(b.email ?? '').trim().toLowerCase();
const name = String(b.name ?? '').trim();

if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
  throw new Error(`Invalid lead: email "${b.email ?? ''}" is missing or malformed`);
}
if (!name) throw new Error('Invalid lead: name is required');

return [{ json: {
  email,
  name,
  company: String(b.company ?? '').trim(),
  budget: Number(b.budget) || 0,
  message: String(b.message ?? '').trim(),
} }];
Enter fullscreen mode Exit fullscreen mode

Throwing is on purpose. A lead with no email can't be followed up, and the throw triggers the error workflow, so you hear about it.

Look the email up first

"Find existing lead" is a Data Table node: operation Get, filter email equals {{ $json.email }}, limit 1.

Turn on Always Output Data in its settings. Without it a new email returns zero items and the run just ends there, no error. With it, the next node gets one empty item {} and can tell new from repeat.

Score with rules you can read

const lead = $('Validate & normalize').first().json;
const existing = $input.first().json; // {} when the email is new

const FREE_MAIL = ['gmail.com','yahoo.com','hotmail.com','outlook.com','icloud.com','aol.com','proton.me','gmx.com','freemail.example.com'];  // last one = demo stand-in
const KEYWORDS = ['urgent','asap','crm','integration','automate','automation','quote','hubspot','salesforce','pipedrive'];

let score = 0;
const reasons = [];
if (lead.budget >= 5000)      { score += 40; reasons.push('budget >= 5000 (+40)'); }
else if (lead.budget >= 1000) { score += 20; reasons.push('budget >= 1000 (+20)'); }
else                          { reasons.push('budget < 1000 (+0)'); }

const domain = lead.email.split('@')[1];
if (FREE_MAIL.includes(domain)) reasons.push(`free mail ${domain} (+0)`);
else { score += 25; reasons.push(`company domain ${domain} (+25)`); }

if (lead.company) { score += 5; reasons.push('company given (+5)'); }

const hits = KEYWORDS.filter(k => lead.message.toLowerCase().includes(k)).slice(0, 3);
if (hits.length) { score += hits.length * 10; reasons.push(`keywords ${hits.join(', ')} (+${hits.length * 10})`); }

const tier = score >= 60 ? 'hot' : score >= 30 ? 'warm' : 'cold';
const isDuplicate = Boolean(existing.id);

return [{ json: {
  ...lead, score, tier,
  reasons: reasons.join('; '),
  status: isDuplicate ? 'duplicate' : 'new',
  submissions: (existing.submissions || 0) + 1,
} }];
Enter fullscreen mode Exit fullscreen mode

Change the numbers to match how your sales team thinks.

Note the $('Validate & normalize') call. After the lookup, $input is the CRM row (or {}), not the lead, so the lead is read by node name.

Upsert, not insert

"Upsert CRM row" is the same Data Table node with operation Upsert, matched on email, columns mapped from the input. New email, new row. Repeat email, same row updated.

After four test leads (hot, cold, the hot one again, and a bad email) the table has two rows. Dana's shows status: duplicate and submissions: 2, and the reasons column shows how each score was built. Her score is 80 here but 100 in the alert email, because the second submission got re-scored and the upsert overwrote the row.

Reply to the form, then send email

"Respond to Webhook" returns { ok, email, score, tier, status } right after the upsert, so the form isn't waiting on SMTP.

An IF node checks status equals new. Duplicates stop there. New leads get an auto-reply, and a second IF sends hot ones to sales with the score and reasons in the body.

The error workflow

Two nodes. An Error Trigger and an email (or Slack) node:

Subject: n8n FAILED: {{ $json.workflow.name }} at "{{ $json.execution.lastNodeExecuted }}"

Workflow: {{ $json.workflow.name }}
Failed node: {{ $json.execution.lastNodeExecuted }}
Error: {{ $json.execution.error.message }}
Open the execution: {{ $json.execution.url }}
Enter fullscreen mode Exit fullscreen mode

Then in the lead workflow's settings, pick it under Error workflow. The bad test lead sent one with Invalid lead: email "not-an-email" is missing or malformed, and the broken copy sent the reading 'trim' one.

What I'd change for a real setup

  • Swap the Data Table nodes for the real CRM node and keep the email match on the upsert.
  • Send the alert to Slack if that's where the team looks.

If you'd rather have someone fix or build this for you, I do it as a Fiverr gig: https://www.fiverr.com/kabilanass/fix-or-build-n8n-workflow-automation-for-leads-to-crm-with-error-alerts

Top comments (0)