Skip to content

Common Issues & Troubleshooting

Solutions to common problems when working with the CyferWall Engage Backend notification system.

🚨 Template Issues

Template Not Found

Error: Template not found: template-id

Causes: - Template ID doesn't exist - Typo in template ID - Template file missing or corrupted

Solutions:

// Check available templates
const templates = notifications.templates()
console.log('Available templates:', templates.map(t => t.id))

// Verify template exists
const info = notifications.info('your-template-id')
if (!info.success) {
  console.error('Template issue:', info.error)
}

File checks:

# Check if template files exist
ls -la templates/notifications/customer/
ls -la templates/notifications/html/

# Test template structure
node src/util/notifications/test-structure.js

Template Rendering Failed

Error: Template rendering failed: Missing required variable 'variableName'

Causes: - Missing required variables - Wrong variable types - Invalid enum values

Solutions:

// Check template requirements first
const info = notifications.info('template-id')
console.log('Required variables:', info.data.required)
console.log('Optional variables:', info.data.optional)

// Ensure all required variables are provided
const data = {
  caseNumber: 'CW-2025-001',
  customerName: 'John Doe',
  // ... include all required variables
}

// Test before sending
const test = await notifications.test('template-id', data)
if (!test.success) {
  console.error('Template test failed:', test.error)
}

Handlebars Syntax Errors

Error: Parse error on line X: Expecting 'ID', got 'INVALID'

Common Issues:

{{!-- WRONG: JavaScript syntax in template --}}
{{new Date().toISOString()}}

{{!-- RIGHT: Use helper functions --}}
{{now "YYYY-MM-DD HH:mm:ss"}}

{{!-- WRONG: Complex logic --}}
{{if urgency === "HIGH" && priorityScore > 80}}

{{!-- RIGHT: Simple comparisons --}}
{{#if (and (eq urgency "HIGH") (gt priorityScore 80))}}

Solutions: - Use Handlebars helpers instead of JavaScript - Simplify complex logic - Validate template syntax:

# Test template compilation
node src/util/notifications/diagnose-templates.js template-id

🔌 Service Issues

Service Not Initialized

Error: Service not initialized

Causes: - Template directory not found - Permission issues reading templates - Handlebars compilation errors

Solutions:

// Check service status
if (!notifications.isReady()) {
  console.error('Notification service failed to initialize')

  // Check template directory
  const fs = require('fs')
  const path = require('path')

  const templateDir = path.join(process.cwd(), 'templates/notifications')
  if (!fs.existsSync(templateDir)) {
    console.error('Template directory not found:', templateDir)
  }
}

File permission checks:

# Check template directory permissions
ls -la templates/notifications/
chmod -R 755 templates/notifications/

# Verify template files are readable
file templates/notifications/customer/*.json

Database Connection Issues

Error: Database connection failed

Solutions:

# Check DATABASE_URL format
echo $DATABASE_URL

# Test database connection
npx prisma studio

# Check if database is accessible
psql "$DATABASE_URL" -c "SELECT NOW();"

Common fixes:

# Quote the DATABASE_URL in .env
DATABASE_URL="postgresql://user:password@localhost:5432/db"

# Regenerate Prisma client
npx prisma generate

# Run pending migrations
npx prisma migrate deploy

📧 Email Provider Issues

Email Delivery Failed

Error: Email failed: Authentication failed

Solutions:

# Check email provider configuration
echo $RESEND_API_KEY
echo $SENDGRID_API_KEY

# Test email provider settings
curl -X POST "https://api.resend.com/emails" \
  -H "Authorization: Bearer $RESEND_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "from": "test@yourdomain.com",
    "to": ["test@example.com"],
    "subject": "Test Email",
    "text": "This is a test email"
  }'

Invalid Email Format

Error: Invalid email address format

Solutions:

// Validate email format before sending
const isValidEmail = (email) => {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
}

if (!isValidEmail(customer.email)) {
  console.error('Invalid email format:', customer.email)
  return
}

await notifications.email('template-id', customer.email, data)

📱 SMS Provider Issues

SMS Delivery Failed

Error: SMS failed: Invalid phone number format

Solutions:

// Format phone number properly
const formatPhoneNumber = (phone) => {
  // Remove all non-digits
  const digits = phone.replace(/\D/g, '')

  // Add country code if missing (assuming US)
  if (digits.length === 10) {
    return `+1${digits}`
  } else if (digits.length === 11 && digits.startsWith('1')) {
    return `+${digits}`
  }

  return phone // Return original if can't format
}

const formattedPhone = formatPhoneNumber(customer.phone)
await notifications.sms(formattedPhone, message)

🔗 Webhook Issues

Webhook Timeout

Error: Webhook failed: Connection timeout

Solutions:

// Add timeout and retry logic
const sendWebhookWithRetry = async (url, data, retries = 3) => {
  for (let i = 0; i < retries; i++) {
    try {
      const result = await notifications.webhook(url, data)
      if (result.success) return result
    } catch (error) {
      console.error(`Webhook attempt ${i + 1} failed:`, error)
      if (i < retries - 1) {
        await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)))
      }
    }
  }
  throw new Error('Webhook failed after all retries')
}

Webhook SSL Issues

Error: Webhook failed: SSL certificate verification failed

Solutions:

# Test webhook endpoint manually
curl -X POST "https://webhook-endpoint.com/webhook" \
  -H "Content-Type: application/json" \
  -d '{"test": "data"}' \
  -v

# Check SSL certificate
openssl s_client -connect webhook-endpoint.com:443 -servername webhook-endpoint.com

🐛 Debug Mode

Enable Debug Logging

# Set debug environment variables
export DEBUG=notification:*
export LOG_LEVEL=debug
export NODE_ENV=development

# Start server with debug mode
npm run dev

Debug Specific Components

import logger from '@/logger'

// Enable debug for notifications
logger.level = 'debug'

// Test with debug output
const result = await notifications.test('template-id', data)
logger.debug('Template test result:', result)

Diagnostic Scripts

# Test all templates
node src/util/notifications/test-comprehensive.js

# Test template structure
node src/util/notifications/test-structure.js

# Test specific template
node src/util/notifications/diagnose-templates.js template-id

# Test notification sending
node src/util/notifications/test-notification.js

📊 Performance Issues

Slow Template Rendering

Issue: Templates take too long to render

Solutions:

// Profile template rendering
const start = Date.now()
const result = await notifications.test('template-id', data)
const duration = Date.now() - start

if (duration > 1000) {
  console.warn(`Slow template rendering: ${duration}ms for ${templateId}`)
}

// Optimize templates:
// 1. Reduce complex Handlebars logic
// 2. Minimize HTML size
// 3. Cache compiled templates (done automatically)
// 4. Reduce variable processing

Memory Usage

Issue: High memory usage with many templates

Solutions:

// Monitor memory usage
const usage = process.memoryUsage()
console.log('Memory usage:', {
  rss: Math.round(usage.rss / 1024 / 1024) + 'MB',
  heapUsed: Math.round(usage.heapUsed / 1024 / 1024) + 'MB'
})

// Restart service periodically if needed
// Templates are cached but can be cleared if necessary

🔧 Environment Issues

Development vs Production

Common differences:

# Development
NODE_ENV=development
DATABASE_URL="postgresql://localhost:5432/engage_dev"
NOTIFICATION_FROM_EMAIL="dev@cyferwall.com"

# Production  
NODE_ENV=production
DATABASE_URL="postgresql://prod-server:5432/engage_prod"
NOTIFICATION_FROM_EMAIL="noreply@cyferwall.com"

Missing Environment Variables

# Check all required variables
node -e "
const required = [
  'DATABASE_URL',
  'RESEND_API_KEY',
  'NOTIFICATION_FROM_EMAIL'
]
required.forEach(key => {
  if (!process.env[key]) {
    console.error('Missing:', key)
  } else {
    console.log('✅', key)
  }
})
"

📞 Getting Help

Before Asking for Help

  1. Check the logs - Most issues have clear error messages
  2. Run diagnostic scripts - Use built-in testing tools
  3. Verify configuration - Double-check environment variables
  4. Test templates - Use the template testing functions

Gathering Information

When reporting issues, include:

# System information
node --version
npm --version

# Environment check
echo "NODE_ENV: $NODE_ENV"
echo "DATABASE_URL: ${DATABASE_URL:0:20}..." # Don't expose full URL

# Test results
node src/util/notifications/test-structure.js 2>&1 | head -20

# Recent logs
tail -50 logs/app.log | grep -i error

Internal Support Channels

  • Slack: #engage-backend-support
  • Email: engineering@cyferwall.com
  • Documentation: This internal documentation
  • Code Review: GitHub issues and PRs

🚀 Quick Fixes

Template Issues

# Reset template cache and test
rm -rf .template-cache/
node src/util/notifications/test-comprehensive.js

Service Issues

# Restart with clean state
rm -rf node_modules/.cache/
npm run build
npm run dev

Database Issues

# Reset database connection
npx prisma generate
npx prisma migrate reset --force

Environment Issues

# Reload environment
source .env
npm run dev

Still having issues? Debug Guide | FAQ | Ask on Slack #engage-backend-support