Petru Constantin este fondatorul DeviDevs și a proiectat platforma multi-agent pe care rulează firma, cu guardrails impuse în cod. Exemplele de cod sunt scrise pe documentația n8n 2.47 (linia stabilă, noiembrie 2026), Code node în JavaScript.
Automatizare onboarding clienți cu n8n: Workflow-uri complete de la început la sfârșit
Onboarding-ul clienților e un șir de pași ușor de automatizat: validezi înregistrarea, creezi contul, programezi emailurile de bun venit, urmărești etapele și predai clientul mai departe când onboarding-ul se termină. Ghidul construiește acest șir în n8n cu un trigger Webhook, noduri Code (JavaScript) și nodurile care apelează aplicația ta și providerul de email.
Arhitectura workflow-ului de onboarding
Handler trigger client nou
// n8n Code node (JavaScript), mode: Run Once for Each Item
// Input: the item produced by the Webhook node (payload under "body")
const data = $input.item.json.body ?? $input.item.json;
// Validate incoming customer data
const requiredFields = ['email', 'name', 'plan'];
const missingFields = requiredFields.filter(f => !data[f]);
if (missingFields.length > 0) {
throw new Error(`Missing required fields: ${missingFields.join(', ')}`);
}
const nameParts = String(data.name).trim().split(/\s+/);
const tiers = {
starter: 'basic',
professional: 'standard',
business: 'premium',
enterprise: 'enterprise'
};
// Normalize customer data
const customer = {
id: data.customer_id || `cust_${$execution.id}`,
email: String(data.email).toLowerCase().trim(),
firstName: nameParts[0],
lastName: nameParts.slice(1).join(' '),
fullName: data.name,
company: data.company || null,
plan: data.plan,
planTier: tiers[String(data.plan).toLowerCase()] || 'basic',
source: data.source || 'website',
signupDate: new Date().toISOString(),
timezone: data.timezone || 'UTC',
locale: data.locale || 'en',
metadata: {
utm_source: data.utm_source,
utm_medium: data.utm_medium,
utm_campaign: data.utm_campaign,
referrer: data.referrer
}
};
// Choose the onboarding path from the plan tier
const paths = {
enterprise: {
type: 'enterprise',
steps: ['sales_handoff', 'kickoff_call', 'custom_setup', 'training', 'go_live'],
assignedCSM: true,
durationDays: 30
},
premium: {
type: 'guided',
steps: ['welcome', 'setup_wizard', 'demo_call', 'training_videos', 'check_in'],
assignedCSM: false,
durationDays: 14
},
default: {
type: 'self_service',
steps: ['welcome', 'setup_wizard', 'email_sequence', 'in_app_guides'],
assignedCSM: false,
durationDays: 7
}
};
return {
json: {
customer,
onboarding: {
path: paths[customer.planTier] || paths.default,
startedAt: customer.signupDate,
currentStep: 0,
completedSteps: [],
status: 'started'
}
}
};Workflow de provizionare utilizatori
// n8n Code node (JavaScript), mode: Run Once for Each Item
// Builds the provisioning plan. The account, API keys and password-reset
// tokens are created by your application's backend (HTTP Request node after
// this one), not generated inside the workflow.
const { customer, onboarding } = $input.item.json;
const plan = String(customer.plan).toLowerCase();
const featuresByPlan = {
starter: ['basic_dashboard', 'email_support', 'api_access'],
professional: ['advanced_analytics', 'priority_support', 'api_access', 'integrations'],
business: ['custom_reports', 'dedicated_support', 'advanced_api', 'sso', 'audit_logs'],
enterprise: ['all_features', 'custom_development', 'sla', 'dedicated_infrastructure']
};
const limitsByPlan = {
starter: { users: 5, storage_gb: 10, api_calls_monthly: 10000 },
professional: { users: 25, storage_gb: 100, api_calls_monthly: 100000 },
business: { users: 100, storage_gb: 500, api_calls_monthly: 500000 },
enterprise: { users: -1, storage_gb: -1, api_calls_monthly: -1 } // -1 = no limit
};
const sampleTemplates = ['getting_started', 'basic_workflow'];
if (customer.planTier !== 'basic') sampleTemplates.push('advanced_automation', 'reporting_template');
if (customer.planTier === 'enterprise') sampleTemplates.push('enterprise_integration', 'compliance_workflow');
const tasks = [
{
type: 'create_account',
data: { customerId: customer.id, email: customer.email, name: customer.fullName, plan: customer.plan }
},
{
type: 'request_api_credentials',
data: { customerId: customer.id }
},
{
type: 'setup_initial_config',
data: {
features: featuresByPlan[plan] || featuresByPlan.starter,
limits: limitsByPlan[plan] || limitsByPlan.starter,
defaults: {
notifications: { email: true, in_app: true, slack: customer.planTier !== 'basic' },
security: { mfa_required: customer.planTier === 'enterprise', session_timeout: 3600 }
}
}
},
{
type: 'create_sample_data',
data: { customerId: customer.id, templates: sampleTemplates }
}
];
return { json: { customer, onboarding, tasks } };Secvența de email-uri de bun venit
// n8n Code node (JavaScript), mode: Run Once for Each Item
// "Onboarding Config" is a Set node with non-secret values:
// companyName, appUrl, docsUrl, supportEmail, bookingUrl.
// "account" is the response of the HTTP Request node that created the
// account in your backend (assumed here to contain passwordResetUrl).
const config = $('Onboarding Config').first().json;
const { customer, onboarding, account } = $input.item.json;
const spotlights = {
starter: { title: 'Automated Reminders', slug: 'reminders' },
professional: { title: 'Workflow Automation', slug: 'workflows' },
business: { title: 'Custom Dashboards', slug: 'dashboards' },
enterprise: { title: 'API Access', slug: 'api' }
};
const spotlight = spotlights[String(customer.plan).toLowerCase()] || spotlights.starter;
const emailSequence = [
{
day: 0, hour: null, // send right away
template: 'welcome',
subject: `Welcome to ${config.companyName}, ${customer.firstName}!`,
personalization: {
firstName: customer.firstName,
plan: customer.plan,
loginUrl: `${config.appUrl}/login`,
passwordResetUrl: account?.passwordResetUrl,
supportEmail: config.supportEmail
}
},
{
day: 1, hour: 10,
template: 'getting_started',
subject: `Get started with ${config.companyName}`,
personalization: {
firstName: customer.firstName,
quickStartUrl: `${config.appUrl}/quickstart`,
videoTutorialUrl: `${config.docsUrl}/tutorials/getting-started`
},
condition: { type: 'not_completed', milestone: 'first_login' }
},
{
day: 3, hour: 14,
template: 'feature_spotlight',
subject: `Did you know? ${spotlight.title}`,
personalization: {
firstName: customer.firstName,
feature: spotlight,
ctaUrl: `${config.appUrl}/features/${spotlight.slug}`
},
condition: { type: 'not_used', feature: spotlight.slug }
},
{
day: 7, hour: 10,
template: 'check_in',
subject: `How's it going, ${customer.firstName}?`,
personalization: {
firstName: customer.firstName,
feedbackUrl: `${config.appUrl}/feedback`,
bookCallUrl: onboarding.path.type !== 'self_service' ? config.bookingUrl : null
}
}
];
if (customer.planTier !== 'basic') {
emailSequence.push({
day: 5, hour: 10,
template: 'integrations',
subject: `Connect ${config.companyName} to your tools`,
personalization: { firstName: customer.firstName, integrationsUrl: `${config.appUrl}/integrations` }
});
}
// Send times in the customer's timezone (Luxon DateTime is available in the Code node)
const scheduledEmails = emailSequence
.sort((a, b) => a.day - b.day)
.map(email => {
let sendAt = DateTime.fromISO(customer.signupDate, { zone: customer.timezone });
if (!sendAt.isValid) sendAt = DateTime.fromISO(customer.signupDate, { zone: 'utc' });
sendAt = sendAt.plus({ days: email.day });
if (email.hour !== null) sendAt = sendAt.set({ hour: email.hour, minute: 0, second: 0, millisecond: 0 });
return {
...email,
scheduledAt: sendAt.toUTC().toISO(),
recipientEmail: customer.email,
recipientName: customer.fullName,
customerId: customer.id,
tags: ['onboarding', `day_${email.day}`, email.template]
};
});
return { json: { customer, onboarding, emailSequence: scheduledEmails } };Urmărire progres
// n8n Code node (JavaScript), mode: Run Once for All Items
// Runs once per customer: the workflow loads one customer and their stored
// progress ("Get Current Progress" node) before this node.
const customer = $input.first().json.customer;
const currentProgress = $('Get Current Progress').first()?.json || {};
const milestones = {
self_service: [
{ id: 'account_created', name: 'Account Created', weight: 10 },
{ id: 'first_login', name: 'First Login', weight: 15 },
{ id: 'profile_completed', name: 'Profile Completed', weight: 10 },
{ id: 'first_project', name: 'Created First Project', weight: 20 },
{ id: 'invited_team', name: 'Invited Team Member', weight: 15 },
{ id: 'used_core_feature', name: 'Used Core Feature', weight: 20 },
{ id: 'completed_tutorial', name: 'Completed Tutorial', weight: 10 }
],
guided: [
{ id: 'account_created', name: 'Account Created', weight: 5 },
{ id: 'first_login', name: 'First Login', weight: 10 },
{ id: 'profile_completed', name: 'Profile Completed', weight: 5 },
{ id: 'demo_completed', name: 'Demo Call Completed', weight: 15 },
{ id: 'first_project', name: 'Created First Project', weight: 15 },
{ id: 'integration_setup', name: 'Set Up Integration', weight: 15 },
{ id: 'invited_team', name: 'Invited Team', weight: 15 },
{ id: 'training_completed', name: 'Completed Training', weight: 20 }
],
enterprise: [
{ id: 'kickoff_completed', name: 'Kickoff Call Completed', weight: 10 },
{ id: 'requirements_gathered', name: 'Requirements Gathered', weight: 10 },
{ id: 'environment_setup', name: 'Environment Set Up', weight: 15 },
{ id: 'sso_configured', name: 'SSO Configured', weight: 10 },
{ id: 'data_migration', name: 'Data Migration Complete', weight: 15 },
{ id: 'team_training', name: 'Team Training Complete', weight: 15 },
{ id: 'pilot_launched', name: 'Pilot Launched', weight: 10 },
{ id: 'go_live', name: 'Go Live Complete', weight: 15 }
]
};
const onboardingType = currentProgress.onboardingType || 'self_service';
const customerMilestones = milestones[onboardingType] || milestones.self_service;
const completedMilestones = currentProgress.completedMilestones || [];
// Weights in each list add up to 100
const progressPercentage = customerMilestones
.filter(m => completedMilestones.includes(m.id))
.reduce((sum, m) => sum + m.weight, 0);
const pendingMilestones = customerMilestones.filter(m => !completedMilestones.includes(m.id));
const DAY_MS = 24 * 60 * 60 * 1000;
const daysSinceSignup = Math.floor((Date.now() - new Date(customer.signupDate).getTime()) / DAY_MS);
function calculateHealthScore() {
let score = 100;
// Penalize progress behind the expected pace (example pace: 10 points per day, capped at 70)
const expectedProgress = Math.min(daysSinceSignup * 10, 70);
if (progressPercentage < expectedProgress) score -= expectedProgress - progressPercentage;
// Penalize inactivity longer than 3 days
const daysSinceActivity = currentProgress.lastActivityAt
? Math.floor((Date.now() - new Date(currentProgress.lastActivityAt).getTime()) / DAY_MS)
: daysSinceSignup;
if (daysSinceActivity > 3) score -= (daysSinceActivity - 3) * 5;
if (completedMilestones.includes('invited_team')) score += 10;
if (completedMilestones.includes('integration_setup')) score += 10;
return Math.max(0, Math.min(100, score));
}
const healthScore = calculateHealthScore();
const interventions = [];
if (healthScore < 50) {
interventions.push({ type: 'low_health', action: 'personal_outreach', priority: 'high' });
}
if (!completedMilestones.includes('first_login') && daysSinceSignup >= 2) {
interventions.push({ type: 'no_login', action: 'reminder_email', priority: 'medium' });
}
if (currentProgress.stalledAt) {
interventions.push({
type: 'stalled_progress',
action: 'help_content',
priority: 'medium',
milestone: currentProgress.stalledAt
});
}
return [{
json: {
customerId: customer.id,
email: customer.email,
plan: customer.plan,
onboardingType,
startedAt: customer.signupDate,
lastActivityAt: currentProgress.lastActivityAt,
progress: {
percentage: progressPercentage,
completedMilestones,
pendingMilestones: pendingMilestones.map(m => m.id),
nextMilestone: pendingMilestones[0] || null,
totalMilestones: customerMilestones.length
},
healthScore,
interventionsNeeded: interventions,
status: progressPercentage >= 100 ? 'completed'
: progressPercentage >= 50 ? 'on_track'
: healthScore < 50 ? 'at_risk' : 'in_progress',
generatedAt: new Date().toISOString()
}
}];Ghiduri personalizate în aplicație
// n8n Code node (JavaScript), mode: Run Once for All Items
// Runs once per customer. "Get User Behavior" returns usage data from your app.
const customer = $input.first().json.customer;
const behavior = $('Get User Behavior').first()?.json || {};
const guideTemplates = {
welcome_tour: {
id: 'welcome_tour',
type: 'product_tour',
steps: [
{ target: '#dashboard', title: 'Your Dashboard', content: 'Your key metrics, {{firstName}}.', position: 'bottom' },
{ target: '#create-button', title: 'Create Your First Project', content: 'Start your first project here.', position: 'right' },
{ target: '#settings-menu', title: 'Settings', content: 'Personalize the workspace for {{company}}.', position: 'left' }
],
dismissible: true
},
feature_discovery: {
id: 'feature_discovery',
type: 'tooltip_sequence',
steps: [
{ target: '#analytics-tab', title: 'Analytics', content: 'Explore your data.', position: 'bottom', planTiers: ['standard', 'premium', 'enterprise'] },
{ target: '#automations', title: 'Automations', content: 'Automate repetitive tasks.', position: 'right' }
]
},
empty_state_prompt: {
id: 'empty_state_prompt',
type: 'modal',
content: { title: "Let's get started", body: 'Create your first project to get going.', cta_action: 'open_create_modal' }
},
integration_prompt: {
id: 'integration_prompt',
type: 'banner',
content: { title: 'Connect your tools', body: 'Integrate the apps you already use.', cta_action: 'navigate_integrations' }
},
upgrade_prompt: {
id: 'upgrade_prompt',
type: 'modal',
content: { title: 'More capacity', body: "You're using {{usagePercentage}}% of your plan limits.", cta_action: 'navigate_pricing' }
}
};
const signupDate = new Date(customer.signupDate);
const daysSinceSignup = Math.floor((Date.now() - signupDate.getTime()) / (24 * 60 * 60 * 1000));
const completed = behavior.completedGuides || [];
const dismissed = behavior.dismissedGuides || [];
const selected = [];
if ((behavior.loginCount ?? 0) <= 1 && !completed.includes('welcome_tour')) {
selected.push({ guide: guideTemplates.welcome_tour, priority: 1, reason: 'First login' });
}
if ((behavior.projectsCreated ?? 0) >= 1 && !completed.includes('feature_discovery')) {
const guide = structuredClone(guideTemplates.feature_discovery);
guide.steps = guide.steps.filter(s => !s.planTiers || s.planTiers.includes(customer.planTier));
selected.push({ guide, priority: 2, reason: 'First project completed' });
}
if ((behavior.projectsCreated ?? 0) === 0 && daysSinceSignup >= 1) {
selected.push({ guide: guideTemplates.empty_state_prompt, priority: 1, reason: 'No projects after 24 hours' });
}
if ((behavior.totalMinutesInApp ?? 0) >= 30 && (behavior.integrationsCount ?? 0) === 0 && !dismissed.includes('integration_prompt')) {
selected.push({ guide: guideTemplates.integration_prompt, priority: 3, reason: 'No integrations after 30 minutes' });
}
if ((behavior.usagePercentage ?? 0) >= 80 && customer.planTier !== 'enterprise') {
selected.push({ guide: guideTemplates.upgrade_prompt, priority: 2, reason: 'High usage' });
}
// Fill placeholders in every string of the guide (walks the object, no JSON string surgery)
const values = {
firstName: customer.firstName ?? '',
company: customer.company || 'your team',
plan: customer.plan ?? '',
usagePercentage: String(behavior.usagePercentage ?? '')
};
function fill(node) {
if (typeof node === 'string') {
return node.replace(/\{\{(\w+)\}\}/g, (match, key) => (key in values ? values[key] : match));
}
if (Array.isArray(node)) return node.map(fill);
if (node && typeof node === 'object') {
return Object.fromEntries(Object.entries(node).map(([k, v]) => [k, fill(v)]));
}
return node;
}
const guides = selected
.sort((a, b) => a.priority - b.priority)
.map(s => ({ ...fill(s.guide), priority: s.priority, reason: s.reason }));
return [{
json: {
customerId: customer.id,
guides,
behavior,
generatedAt: new Date().toISOString()
}
}];Finalizare și predare
// n8n Code node (JavaScript), mode: Run Once for All Items
// Input: one progress report per item (output of the progress tracker)
const DAY_MS = 24 * 60 * 60 * 1000;
const maxDays = { self_service: 14, guided: 30, enterprise: 60 };
function decide(report, isComplete, isTimedOut) {
if (isComplete) {
return {
action: 'complete_onboarding',
tasks: [
{ type: 'send_completion_email', template: 'onboarding_complete' },
{ type: 'update_customer_stage', stage: 'active' },
{ type: 'trigger_nps_survey', delay_days: 7 },
{ type: 'schedule_success_call', condition: 'premium_or_higher' }
]
};
}
if (isTimedOut) {
return {
action: 'escalate_stalled',
tasks: [
{ type: 'notify_csm', priority: 'high' },
{ type: 'send_reengagement_email', template: 'stuck_onboarding' },
{ type: 'create_support_ticket', reason: 'Stalled onboarding' }
]
};
}
if (report.interventionsNeeded.length > 0) {
return {
action: 'intervention_required',
tasks: report.interventionsNeeded.map(i => ({ ...i, type: `handle_${i.type}` }))
};
}
return { action: 'continue_monitoring', tasks: [] };
}
function recommendations(report) {
const list = [];
if (report.progress.percentage < 50) {
list.push({ type: 'engagement', message: 'Consider personalized outreach' });
}
if (!report.progress.completedMilestones.includes('invited_team')) {
list.push({ type: 'expansion', message: 'Encourage team invitations' });
}
if (report.healthScore < 70) {
list.push({ type: 'support', message: 'Proactive support call recommended' });
}
return list;
}
return $input.all().map(item => {
const report = item.json;
const daysSinceStart = Math.floor((Date.now() - new Date(report.startedAt).getTime()) / DAY_MS);
const isComplete = report.progress.percentage >= 100;
const isTimedOut = !isComplete && daysSinceStart > (maxDays[report.onboardingType] || 14);
return {
json: {
customerId: report.customerId,
email: report.email,
plan: report.plan,
onboardingType: report.onboardingType,
finalStatus: isComplete ? 'completed' : isTimedOut ? 'timed_out' : 'in_progress',
completionPercentage: report.progress.percentage,
healthScore: report.healthScore,
completedMilestones: report.progress.completedMilestones,
pendingMilestones: report.progress.pendingMilestones,
daysToComplete: isComplete ? daysSinceStart : null,
nextSteps: decide(report, isComplete, isTimedOut),
recommendations: recommendations(report),
reportedAt: new Date().toISOString()
}
};
});Bune practici
Design de onboarding
- Personalizează pe segment: Clienți diferiți au nevoie de fluxuri de onboarding diferite
- Urmărește milestone-urile: Definește metrici clare de succes pentru fiecare etapă de onboarding
- Intervino devreme: Monitorizează scorurile de sănătate și acționează înainte ca clienții să plece
- Iterează continuu: Îmbunătățește pe baza ratelor de finalizare și a feedback-ului
Sfaturi de automatizare
- Folosește secvențe de email condiționate: fiecare email programat are o condiție (de exemplu „not completed: first_login”) pe care un pas de verificare o evaluează înainte de trimitere
- Distanțează punctele de contact cu nodul Wait sau cu un Schedule Trigger care preia emailurile al căror
scheduledAta trecut - Combină ghidurile din aplicație cu emailul, ca aceeași etapă să nu fie împinsă de două ori, pe două canale
- Salvează fiecare eveniment de onboarding cu ID-ul clientului, ca să vezi unde se blochează clienții
Onboarding-ul automatizat cu n8n asigură experiențe consistente și personalizate care contribuie la succesul și retenția clienților.
Surse oficiale
- Code node | n8n Docs
- Data structure | n8n Docs
- Output of other nodes | n8n Docs
- Handling dates with Luxon | n8n Docs
- n8n 2.0 breaking changes | n8n Docs
Pe același subiect: Automatizare suport clienti cu n8n, Automatizare AI: Zapier vs Make vs n8n - Pe care sa o alegi?, n8n automatizare CRM: pattern-uri HubSpot si Salesforce. Mai multe articole în categoria n8n Automation.