DocsBest Practices

    Best Practices

    Production-ready patterns for your LoyalPro integration

    12 min readAdvanced

    Quick Summary

    Secure your keys
    Cache responses
    Handle retries
    Validate data

    Security

    Never expose API keys in client-side code

    Always keep your API keys on the server. Use environment variables and never commit keys to version control.

    Do

    Store keys in environment variables: process.env.LOYALPRO_API_KEY

    Don't

    Hardcoding keys: const apiKey = 'sk_live_abc123'

    Use test mode for development

    Always use test API keys (sk_test_*) during development. Switch to live keys only in production.

    Do

    Use sk_test_* keys in development and staging environments

    Don't

    Using live keys during development or testing

    Implement proper authentication

    Secure your webhook endpoints and API routes with proper authentication and authorization checks.

    Do

    Verify webhook signatures before processing

    Don't

    Processing webhooks without signature verification

    Performance

    Implement caching strategies

    Cache frequently accessed data like customer profiles and point balances to reduce API calls and improve response times.

    Do

    Cache customer data with a 5-minute TTL

    Don't

    Making API calls on every page load

    Use pagination for large datasets

    When fetching lists of customers or transactions, always use pagination to avoid memory issues and slow responses.

    Do

    Fetch 100 records per page using cursor-based pagination

    Don't

    Fetching all records in a single request

    Process webhooks asynchronously

    Acknowledge webhooks immediately and process the data asynchronously using a job queue to prevent timeouts.

    Do

    Queue webhook data for background processing

    Don't

    Processing heavy operations in the webhook handler

    Error Handling

    Implement retry logic with exponential backoff

    When API calls fail, retry with increasing delays. This helps handle temporary network issues.

    Do

    Retry after 1s, 2s, 4s, 8s with jitter

    Don't

    Immediate retries in a tight loop

    Handle all error responses gracefully

    Check for and handle different error types appropriately. Log errors for debugging.

    Do

    Display user-friendly messages and log technical details

    Don't

    Showing raw API errors to end users

    Set appropriate timeouts

    Configure reasonable timeouts for API calls to prevent your application from hanging.

    Do

    Set 30-second timeout for API requests

    Don't

    No timeout configuration (infinite wait)

    Data Management

    Store customer IDs, not sensitive data

    Store LoyalPro customer IDs in your database rather than duplicating sensitive customer information.

    Do

    Store: { userId: 'your_id', loyalproId: 'cus_abc' }

    Don't

    Duplicating customer email, phone, and PII locally

    Use idempotency keys for mutations

    Include idempotency keys when creating or updating resources to prevent duplicate operations.

    Do

    Include X-Idempotency-Key header with unique value

    Don't

    Sending duplicate requests without idempotency protection

    Validate data before sending

    Validate all data client-side before making API calls to reduce errors and improve UX.

    Do

    Validate email format, phone numbers, and required fields

    Don't

    Sending unvalidated data directly to the API

    Production-Ready Example

    Here's an example that implements multiple best practices in a single integration:

    Best Practices Implementation
    // Best practices implementation
    const LoyalPro = require('@loyalpro/node-sdk');
    
    // 1. Use environment variables
    const loyalpro = new LoyalPro(process.env.LOYALPRO_API_KEY);
    
    // 2. Implement caching
    const cache = new Map();
    const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
    
    async function getCustomerWithCache(customerId) {
      const cacheKey = `customer:${customerId}`;
      const cached = cache.get(cacheKey);
      
      if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
        return cached.data;
      }
      
      const customer = await loyalpro.customers.retrieve(customerId);
      cache.set(cacheKey, { data: customer, timestamp: Date.now() });
      return customer;
    }
    
    // 3. Implement retry with exponential backoff
    async function withRetry(fn, maxRetries = 3) {
      for (let i = 0; i < maxRetries; i++) {
        try {
          return await fn();
        } catch (error) {
          if (i === maxRetries - 1) throw error;
          const delay = Math.pow(2, i) * 1000 + Math.random() * 1000;
          await new Promise(resolve => setTimeout(resolve, delay));
        }
      }
    }
    
    // 4. Use idempotency keys
    async function awardPointsSafely(customerId, points, orderId) {
      return withRetry(() => 
        loyalpro.points.award({
          customer_id: customerId,
          points: points,
        }, {
          idempotencyKey: `award-${orderId}`
        })
      );
    }

    Next Steps

    Was this page helpful?

    Help us improve our documentation