Tips > Building Workflows

Create Reusable Utility Functions at the Top of Code Nodes

When your Code node grows beyond 20-30 lines, organize it by defining utility functions at the top.

TipIntermediate2 min read

When your Code node grows beyond 20-30 lines, organize it by defining utility functions at the top. This makes the main logic readable and lets you reuse parsing, formatting, and validation logic within the same node.

Real-world example: A data sync workflow processes contact records that need phone number normalization, email validation, and name formatting before upserting to a CRM.

// Mode: Run Once for All Items

// --- Utility Functions ---
function normalizePhone(raw) {
  if (!raw) return null;
  const digits = raw.replace(/\D/g, '');
  if (digits.length === 10) return `+1${digits}`;
  if (digits.length === 11 && digits.startsWith('1')) return `+${digits}`;
  return digits.length >= 10 ? `+${digits}` : null;
}

function isValidEmail(email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email ?? '');
}

function titleCase(str) {
  if (!str) return '';
  return str.toLowerCase().replace(/\b\w/g, c => c.toUpperCase());
}

function buildFullName(first, last, company) {
  const name = [first, last].filter(Boolean).map(titleCase).join(' ');
  return name || company || 'Unknown';
}

// --- Main Logic ---
return $input.all().map(item => {
  const c = item.json;
  return {
    json: {
      fullName: buildFullName(c.firstName, c.lastName, c.company),
      email: isValidEmail(c.email) ? c.email.toLowerCase().trim() : null,
      phone: normalizePhone(c.phone),
      company: c.company?.trim() || null,
      isValid: isValidEmail(c.email) && !!normalizePhone(c.phone),
    }
  };
});
```text
If you find yourself copying utility functions across workflows, consider creating a shared Code node at the start of your workflow that attaches helpers to `$workflow` static data (see n8n's static data feature).

**Related:** [Use Edit Fields in "Map Each" Mode for Simple Renames](../data-transformation/01-use-edit-fields-in-map-each-mode-for-simple-renames.md) | [Configure Payload Size and Binary Data Mode for Large Files](../performance-and-large-files/01-configure-payload-size-and-binary-data-mode-for-large-files.md)

Want this running in your stack?

I build production n8n and Cloudflare automation for teams — the same engineering behind HarperFlow. Fixed-price, escrow-protected, US-based.