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
-
Request only what you need
- Use
expandProductDetails=false
when you only need product IDs - Only fetch full details when displaying complete product information
- Use
-
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)
-
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
-
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
-
Error handling
- Gracefully handle API errors so they don't break your UI
- Provide meaningful fallbacks when recommendations are unavailable
-
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
-
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
-
Authentication handling
- Implement robust token refresh mechanisms
- Have a plan for handling expired tokens
-
Monitoring and analytics
- Track recommendation impressions and clicks
- Analyze which recommendation types drive the most engagement and conversions
Optimizing API Usage
Efficient Parameter Usage
Scenario | Recommended Parameters | Purpose |
---|---|---|
PDP (basic) | currentUrl , refId | Basic product-based recommendations |
PDP (advanced) | currentUrl , refId , expandProductDetails , showInStockOnly=false | Full product details including out-of-stock items |
Cart Page | currentUrl , productsInCart[] , expandProductDetails | Recommendations based on cart items |
Homepage (personalized) | currentUrl , customerId , languageTag , currencyCode | Language and currency specific personalized recommendations |
Category Page | currentUrl , indexFilterValue , elements | Filtered 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
Issue | Possible Causes | Solutions |
---|---|---|
No recommendations returned | Invalid route or URL | Verify the currentUrl matches a configured route |
Missing required parameters | Ensure all required parameters for the scenario are provided | |
No matching products found | Check that the provided refId exists and has recommendations | |
Out of stock filtering | Try setting showInStockOnly=false | |
Incorrect language/currency | Missing locale parameters | Explicitly set languageTag and currencyCode |
Unsupported language/currency | Verify the requested language/currency is supported | |
Empty widget slots | Misconfigured widgets | Check widget configuration in the Particular Audience portal |
Insufficient product catalog data | Ensure products have all required attributes | |
Performance issues | Too many expanded products | Limit use of expandProductDetails or cache results |
High latency | Consider server-side caching or CDN | |
Authorization errors | Invalid or expired token | Refresh 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
- 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());
}
}
- 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
- 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:
- Contact Particular Audience Support at support@particularaudience.com
- 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