REST API Troubleshooting Guide

This guide provides solutions for common issues you might encounter when working with the PersonalizeWP REST API endpoints.

Common Issues and Solutions

Unable to Retrieve UID from Local Storage

Issue: The visitor's UID is not found in local storage, causing API calls to fail.

Solutions:

  1. Verify PersonalizeWP is properly installed: Ensure that PersonalizeWP is correctly installed and activated on your site.
  2. Check local storage directly: Use browser developer tools to check if the pwp_tracked_user item exists in local storage:
// Browser console
console.log(localStorage.getItem('pwp_tracked_user'));
  1. Add defensive coding: Always include checks for the presence of the UID before making API calls:
const PWP = localStorage.getItem('pwp_tracked_user') || '';
const UID = (PWP) ? JSON.parse(PWP).id : null;

if (!UID) {
  console.warn('PersonalizeWP user ID not found. User may be new or using privacy mode.');
  // Show fallback content or default behavior
  return;
}
  1. Implement a delay: If you're calling the API immediately after page load, the PersonalizeWP tracking script may not have had time to create the UID yet. Consider adding a short delay:
setTimeout(() => {
  // Your API call code here
}, 1000);  // 1 second delay

API Requests Return Errors

Issue: Requests to the PersonalizeWP API endpoints fail with errors.

Solutions:

  1. Check REST API availability: Verify that the WordPress REST API is functioning properly:
fetch('/wp-json/')
  .then(response => response.json())
  .then(data => console.log('REST API is working', data))
  .catch(error => console.error('REST API issue', error));
  1. Verify endpoint URLs: Ensure you are using the correct endpoint URLs:
const baseURL = window.pwpSettings?.root || '/wp-json/';
const namespace = 'personalizewp/v1/';
const endpoint = 'visitor-activities';  // or 'visitor-segments'

const fullURL = `${baseURL}${namespace}${endpoint}`;
console.log('API URL:', fullURL);
  1. Check request format: Verify that your request body is properly formatted:
// For activities endpoint
const requestBody = { 
  uid: UID,
  filters: [  // optional
    { activity_type: 'view' },
    { object_type: 'product' }
  ]
};

// For segments endpoint
const requestBody = { uid: UID };

console.log('Request body:', JSON.stringify(requestBody));
  1. Test with Postman or cURL: Test the API endpoints directly using API testing tools.
  2. Check browser console: Look for CORS or other network-related errors in the browser console.

No Data Returned from API

Issue: API calls succeed but return empty arrays or unexpected data.

Solutions:

  1. Verify data exists: Confirm that activities or segments exist for the visitor in PersonalizeWP:
    • Check the PersonalizeWP dashboard for the visitor's activities
    • Verify segment conditions are set up correctly
    • Make sure the visitor has performed actions that would trigger activity recording
  2. Check filters: If using filters with the /visitor-activities endpoint, ensure they're not too restrictive:
// Instead of this (might be too restrictive)
const filters = [
  { activity_type: 'view' },
  { object_type: 'product' },
  { url: 'specific-url' }
];

// Try this (less restrictive)
const filters = [
  { activity_type: 'view' }
];
  1. Log raw response: Inspect the complete API response:
fetch(apiUrl, requestOptions)
  .then(response => response.text())  // Get raw text instead of JSON
  .then(text => {
    console.log('Raw response:', text);
    return text ? JSON.parse(text) : [];
  })
  .then(data => console.log('Parsed data:', data))
  .catch(error => console.error('Error:', error));

Performance Issues

Issue: API calls are slow or causing performance problems.

Solutions:

  1. Implement caching: Cache API responses to reduce repeated calls:
// Simple caching implementation
const pwpCache = {
  activities: null,
  segments: null,
  timestamp: 0,
  isExpired: function() {
    return Date.now() - this.timestamp > 300000; // 5 minutes
  }
};

async function getCachedActivities() {
  if (!pwpCache.activities || pwpCache.isExpired()) {
    // Fetch from API
    pwpCache.activities = await fetchActivitiesFromAPI();
    pwpCache.timestamp = Date.now();
  }
  return pwpCache.activities;
}
  1. Limit API calls: Only call the API when needed and avoid duplicate calls:
    • On specific pages rather than every page
    • After user interactions instead of on page load
    • When the recommended content is in the viewport
  2. Optimize request size: Only request the data you need:
// Use specific filters to reduce response size
const filters = [
  { activity_type: 'view' },
  { object_type: 'product' }
];

Integration with Other Plugins

Issue: Conflicts with other plugins or custom code.

Solutions:

  1. Avoid global variable conflicts: Use namespaced variables and functions:
// Instead of this
const UID = JSON.parse(localStorage.getItem('pwp_tracked_user')).id;

// Do this
const PWP = {
  init: function() {
    this.UID = this.getUserId();
    // Other initialization
  },
  getUserId: function() {
    const userData = localStorage.getItem('pwp_tracked_user');
    return userData ? JSON.parse(userData).id : null;
  }
};
PWP.init();
  1. Check for script loading order: Ensure your code runs after PersonalizeWP is initialized:
// Listen for PersonalizeWP initialization
document.addEventListener('pwp_initialized', function() {
  // Now it's safe to use PersonalizeWP data
  initYourPersonalizedBlocks();
});

// Fallback if event doesn't fire
setTimeout(function() {
  initYourPersonalizedBlocks();
}, 2000);
  1. Debug plugin conflicts: Temporarily disable other plugins to identify conflicts.

Debugging Tips

Console Logging for APIs

Add comprehensive logging to track API calls and responses:

async function fetchVisitorActivities(uid, filters = []) {
  console.group('PersonalizeWP API Call: Visitor Activities');
  console.log('UID:', uid);
  console.log('Filters:', filters);
  
  try {
    const response = await fetch(`${baseURL}${namespace}visitor-activities`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ uid, filters })
    });
    
    console.log('Response status:', response.status);
    
    if (!response.ok) {
      throw new Error(`API error: ${response.status}`);
    }
    
    const data = await response.json();
    console.log('Response data:', data);
    console.groupEnd();
    return data;
  } catch (error) {
    console.error('API call failed:', error);
    console.groupEnd();
    return [];
  }
}

Network Monitor

Use your browser's network monitor (DevTools) to examine API requests and responses:

  1. Open browser DevTools (F12 or right-click > Inspect)
  2. Go to the Network tab
  3. Filter requests by "Fetch/XHR"
  4. Perform the action that triggers the API call
  5. Examine the request and response details

Error Handling

Implement robust error handling in your code:

function displayProductsForYou() {
  const container = document.getElementById('pwp-products-container');
  
  if (!container) {
    console.error('Products container not found');
    return;
  }
  
  getVisitorUID()
    .then(uid => {
      if (!uid) {
        throw new Error('No visitor UID found');
      }
      return fetchVisitorSegments(uid);
    })
    .then(segments => getProductRecommendations(segments))
    .then(products => renderProducts(products, container))
    .catch(error => {
      console.error('PersonalizeWP error:', error);
      showFallbackProducts(container);
    });
}

function showFallbackProducts(container) {
  // Show default products if personalization fails
  container.innerHTML = '<p>Loading top products...</p>';
  // Fetch and display popular products
}

Getting Additional Help

If you continue to experience issues with the PersonalizeWP REST API:

  1. Check Documentation: Review the complete PersonalizeWP documentation at help.personalizewp.com

    Support Channels:

    • Submit a support ticket through the PersonalizeWP website
    • Post in the PersonalizeWP community forums
    • Contact our support team at support@personalizewp.com

      Provide Detailed Information:

    • PersonalizeWP version
    • WordPress version
    • Theme and active plugins
    • Browser and device information
    • Steps to reproduce the issue
    • Error messages from the browser console
    • Network request and response logs

By following this troubleshooting guide, you should be able to resolve most common issues with the PersonalizeWP REST API. For complex scenarios, don't hesitate to reach out to our support team for personalized assistance.

Still need help? Contact Us Contact Us