Skip to main content

Best Practices & Troubleshooting

This guide provides recommendations for optimizing your implementation of the Recommendations API and solutions for common issues.

Implementation Best Practices

Performance Optimization

  1. Request only what you need

    • Use expandProductDetails=false when you only need product IDs
    • Only fetch full details when displaying complete product information
  2. Implement caching strategies

    • Cache recommendations with appropriate TTL (Time To Live)
    • Consider different caching durations for different page types:
      • Home page: 5-15 minutes
      • Category pages: 15-30 minutes
      • Product pages: 1-5 minutes
      • Cart recommendations: No cache (real-time)
  3. Pagination and lazy loading

    • For routes with many widgets, consider lazy loading widgets as they scroll into view
    • Implement virtual scrolling for long lists of recommendations

User Experience

  1. Progressive enhancement

    • Display skeleton screens while recommendations are loading
    • Have fallback content ready if recommendations fail to load
    • Pre-fetch recommendations for likely next pages
  2. Error handling

    • Gracefully handle API errors so they don't break your UI
    • Provide meaningful fallbacks when recommendations are unavailable
  3. A/B testing

    • Test different recommendation strategies to find what works best for your audience
    • Measure engagement and conversion rates for different recommendation implementations

Integration Tips

  1. Server-side vs. client-side

    • For SEO purposes, consider server-side rendering of above-the-fold recommendations
    • Use client-side calls for personalized recommendations and below-the-fold content
  2. Authentication handling

    • Implement robust token refresh mechanisms
    • Have a plan for handling expired tokens
  3. Monitoring and analytics

    • Track recommendation impressions and clicks
    • Analyze which recommendation types drive the most engagement and conversions

Optimizing API Usage

Efficient Parameter Usage

ScenarioRecommended ParametersPurpose
PDP (basic)currentUrl, refIdBasic product-based recommendations
PDP (advanced)currentUrl, refId, expandProductDetails, showInStockOnly=falseFull product details including out-of-stock items
Cart PagecurrentUrl, productsInCart[], expandProductDetailsRecommendations based on cart items
Homepage (personalized)currentUrl, customerId, languageTag, currencyCodeLanguage and currency specific personalized recommendations
Category PagecurrentUrl, indexFilterValue, elementsFiltered recommendations for category/search pages

Common Combinations

// PDP - Similar products with pricing in local currency
const pdpParams = new URLSearchParams({
currentUrl: window.location.href,
refId: '12345',
expandProductDetails: 'true',
currencyCode: userCurrency,
languageTag: userLanguage
});

// Cart - Complete the look with only in-stock items
const cartParams = new URLSearchParams();
cartParams.append('currentUrl', window.location.href);
cartItems.forEach((item, index) => {
cartParams.append(`productsInCart[${index}]`, item);
});
cartParams.append('expandProductDetails', 'true');
cartParams.append('showInStockOnly', 'true');

// Personalized homepage recommendations
const homeParams = new URLSearchParams({
currentUrl: window.location.href,
customerId: userId,
expandProductDetails: 'true',
languageTag: userLanguage
});

Advanced Use Cases

Interstitial Recommendations

For showing recommendations between page navigation:

// Pre-fetch recommendations for likely next pages
function prefetchRecommendations(productId) {
const params = new URLSearchParams({
currentUrl: `https://example.com/product/${productId}`,
refId: productId
});

const pdpUrl = `https://<PA_END_POINT>/3.0/recommendations?${params.toString()}`;

// Create a hidden fetch that will be cached by the browser
fetch(pdpUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
priority: 'low' // Use low priority to avoid competing with critical resources
}).catch(err => {
// Silently fail - this is just a prefetch
console.debug('Prefetch failed:', err);
});
}

Multi-layered Personalization

Combine multiple personalization signals:

// Comprehensive personalization using multiple parameters
async function getHighlyPersonalizedRecommendations() {
const params = new URLSearchParams({
currentUrl: window.location.href,
customerId: userId,
expandProductDetails: 'true',
languageTag: userLanguage,
currencyCode: userCurrency
});

// Add products in cart
cart.items.forEach((item, index) => {
params.append(`productsInCart[${index}]`, item.id);
});

// Add customer segments
user.segments.forEach((segment, index) => {
params.append(`customerSegments[${index}]`, segment);
});

// Add search context if available
if (searchContext) {
params.append('searchQuery', searchContext);
}

// Add category filters if on a category page
if (categoryContext) {
params.append('indexFilterValue', `category:${categoryContext}`);
}

const url = `https://<PA_END_POINT>/3.0/recommendations?${params.toString()}`;
return fetch(url, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
}).then(response => response.json());
}

Troubleshooting

Common Issues and Solutions

IssuePossible CausesSolutions
No recommendations returnedInvalid route or URLVerify the currentUrl matches a configured route
Missing required parametersEnsure all required parameters for the scenario are provided
No matching products foundCheck that the provided refId exists and has recommendations
Out of stock filteringTry setting showInStockOnly=false
Incorrect language/currencyMissing locale parametersExplicitly set languageTag and currencyCode
Unsupported language/currencyVerify the requested language/currency is supported
Empty widget slotsMisconfigured widgetsCheck widget configuration in the Particular Audience portal
Insufficient product catalog dataEnsure products have all required attributes
Performance issuesToo many expanded productsLimit use of expandProductDetails or cache results
High latencyConsider server-side caching or CDN
Authorization errorsInvalid or expired tokenRefresh access token and retry

Error Response Examples

Invalid or Missing Parameter

{
"error": {
"code": "INVALID_PARAMETER",
"message": "Parameter 'currentUrl' is required",
"details": {
"parameter": "currentUrl"
}
}
}

Authentication Error

{
"error": {
"code": "UNAUTHORIZED",
"message": "Invalid or expired access token",
"details": {
"hint": "Please refresh your access token"
}
}
}

Route Not Found

{
"error": {
"code": "ROUTE_NOT_FOUND",
"message": "No matching route found for the provided URL",
"details": {
"url": "https://example.com/unknown-page"
}
}
}

Debugging Tips

  1. Enable verbose logging
// Enable detailed logging for recommendation calls
const DEBUG_MODE = true;

async function getRecommendations(url) {
if (DEBUG_MODE) {
console.log('Fetching recommendations:', url);
const startTime = performance.now();

try {
const response = await fetch(url, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
});

const data = await response.json();
const endTime = performance.now();

console.log(`Recommendations loaded in ${(endTime - startTime).toFixed(2)}ms`);
console.log('Response data:', data);

return data;
} catch (error) {
console.error('Recommendation API error:', error);
throw error;
}
} else {
// Standard non-verbose request
return fetch(url, {
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
}).then(response => response.json());
}
}
  1. Check route configuration

If recommendations are not appearing, verify in the Particular Audience portal that:

  • The route pattern matches your currentUrl
  • The widgets are correctly configured
  • The tactics are properly set up
  • Product catalog data is complete and up-to-date
  1. Test with minimal parameters

When troubleshooting, start with just the required parameters and gradually add optional ones to identify which parameter might be causing issues.

Support Resources

If you encounter persistent issues or have questions about the Recommendations API:

  1. Contact Particular Audience Support at support@particularaudience.com
  2. Include the following information for faster resolution:
    • API request URL (with sensitive data removed)
    • Response received
    • Expected behavior
    • Browser and device information (if client-side issue)
    • Timestamps of when the issue occurred