# Changelog Source: https://docs.glood.ai/ai-image-video-editor/changelog Release notes and updates for Glood AI Image & Video Editor ## Release History Stay up to date with the latest features, improvements, and bug fixes for Glood AI Image & Video Editor. *** ### November 6, 2024 #### 🎨 Improved Video Generation **Enhanced First Frame Generation with AI** We've significantly improved video generation quality by implementing AI-powered first frame generation. This enhancement ensures: * **Better Starting Point**: Videos now begin with an optimized first frame that sets the tone for the entire generation * **Improved Consistency**: More consistent video quality across different product types * **Enhanced Motion**: Smoother transitions from the initial frame throughout the video * **Higher Accuracy**: Better interpretation of video prompts resulting in more accurate outputs **Impact**: This improvement particularly benefits product videos where the initial presentation is crucial for engagement. Users should see noticeably better video quality, especially for fashion and apparel products. > [!NOTE] > > **Pro Tip**: With this enhancement, your existing video prompts may produce even better results. Consider regenerating key product videos to take advantage of the improved AI models. *** ## Coming Soon We're actively working on exciting new features and improvements: > [card] Additional Format Support > > Support for more video and image output formats including JPG, WEBP, and MOV > [card] Batch Export Options > > Download multiple videos and images in a single archive > [card] Advanced Editing Controls > > Fine-tune video generation with advanced parameter controls > [card] API Enhancements > > Extended API capabilities for headless and custom integrations *** ## Feedback & Suggestions We value your input! If you have feature requests or suggestions for improvements: * **Email**: [support@glood.ai](mailto:support@glood.ai) * **Feature Requests**: Share your ideas and we'll consider them for future releases > [!TIP] > > **Stay Updated**: Bookmark this page to stay informed about new features and improvements. Major updates are typically announced here first. # FAQ Source: https://docs.glood.ai/ai-image-video-editor/faq Frequently asked questions about Glood AI Image & Video Editor ## Frequently Asked Questions Find answers to common questions about using Glood AI Image & Video Editor. If you don't see your question here, feel free to reach out to our support team. ### General Questions > [accordion] What is Glood AI Image & Video Editor? > > Glood AI Image & Video Editor is an AI-powered platform that helps Shopify Plus merchants create professional product videos and edit product images at scale. It offers three main capabilities: > > * **AI Video Generation**: Transform static product photos into engaging videos > * **Intelligent Image Editing**: AI-powered background generation, removal, resizing, and enhancement > * **Workflow Automation**: Create reusable workflows that process multiple products automatically > > The tool is designed specifically for e-commerce, making it easy to maintain consistent, high-quality visual content across your entire product catalogue. > [accordion] Who can use the AI Image & Video Editor? > > The AI Image & Video Editor is available to **Shopify Plus merchants** who have: > > * An active Shopify Plus store > * Products with images in your catalogue > * The Glood AI Image & Video Editor app installed from the Shopify App Store > > No technical skills or coding knowledge is required. The tool features an intuitive, no-code interface that anyone on your team can use. > [accordion] Do I need technical skills to use this? > > No! The AI Image & Video Editor is designed to be user-friendly and requires no technical or design skills. > > The interface is point-and-click, with intuitive controls for: > > * Selecting products > * Configuring video and image settings > * Building editing workflows > * Previewing and publishing results > > If you can navigate your Shopify admin, you can use this tool. We also provide detailed guides and preset options to help you get started quickly. > [accordion] What types of videos can I generate? > > You can generate professional product showcase videos from your existing product images. These videos are perfect for: > > **Use Cases**: > > * Social media content (Instagram, TikTok, Facebook) > * Product page enhancements > * Email marketing campaigns > * Paid advertising > * Product demonstrations > > **Format Options**: > > * **Aspect Ratios**: 16:9 (Landscape), 9:16 (Portrait/Stories), 1:1 (Square) > * **Resolutions**: 1080p (Full HD), 720p (HD), 480p (SD) > * **Duration**: Customizable length (typically 5-15 seconds) > * **Audio**: Optional AI-generated audio > > You can describe the style and motion you want through text prompts, and the AI will generate videos that bring your products to life. > [accordion] What image editing operations are available? > > The platform offers comprehensive AI-powered image editing tools: > > **Core Operations**: > > * **Background Generation**: Create contextual, professional backgrounds that complement your products > * **Background Removal**: Automatically remove backgrounds with precision for clean product shots > * **Smart Resizing & Cropping**: Intelligently resize images while maintaining focus on product features > * **Image Enhancement**: Apply AI filters and quality improvements > * **Format Optimization**: Convert and optimize images for web performance > > **Presets**: > > * **Fashion Preset**: Optimized for clothing and accessories > * **Furniture Preset**: Designed for home goods and furniture > * **Custom Operations**: Build your own editing pipeline by chaining multiple operations > > All operations can be combined and applied to multiple products simultaneously through batch processing. ### Credits & Pricing > [accordion] How does the credit system work? > > Glood AI Image & Video Editor uses a flexible credit-based pricing model: > > * **Credits are consumed** when you generate videos or edit images > * **Credit cost varies** based on your settings: > * Video duration and resolution > * Image editing complexity and number of operations > * Output quality settings > > **Key Benefits**: > > * Pay only for what you use > * No monthly subscriptions > * Purchased credits valid for 1 year > * Clear cost estimates before processing > > Before generating any content, you'll see the exact credit cost, helping you manage your budget effectively. > [accordion] How much do credits cost? > > Credits are available in flexible packs that scale with your needs: > > **Credit Packs**: > > * Packs start from as low as $20, $50, and go up from there > * Multiple pack sizes available to fit different usage levels > * Perfect for both small batches and large-scale operations > > **Volume Discounts**: > > * Higher value packs come with attractive discounts > > * The more credits you purchase, the better value you get > > * Ideal for merchants with extensive catalogues or ongoing content needs > > > [!NOTE] > > > > **Best Value**: Larger credit packs offer significant savings per credit. Choose a pack size that matches your planned usage to maximize value. > > **Credit Validity**: > > * Purchased credits are valid for **1 year** from the date of purchase > * Free welcome credits expire after **30 days** > [accordion] Do I get free credits? > > Yes! **Every new installation receives \$20 in free credits** as a welcome bonus. > > This allows you to: > > * Test the platform with real products > * Generate sample videos and edited images > * Explore different features and settings > * Evaluate quality before purchasing additional credits > > **Important**: Free welcome credits expire after **30 days**, so be sure to use them to explore the platform's capabilities during your trial period. The free credits work exactly like purchased credits and can be used for any video generation, image editing, or workflow automation task. > [accordion] How can I see credit costs before generating? > > The platform shows **real-time credit estimates** before you commit to any generation: > > **For Video Generation**: > > * The "Credit Estimate" section shows the exact cost based on your selected duration, resolution, and aspect ratio > * Updates automatically as you adjust settings > > **For Image Editing**: > > * Credit cost is calculated based on the number of images and operations in your pipeline > * Displayed before you start processing > > **Dashboard Monitoring**: > > * View your current credit balance on the main dashboard > * Click "**+ Purchase Credits**" anytime to add more > * Track usage history in the "**Credit Usage**" section > > This transparency helps you make informed decisions and control costs effectively. > [accordion] What happens if I run out of credits? > > If you run out of credits: > > 1. **Processing stops** - Any queued or in-progress jobs will pause > > 2. **You'll be notified** - The system will alert you that credits are needed > > 3. **Purchase more anytime** - Click "**+ Purchase Credits**" from the dashboard > > 4. **Work resumes automatically** - Once credits are added, processing continues from where it left off > > > [!TIP] > > > > **Pro Tip**: Set a reminder to check your credit balance regularly, especially if you're running large batch operations or scheduled workflows. This ensures uninterrupted processing. > [accordion] Can I get a refund on unused credits? > > **All credits are non-refundable once purchased.** > > **Refund Policy**: > > * Credits cannot be refunded or exchanged for cash > * No refunds are provided for unused credits > * Purchased credits are valid for 1 year from purchase date > * Free credits expire after 30 days > > **If You Have Issues**: > If you experience technical problems that prevent you from using credits properly, please contact our support team at [support@glood.ai](mailto:support@glood.ai). We'll work with you to resolve any technical issues. > [accordion] What happens if generation fails or produces an error? > > If video generation or image editing fails due to system errors, you won't lose credits: > > **Error Handling**: > > * **System Errors**: Credits are **not charged** if processing fails due to technical errors on our end > * **Automatic Refund**: If credits were deducted for a failed generation, they are **automatically refunded** to your account > * **Error Messages**: You'll receive clear error messages explaining what went wrong > > **Important Distinction**: > > * βœ… **Technical Errors** (system failures, processing errors, timeouts): Credits refunded > * ❌ **Unsatisfactory Results** (output not matching expectations, quality concerns): Credits **not refunded** > > **Unsatisfactory Output**: > If the generated content completes successfully but doesn't meet your expectations: > > * Credits are **not refunded** for completed generations > * You can regenerate with different settings or prompts (new credits required) > * Use the preview and estimate features to minimize unexpected results > > **Best Practices to Avoid Wasted Credits**: > > * Review credit estimates before generating > > * Test with lower quality/resolution settings first > > * Use specific, detailed prompts for video generation > > * Start with single products before batch processing > > > [!TIP] > > > > **Pro Tip**: If you're consistently experiencing generation failures or technical errors, contact [support@glood.ai](mailto:support@glood.ai) with details about your workflow. We can help troubleshoot and ensure smooth processing. ### Video Generation > [accordion] How long does it take to generate a video? > > Video generation typically takes **2-5 minutes**, depending on several factors: > > **Factors Affecting Processing Time**: > > * Video duration (longer videos take more time) > * Resolution quality (1080p takes longer than 480p) > * Complexity of the prompt > * Current server load > > **Background Processing**: > > * You don't need to stay on the page while videos generate > > * Close the browser and check back later > > * Your videos continue processing in the background > > * You'll be able to view completed videos when you return > > > [!NOTE] > > > > **Tip**: You'll see a progress indicator showing the completion percentage. The system typically provides accurate time estimates once processing begins. > [accordion] What video quality settings are available? > > The platform offers flexible quality settings to match your needs: > > **Resolution Options**: > > * **1080p (Full HD)**: Highest quality, best for product pages and premium marketing > * **720p (HD)**: Balanced quality and file size, great for most uses > * **480p (SD)**: Smaller file size, suitable for thumbnails or quick previews > > **Aspect Ratios**: > > * **16:9 (Landscape)**: Perfect for YouTube, website banners, and horizontal displays > * **9:16 (Portrait)**: Optimized for Instagram Stories, TikTok, and mobile-first content > * **1:1 (Square)**: Ideal for Instagram feed posts and Facebook > > **Additional Settings**: > > * **Duration**: Set video length in seconds (typically 5-15 seconds) > * **Generate Audio**: Toggle to add AI-generated background audio > > Higher quality settings consume more credits but deliver superior results. The credit estimate updates in real-time as you adjust settings. > [accordion] Can I customize the video style? > > Yes! You can guide the AI video generation through **text prompts**: > > **Video Prompt Feature**: > > * Describe the scene, style, and actions you want in the video > * Be specific about movement, mood, and presentation > * The AI interprets your prompt to generate matching video content > > **Example Prompts**: > > * *"Create a realistic video of this person moving to show the dress flowing naturally"* > * *"Show the product rotating slowly against a clean white background"* > * *"Generate a dynamic video with the model walking to showcase the outfit"* > > **Tips for Effective Prompts**: > > * Be specific about the type of motion you want > * Mention the background or environment if relevant > * Describe the mood or style (elegant, energetic, minimal, etc.) > * Keep prompts clear and focused (0-5000 characters) > > You can regenerate videos with different prompts until you achieve the desired result. > [accordion] What happens to generated videos? > > Generated videos are automatically integrated with your Shopify store: > > **Auto-Publishing**: > > * Videos are **automatically published** to your Shopify product media > * They appear in the product's media gallery alongside images > * Customers can view them on product pages immediately > > **Additional Options**: > > * **Download**: Save videos to your device for use elsewhere (social media, ads, etc.) > * **Regenerate**: Create a new version with different settings or prompts > * **Remove from Product**: Unlink the video if you no longer want it displayed > > **Video Details**: > > * View publication status and creation timestamp > * Check credit usage for each video > * Access the video file anytime from your dashboard > > You maintain full control over where and how your generated videos are used. > [accordion] Can I generate videos for multiple products at once? > > Yes! The platform supports **batch video generation**: > > **How It Works**: > > 1. Click "**Pick Product**" and select multiple products or variants > 2. Configure video settings that will apply to all selected products > 3. Write a prompt that works for the product category > 4. Review the total credit estimate for all videos > 5. Generate all videos with one click > > **Benefits**: > > * Save time by processing multiple products simultaneously > * Ensure consistent video style across product collections > * Ideal for seasonal updates or new product launches > > **Use Cases**: > > * Generate videos for an entire collection > * Create matching videos for product variants > * Bulk-process catalog additions > > For even more automation, consider using **Workflows** to schedule batch video generation for specific product collections. ### Image Editing > [accordion] Can I edit multiple images at the same time? > > Absolutely! **Batch image editing** is one of the platform's key strengths: > > **How Batch Editing Works**: > > 1. Select multiple products and their images > 2. Build an editing operations pipeline > 3. Apply the same operations to all selected images at once > 4. Monitor progress for the entire batch > 5. Review and publish all edited images together > > **Benefits**: > > * **Time Savings**: Edit hundreds of images in the time it would take to edit one manually > * **Consistency**: Ensure uniform visual standards across your catalogue > * **Efficiency**: Perfect for seasonal updates, rebranding, or catalogue maintenance > > **Example Use Cases**: > > * Remove backgrounds from all products in a collection > > * Generate matching backgrounds for product variants > > * Resize all images to consistent dimensions > > * Apply enhancement filters to an entire category > > > [!TIP] > > > > **Pro Tip**: Use workflows to save your batch editing operations as templates. Apply them to new products automatically as your catalogue grows. > [accordion] What's the difference between presets and custom operations? > > The platform offers both quick presets and fully customizable editing pipelines: > > **Presets** (Quick & Easy): > > * **Fashion Preset**: Pre-configured operations optimized for clothing and accessories > * Background generation with fashion-appropriate scenes > * Smart cropping for apparel > * Color enhancement for fabric > * **Furniture Preset**: Designed for home goods and furniture > * Contextual room backgrounds > * Lighting adjustments for interiors > * Perspective correction > > Presets are one-click solutions that apply a series of optimized operations automatically. > > **Custom Operations** (Full Control): > > * Build your own editing pipeline by selecting and ordering specific operations > * Chain multiple operations together (e.g., Remove Background β†’ Generate Background β†’ Resize β†’ Enhance) > * Configure parameters for each operation individually > * Save custom pipelines as reusable workflows > > **When to Use Each**: > > * Use **presets** for quick, standard edits that don't require customization > * Use **custom operations** when you need specific results or unique editing sequences > [accordion] Can I chain multiple editing operations together? > > Yes! The **operations pipeline** lets you combine multiple edits into a single workflow: > > **How It Works**: > > 1. Add operations to your pipeline in the desired sequence > 2. Each operation processes the output of the previous one > 3. Configure parameters for each step > 4. Preview the entire pipeline before processing > 5. Execute all operations with one click > > **Example Pipeline Sequences**: > > **Clean Product Shots**: > > 1. Remove Background > 2. Resize to 2000x2000px > 3. Enhance Quality > 4. Optimize Format (WEBP) > > **Lifestyle Images**: > > 1. Remove Background > 2. Generate Lifestyle Background > 3. Smart Crop > 4. Color Enhancement > > **Social Media Ready**: > > 1. Remove Background > 2. Generate Solid Color Background > 3. Resize to 1080x1080px > 4. Add Padding > > The pipeline approach ensures consistent results and saves you from manually running each operation separately. > [accordion] Will the edited images replace my original images? > > **No, your original images are always preserved.** The editing process is non-destructive: > > **How It Works**: > > * Edited images are created as **new files** > * Original images remain untouched in your Shopify media library > * You decide whether to publish edited versions or keep originals > > **Publishing Options**: > > * **Add to Product**: Edited images are added alongside originals > * **Replace**: Manually choose to replace originals (you control this) > * **Download Only**: Keep edited images locally without affecting your store > > **Safety Features**: > > * Original product images are never deleted automatically > * You can always revert to originals if needed > * Download both versions for comparison > > This approach gives you complete flexibility to test and compare results before making any changes to your live product pages. > [accordion] What image formats are supported? > > **Current Supported Formats**: > > **Input Formats**: > > * PNG (with transparency) > * JPG/JPEG > * WEBP > * Other common image formats > > **Output Format**: > > * **PNG** - All edited images are exported in PNG format for maximum quality and transparency support > > **Coming Soon**: > We're actively working on adding support for more output formats, including JPG, WEBP, and other formats. These will be available in future updates. > > **Image Requirements**: > > * Maximum file size: Typically 20MB per image > > * Recommended minimum resolution: 800x800px > > * Best results with high-quality source images > > > [!NOTE] > > > > **Quality First**: We currently export all images in PNG format to ensure the highest quality output with full transparency support, which is essential for product images with removed or generated backgrounds. ### Workflows & Automation > [accordion] What are workflows and why should I use them? > > **Workflows are automated processes** that apply video generation or image editing operations to multiple products automatically: > > **What They Do**: > > * Combine multiple operations into reusable templates > * Apply consistent editing to products based on rules (collections, tags, etc.) > * Run on-demand or on automatic schedules > * Process products in bulk without manual intervention > > **Benefits**: > > * **Consistency**: Maintain uniform visual standards across your entire catalogue > * **Time Savings**: Set up once, run automatically forever > * **Scalability**: Process thousands of products effortlessly > * **Flexibility**: Create different workflows for different product types > > **Example Use Cases**: > > * Automatically generate videos for all new products added to a collection > * Schedule weekly background removal for uploaded images > * Apply seasonal backgrounds to specific product categories > * Create social-media-ready images for products tagged "featured" > > Workflows turn repetitive tasks into automated processes, freeing your team to focus on strategy and creativity. > [accordion] Can I schedule workflows to run automatically? > > Yes! Workflows support both **on-demand** and **scheduled** execution: > > **On-Demand Workflows**: > > * Trigger manually whenever you need them > * Run for specific products you select > * Execute immediately > * Perfect for one-time bulk operations > > **Scheduled Workflows** (Automated): > > * Set up recurring schedules (daily, weekly, monthly) > * Define specific times and timezones > * Automatically apply to new products matching your filters > * Process products in the background without manual intervention > > **Example Schedules**: > > * **Daily**: Process all products added in the last 24 hours > * **Weekly**: Apply seasonal backgrounds every Monday morning > * **Monthly**: Generate new videos for products with updated images > > **Configuration**: > > * Choose trigger frequency > * Set product filters (collections, tags, date added) > * Define workflow steps and settings > * Activate or pause workflows anytime > > Scheduled workflows ensure your visual content stays fresh and consistent without requiring constant attention. > [accordion] How do I apply workflows to specific product collections? > > Workflows include powerful **product filtering** options to target exactly the right products: > > **Filter Options**: > > * **Collections**: Apply to all products in specific collections > * **Tags**: Target products with certain tags (e.g., "new-arrival", "featured", "sale") > * **Product Type**: Filter by product type (e.g., "Dresses", "Furniture") > * **Vendor**: Apply to products from specific vendors > * **Date Added**: Process products added after a certain date > * **Availability**: Include/exclude products based on inventory status > > **How to Set Up**: > > 1. Create a new workflow > 2. In the workflow configuration, define your product filters > 3. Preview which products match your filters > 4. Configure the operations to apply > 5. Set the trigger (on-demand or scheduled) > 6. Activate the workflow > > **Example Filters**: > > * *Collection = "Summer Collection" AND Tag = "featured"* > * *Product Type = "Dresses" AND Date Added > Last 7 days* > * *Vendor = "Brand X" AND Availability = In Stock* > > This targeting ensures workflows only affect the products you intend, preventing unwanted changes to your catalogue. > [accordion] Can I reuse workflows? > > Yes! Workflows are fully reusable and can be saved as templates: > > **Template Features**: > > * **Save Workflows**: Any workflow can be saved as a reusable template > * **Duplicate Workflows**: Clone existing workflows and modify them > * **Share Configurations**: Use the same editing pipeline across different product sets > > **How to Reuse**: > > 1. Create a workflow with your desired operations > 2. Save it with a descriptive name > 3. Duplicate the workflow for similar use cases > 4. Modify filters or settings as needed > 5. Activate multiple variations > > **Example Reuse Scenarios**: > > * Create a "Background Removal" template for different collections > * Save a "Video Generation - Portrait" template for various product types > * Build seasonal templates (Summer Backgrounds, Winter Themes, etc.) > > **Benefits**: > > * Faster setup for new campaigns > * Consistent application of proven editing sequences > * Easy experimentation with variations > * Simplified team collaboration > > Templates make it easy to scale your visual content strategy without reinventing workflows every time. ### Technical & Troubleshooting > [accordion] My video generation is taking longer than expected. What should I do? > > Video generation times can vary, but here's what to know: > > **Normal Processing Times**: > > * **Standard**: 2-5 minutes for most videos > * **Complex Prompts**: Up to 10 minutes for detailed scenes > * **High Resolution**: 1080p videos may take longer than 480p > > **What to Do If It's Taking Too Long**: > > 1. **Wait a Bit Longer**: Processing times can vary based on server load > 2. **Check Your Connection**: Ensure you have stable internet > 3. **Background Processing**: You can close the pageβ€”your video continues processing > 4. **Check Status**: Return to the dashboard to see if processing completed > > **When to Contact Support**: > > * Video has been processing for over 30 minutes > > * Processing is stuck at the same percentage > > * You receive an error message > > > [!TIP] > > > > **Pro Tip**: The progress indicator typically provides accurate estimates once processing is 10-20% complete. If it stalls, wait 5 minutes and refresh the page. > > Contact [support@glood.ai](mailto:support@glood.ai) if processing consistently takes longer than expected. > [accordion] The generated video doesn't match my prompt. How can I improve it? > > If your video doesn't match expectations, try these prompt improvement techniques: > > **Writing Better Prompts**: > > **Be Specific**: > > * ❌ *"Show the product"* > * βœ… *"Show the dress on the model with gentle movement to display fabric flow"* > > **Describe the Motion**: > > * ❌ *"Make a video"* > * βœ… *"Create a video with the model turning 360 degrees to showcase the outfit from all angles"* > > **Mention Background/Scene**: > > * ❌ *"Nice background"* > * βœ… *"Generate a video with a clean white studio background and professional lighting"* > > **Specify Style**: > > * ❌ *"Make it look good"* > * βœ… *"Create an elegant, slow-motion video with smooth transitions and minimal movement"* > > **Common Issues & Fixes**: > > * **Too much motion**: Use words like "gentle", "subtle", "slow" > * **Wrong focus**: Specify what should be emphasized > * **Poor quality**: Ensure source images are high resolution > > **Regeneration**: > > * Use the **Regenerate** button to try different prompts > * Adjust video settings (duration, resolution, aspect ratio) > * Credits are only charged for completed videos you keep > > Experimentation is keyβ€”try different prompt variations to find what works best for your products. > [accordion] Why is my image editing failing? > > Image editing can fail for several reasons. Here's how to troubleshoot: > > **Common Issues**: > > **1. File Size or Format**: > > * Ensure images are under 20MB > * Use supported formats (PNG, JPG, WEBP) > * Check that files aren't corrupted > > **2. Image Quality**: > > * Source images should be at least 800x800px > * Avoid extremely low-resolution images > * Heavily compressed images may produce poor results > > **3. Complex Operations**: > > * Some operation combinations may conflict > * Try simplifying your pipeline > * Run operations one at a time to identify issues > > **4. Product/Image Not Found**: > > * Ensure products still exist in Shopify > * Check that images haven't been deleted > * Refresh the product selection > > **Resolution Steps**: > > 1. Verify source image quality and format > 2. Simplify the operations pipeline > 3. Try editing one image at a time to isolate the issue > 4. Check error messages for specific guidance > 5. Contact support with error details if problem persists > > **Error Messages**: > > * Read error messages carefullyβ€”they often indicate the specific issue > * Screenshot errors to share with support if needed > > If you consistently encounter failures, reach out to [support@glood.ai](mailto:support@glood.ai) with details about your workflow and product types. > [accordion] Can I cancel a video or image generation in progress? > > **Cancellation Policy**: > > **While Processing**: > > * You can attempt to cancel jobs while they're in the queue or early in processing > * Look for a "Cancel" or "Stop" button on the processing screen > * Success depends on how far along processing has progressed > > **Credit Refunds**: > > * **Cancelled before processing starts**: Full credit refund > * **Cancelled during processing**: Partial refund based on completion percentage > * **Completed processing**: No refund (you receive the generated content) > > **Background Processing**: > > * Closing the browser doesn't cancel processing > * Jobs continue in the background even if you navigate away > * Return to the dashboard to check status and cancel if needed > > **Best Practices**: > > * Review credit estimates carefully before starting > * Use preview features when available > * Test with single products before batch processing > * Start with lower resolution/quality to test prompts and settings > > If you accidentally start a large batch operation, cancel it immediately to minimize credit usage. > [accordion] Where do the generated videos and images appear in Shopify? > > Generated content is automatically integrated with your Shopify product media: > > **Location in Shopify**: > > 1. Go to **Products** in your Shopify admin > 2. Select the product you generated content for > 3. Scroll to the **Media** section > 4. Your videos and images appear in the media gallery > > **Auto-Publishing**: > > * Videos and images are **automatically published** by default > * They appear alongside existing product images > * Customers see them on product pages immediately > * You can reorder media to control display priority > > **Manual Publishing Option**: > > * If you prefer to review first, you can choose manual publishing > * Download content and upload it yourself > * Or publish selectively from the AI Image & Video Editor dashboard > > **Media Management**: > > * Reorder media in Shopify to control which appears first > * Delete unwanted media from the product page > * Videos play inline on product pages (no external player needed) > > **Visibility**: > > * Published media is immediately visible to customers > * Videos work on all devices (desktop, mobile, tablet) > * Optimized for fast loading and smooth playback > > Your generated visual content integrates seamlessly with Shopify's native media handling. > [accordion] Is there a limit to how many videos or images I can create? > > **No hard limits**β€”the system is credit-based and scales with your needs: > > **Credit-Based Model**: > > * Create as many videos and images as you have credits for > * No monthly caps or restrictions > * Purchase more credits anytime to continue > > **Practical Considerations**: > > **Processing Queue**: > > * Large batch operations are queued and processed sequentially > * Very large batches (100+ products) may take time to complete > * Background processing allows you to continue working > > **Best Practices for Large Batches**: > > * Break extremely large batches into smaller chunks (50-100 products) > * Use workflows to schedule processing during off-hours > * Monitor credit usage to ensure sufficient balance > * Test settings on a few products before processing entire catalogues > > **Workflow Automation**: > > * Workflows can process unlimited products over time > * Schedule recurring workflows for continuous processing > * Ideal for catalogues with thousands of products > > **Volume Recommendations**: > > * Purchase larger credit packs for better value (up to 20% savings) > * Consider enterprise packs for extensive catalogue operations > * Priority processing included with larger packs > > Whether you have 10 products or 10,000, the platform scales to meet your needs. ### Integration & Publishing > [accordion] How do videos and images get added to my Shopify store? > > The platform offers flexible publishing options for generated content: > > **Auto-Publishing** (Default): > > * Videos and images are **automatically published** to product media upon completion > * Appear in the Shopify product media gallery immediately > * Customers can see them on product pages right away > * No manual upload required > > **How Auto-Publishing Works**: > > 1. You generate a video or edit an image > 2. Processing completes successfully > 3. Content is automatically added to the product's media in Shopify > 4. You receive confirmation of publication > > **Manual Publishing Option**: > > * Review content before publishing (optional setting) > * Download to your device first > * Manually approve each piece of content > * Publish selectively from your dashboard > > **Publishing Controls**: > > * **Publish**: Add content to Shopify product media > * **Download**: Save to your device without publishing > * **Remove**: Unlink content from a product > * **Republish**: Update or replace existing media > > **Media Organization**: > > * Content appears at the end of existing media by default > * Reorder media in Shopify to control display order > * Set featured images and videos from Shopify admin > > The seamless integration ensures your visual content reaches customers with minimal effort. > [accordion] Can I use the AI-generated content outside of Shopify? > > **Yes! You have full rights to use generated content anywhere:** > > **Download Options**: > > * Download videos and images directly from the dashboard > * Save to your device in standard formats > * Use across any marketing channel > > **Usage Rights**: > > * You own all AI-generated content created from your products > * Use freely in marketing materials, social media, advertising, etc. > * No additional licensing fees or restrictions > * Commercial use fully permitted > > **Use Cases Beyond Shopify**: > > * **Social Media**: Instagram, TikTok, Facebook, Pinterest > * **Paid Advertising**: Google Ads, Facebook Ads, display campaigns > * **Email Marketing**: Product showcases in newsletters > * **Marketplaces**: Amazon, eBay, Etsy product listings > * **Print Materials**: Catalogs, brochures, packaging > * **Wholesale**: B2B presentations and line sheets > > **File Formats**: > > * **Videos**: MP4 (universally compatible format supported by all platforms) > * **Images**: PNG (high-quality output with transparency support) > > **Coming Soon**: We're working on adding more format options for both videos and images in future updates. > > While the tool integrates seamlessly with Shopify, you're free to use your generated content across your entire marketing ecosystem. > [accordion] Do I need to install anything on my theme? > > **No theme installation required!** The AI Image & Video Editor is a standalone Shopify app: > > **How It Works**: > > * Install the app from the Shopify App Store > * Access the editor through your Shopify admin > * Generate and publish content directly to product media > * No theme code modifications needed > > **Integration**: > > * Uses Shopify's native media handling > * Videos and images appear automatically in your theme > * Works with any Shopify theme (no compatibility issues) > * No liquid code changes required > > **Theme Compatibility**: > > * Supports all Shopify themes (OS 2.0 and legacy) > * Content displays using your theme's existing media gallery > * Responsive and mobile-friendly automatically > * Theme updates don't affect the app > > **What You Need**: > > * Shopify Plus account > * App installed from Shopify App Store > * That's it! > > The app operates entirely within Shopify's ecosystem, making it plug-and-play without technical setup or theme modifications. ## Still Have Questions? Can't find what you're looking for? We're here to help! > [card] [Contact Support](mailto:support@glood.ai) > > Email us at [support@glood.ai](mailto:support@glood.ai) for personalized assistance > [card] [View Changelog](/ai-image-video-editor/changelog) > > Check out the latest updates and new features > [card] [Get Started Guide](/ai-image-video-editor/get-started) > > Review our comprehensive getting started documentation > [card] [Main Documentation](/ai-image-video-editor) > > Explore the full AI Image & Video Editor documentation # Get Started Source: https://docs.glood.ai/ai-image-video-editor/get-started Get started with Glood AI Image & Video Editor ## Getting Started with AI Image & Video Editor Welcome to Glood AI Image & Video Editor! This guide will walk you through the three main features: AI Video Generation, Image Editing, and Workflow Automation. Plus, learn about our credit-based pricing system. > [!NOTE] > > **Free Credits on Install**: Get \$20 in free credits when you install the app to start creating immediately! ## Prerequisites Before you begin, ensure you have: * Installed the Glood AI Image & Video Editor app from the Shopify App Store * Products with images in your Shopify store * An active Shopify Plus store ## Feature Walkthroughs > [tab] Video Generation > > ### Generate AI Videos from Product Images > > Transform your static product photos into engaging video content in minutes. > > **1. Navigate to Videos Page** > > From the main dashboard, click on **"Generate Video"** button or navigate to the Videos section from the sidebar. > > ![Video Editor Dashboard](https://mintcdn.com/gloodai/o3ibO2kMK4qRoOY4/images/ai-video-editor/video-dashboard.png?fit=max\&auto=format\&n=o3ibO2kMK4qRoOY4\&q=85\&s=01cfeda791f16cd7132a49157e050d37) > > **2. Select Your Products** > > Click **"Pick Product"** to open the product selector. You can: > > * Search for products by name > * Filter by collection or availability > * Select single or multiple product variants > * Add custom filters to narrow down your selection > > ![Product Selection](https://mintcdn.com/gloodai/o3ibO2kMK4qRoOY4/images/ai-video-editor/product-selection.png?fit=max\&auto=format\&n=o3ibO2kMK4qRoOY4\&q=85\&s=8d3a373a61ba9ff3a207164126de4c44) > > Select the products you want to create videos for and click **"Select"**. > > **3. Configure Video Settings** > > Once your product is selected, configure your video parameters: > > ![Video Generation Settings](https://mintcdn.com/gloodai/o3ibO2kMK4qRoOY4/images/ai-video-editor/video-settings.png?fit=max\&auto=format\&n=o3ibO2kMK4qRoOY4\&q=85\&s=8f14dccbbe004786e165165581a1f6d0) > > **Video Prompt**: Describe the video you want to generate. Be specific about the scene, style, and actions. Example: *"Create a realistic video of this person moving to show the dress"* > > **Video Settings**: > > * **Aspect Ratio**: Choose from 16:9 (Landscape), 9:16 (Portrait), 1:1 (Square) > * **Resolution**: Select from 1080p (Full HD), 720p (HD), or 480p (SD) > * **Generate Audio**: Toggle to add AI-generated audio to your video > * **Duration**: Set video length in seconds (typically 5-15 seconds) > > **Credit Estimate**: View the estimated credit cost based on your settings before generation. > > **4. Generate and Preview** > > Click **"Generate Video"** to start the AI generation process. > > ![Video Processing](https://mintcdn.com/gloodai/o3ibO2kMK4qRoOY4/images/ai-video-editor/video-processing.png?fit=max\&auto=format\&n=o3ibO2kMK4qRoOY4\&q=85\&s=26de5e418ee78bfdaf6c5c2aabfedd2f) > > The system will: > > 1. Process your product images > 2. Apply AI models to generate motion and effects > 3. Render the final video > > You'll see a progress indicator showing completion percentage. This typically takes 2-5 minutes depending on video length and quality settings. > > **5. Review and Publish** > > Once completed, preview your generated video: > > ![Video Completed](https://mintcdn.com/gloodai/o3ibO2kMK4qRoOY4/images/ai-video-editor/video-completed.png?fit=max\&auto=format\&n=o3ibO2kMK4qRoOY4\&q=85\&s=a6318ff2202f5ca53af8760e9658d6f8) > > **Video Details**: > > * View publication status > * Check creation timestamp > * Review credit usage > > **Actions**: > > * **Download**: Save the video to your device > > * **Regenerate**: Create a new version with different settings > > * **Remove from Product**: Unlink the video from the product > > * The video is automatically **Published** to your Shopify product media > > > [!NOTE] > > > > **Tip**: You can close the page during generation and check back later. Your video will continue processing in the background. > [tab] Image Editing > > ### Edit Product Images with AI > > Use AI-powered tools to enhance, resize, and transform your product images. > > **1. Navigate to Image Editor** > > From the dashboard, click **"Edit Image"** or navigate to the Images section. > > ![Image Editor Dashboard](https://mintcdn.com/gloodai/o3ibO2kMK4qRoOY4/images/ai-video-editor/image-dashboard.png?fit=max\&auto=format\&n=o3ibO2kMK4qRoOY4\&q=85\&s=0eacf21985ec21f96fa39273072ca2d9) > > You'll see your image editing activity, recently edited images, and quick access to editing tools. > > **2. Select Products and Images** > > Click to select the products and images you want to edit: > > ![Product and Image Selection](https://mintcdn.com/gloodai/o3ibO2kMK4qRoOY4/images/ai-video-editor/image-selection.png?fit=max\&auto=format\&n=o3ibO2kMK4qRoOY4\&q=85\&s=97966adddfdcf1f7bb989cc167cac196) > > You can: > > * Search for specific products > * Select single or multiple products > * Choose specific product images or variants > * Filter by collection or product type > * Preview images before editing > > **3. Choose Edit Preset and Configure** > > Select from available editing presets and configure your operations: > > ![Image Editing Settings](https://mintcdn.com/gloodai/o3ibO2kMK4qRoOY4/images/ai-video-editor/image-settings.png?fit=max\&auto=format\&n=o3ibO2kMK4qRoOY4\&q=85\&s=7b2ea8b23da29bbd6233655d22fff01a) > > **Fashion/Furniture Presets**: > > * Background generation with contextual scenes > * Background removal for clean product shots > * Smart cropping and composition > > **Custom Editing Options**: > > * **Background Generation**: Create custom backgrounds that complement your products > * **Background Removal**: Automatically remove backgrounds with precision > * **Resizing & Cropping**: Intelligent resizing that maintains product focus > * **Enhancement**: Apply AI filters and quality improvements > * **Format Optimization**: Convert and optimize for web performance > > **4. Build Operations Pipeline** > > Chain multiple editing operations together: > > 1. Add operations in sequence (e.g., Remove Background β†’ Generate New Background β†’ Resize) > 2. Configure parameters for each operation > 3. Preview the editing pipeline > 4. Review estimated credit cost before processing > > The system will show you the exact credit cost based on the number of images and operations selected. > > **5. Process and Review** > > Execute the editing pipeline and monitor progress: > > ![Image Processing](https://mintcdn.com/gloodai/o3ibO2kMK4qRoOY4/images/ai-video-editor/image-processing.png?fit=max\&auto=format\&n=o3ibO2kMK4qRoOY4\&q=85\&s=f46e83ae4c8dab12bbbd7d0ead968ce1) > > * Process begins immediately after confirmation > * View real-time progress for each operation > * Monitor processing status for batch operations > * Track completion percentage for each image > > Once processing is complete, review your edited images: > > ![Image Editing Completed](https://mintcdn.com/gloodai/o3ibO2kMK4qRoOY4/images/ai-video-editor/image-completed.png?fit=max\&auto=format\&n=o3ibO2kMK4qRoOY4\&q=85\&s=dd98da700e7c762e447b37dd24f6a916) > > **Review and Actions**: > > * Preview all edited images side-by-side with originals > > * Check processing status and credit usage > > * Download edited images individually or in bulk > > * Publish directly to Shopify product media > > * Regenerate with different settings if needed > > * View detailed operation logs and results > > > [!NOTE] > > > > **Batch Processing Tip**: Select multiple products and apply the same editing operations to all of them at once. Perfect for maintaining consistent visual standards across your catalogue. > [tab] Workflow Automation > > ### Automate Visual Creation at Scale > > Create reusable workflows to process multiple products automatically. > > **1. Navigate to Workflows** > > From the dashboard, click **"Build Workflow"** or go to the Workflows section. > > **2. Create New Workflow** > > Click **"Create Workflow"** and provide: > > * **Workflow Name**: Descriptive name for your automation > * **Description**: What this workflow does > * **Trigger Type**: On-demand or scheduled > > **3. Build Workflow Steps** > > Add and configure steps in your workflow: > > **Step Types**: > > * Video Generation (with specific settings) > * Image Editing (with operation chains) > * Publishing actions > * Conditional logic > > **Configuration**: > > * Set parameters for each step > * Define product filters (collections, tags, etc.) > * Configure output destinations > * Set quality and format preferences > > **4. Configure Workflow Triggers** > > Choose how and when your workflow runs: > > **On-Demand**: Manually trigger when needed > > * Run for specific products > * Execute immediately > > **Scheduled**: Automatic execution > > * Set recurring schedule (daily, weekly, monthly) > * Define time and timezone > * Apply to new products automatically > > **5. Test and Activate** > > Before full deployment: > > 1. Test the workflow with a sample product > > 2. Review credit estimates for full execution > > 3. Verify output quality > > 4. Activate the workflow for production use > > > [!NOTE] > > > > **Pro Tip**: Use workflows to maintain consistent visual standards across your entire product catalogue. Set up scheduled runs to automatically process new products as they're added. ## Credit-Based Pricing Glood AI Image & Video Editor uses a flexible credit system that scales with your needs. ### How Credits Work * **Credits** are consumed when you generate videos or edit images * Credit cost varies based on: * Video duration and resolution * Image editing operations and complexity * Output quality settings ### Free Credits > [card] Welcome Bonus > > Receive **\$20 in free credits** when you install the app. Start creating immediately with no upfront cost! > > **Note**: Free credits expire after 30 days, so use them to explore the platform's capabilities. ### Purchasing Credits Buy credit packs that fit your workflow. Higher value packs include attractive discounts: > [card] Flexible Packs > > Perfect for all usage levels > > * Packs start from $20, $50, and up > * Multiple sizes available > * Valid for 1 year from purchase > [card] Volume Discounts > > Best value for scale operations > > * Higher value packs offer significant savings > * Better value per credit > * Ideal for extensive catalogues > [!NOTE] > > **Credit Policy**: Purchased credits are valid for 1 year from purchase date. All credits are non-refundable. However, if generation fails due to system errors, credits are automatically refunded to your account. ### Managing Your Credits Monitor and purchase credits from the dashboard: 1. **View Balance**: Check your current credit balance on the main dashboard 2. **Purchase More**: Click **"+ Purchase Credits"** anytime 3. **Track Usage**: Review credit consumption in the **"Credit Usage"** section 4. **Estimate Costs**: See credit estimates before generating content > [!NOTE] > > **Credit Estimates**: Before generating any video or image, you'll see the exact credit cost. This helps you manage your budget and make informed decisions. ## Activity Dashboard Track your creative output with detailed activity metrics: * **Videos Created**: Total number of videos generated * **Total Duration**: Combined length of all videos created * **Images Edited**: Count of processed images * **Images Published**: Images published to products * **Workflows**: Active and total workflow count * **Workflow Runs**: Number of automated executions ## Next Steps Now that you're set up, explore these resources: > [card] [View Examples](/ai-image-video-editor/examples) > > See real examples of generated videos and edited images > [card] [Best Practices](/ai-image-video-editor/best-practices) > > Learn tips for creating high-quality visual content > [card] [FAQ](/ai-image-video-editor/faq) > > Get answers to common questions > [card] [API Reference](/api-reference) > > Integrate video and image generation into your workflow ## Need Help? * **FAQ**: Check our [Frequently Asked Questions](/ai-image-video-editor/faq) * **Changelog**: View [latest updates and releases](/ai-image-video-editor/changelog) * **Support**: Contact our team for assistance # AI Image & Video Editor Source: https://docs.glood.ai/ai-image-video-editor/index Intelligent image and video editing for Shopify stores ## Overview Welcome to the Glood AI Image & Video Editor documentation. Our AI-powered platform helps you easily generate videos and edit images for your commerce products at scale. Transform your product catalogue with professional-quality visual content using advanced AI models designed specifically for e-commerce. > [!NOTE] > > Streamline your visual content creation workflow and save hours of manual editing time. Process multiple products automatically with custom workflows that can run on-demand or on schedule. ## Key Features > [card] [AI Video Generation](/ai-image-video-editor/get-started) > > Automatically generate engaging product videos from catalogue images. Transform static product photos into dynamic video content that captures attention and drives conversions. > [card] [Intelligent Image Editing](/ai-image-video-editor/get-started) > > AI-powered image editing tools including background generation, background removal, image resizing, and enhancement. Perfect your product visuals effortlessly. > [card] [Automated Workflows](/ai-image-video-editor/get-started) > > Create custom editing workflows that run at scale. Process multiple products automatically and schedule recurring edits for your entire catalogue. ## Core Capabilities ### Video Generation from Product Images Transform your static product images into captivating video content for your catalogue: * **Automated Video Creation**: Generate professional product videos from single or multiple product images * **Multiple Style Options**: Choose from various video templates and styles to match your brand * **Bulk Processing**: Create videos for your entire product catalogue in minutes * **Optimized for Commerce**: Videos designed to highlight product features and drive conversions ### Intelligent Image Editing Suite Comprehensive AI-powered image editing tools tailored for product photography: * **Background Generation**: Create stunning, contextual backgrounds that complement your products * **Background Removal**: Automatically remove backgrounds with precision for clean, professional product shots * **Smart Resizing & Cropping**: Intelligently resize and crop images while maintaining focus on key product features * **Image Enhancement**: Apply AI-powered filters and adjustments to improve image quality * **Format Optimization**: Automatically optimize images for web performance without sacrificing quality ### Workflow Automation at Scale Build powerful automation workflows for custom editing that scales with your business: * **Custom Editing Pipelines**: Chain multiple editing operations into reusable workflows * **Multi-Product Batch Processing**: Apply edits to hundreds or thousands of products simultaneously * **Scheduled Automation**: Set up workflows to run automatically at specified intervals * **Reusable Templates**: Save your workflows as templates for consistent editing across your catalogue * **On-Demand Execution**: Run workflows manually whenever you need to update product visuals ## Getting Started Ready to start editing? Check out our [Get Started Guide](/ai-image-video-editor/get-started) to begin transforming your product visuals with AI. ## Need Help? * [FAQ](/ai-image-video-editor/faq) - Frequently asked questions * [Changelog](/ai-image-video-editor/changelog) - Latest updates and releases # Changelog Source: https://docs.glood.ai/ai-search-merchandising/changelog Release notes and updates for Glood AI Search & Merchandising ## Changelog Stay up to date with the latest features, improvements, and bug fixes. ### Version History #### October 2026 β€” Sales channel filtering * **Settings β†’ Sales channels**: choose which Shopify sales channels (for example Point of Sale or Headless) Glood may filter by. Saving re-indexes the publication ids of every product in the background. * **Headless APIs**: every search endpoint accepts an optional `publicationIds` array of Shopify publication ids and returns only products published on those channels. Without the parameter nothing changes. See [Filter by Sales Channel](/ai-search-merchandising/filter-by-sales-channel). *** ## Archive # Configure Collection-Level Default Sorting Source: https://docs.glood.ai/ai-search-merchandising/configure-collection-default-sorting Override the shop-wide default sort order for individual collections. By default every collection page uses the same shop-wide sort order. You can override that for individual collections β€” for example order one collection by price and leave the rest as they are. Collections you don't list keep using the default sort order. ## How to set a collection's sort order #### 1. Open the collection sort settings In the Glood AI Search & Merchandising app, go to **Settings** and scroll to the **Search Results Page** section. Under **Sort order for specific collections**, click **Add collection**. ![Sort order for specific collections setting with no collections listed and an Add collection button](https://mintcdn.com/gloodai/C66FIUTyOwyi_rxt/images/collection-sort-order-empty.png?fit=max\&auto=format\&n=C66FIUTyOwyi_rxt\&q=85\&s=801850af3fe59ce5eb49e6f9c6c118ef) #### 2. Select the collection and its ordering Pick the collection, then choose the ordering you want for it. Repeat for each collection you want to override β€” use the trash icon to remove one and send it back to the default sort order. ![Sort order for specific collections setting with two collections, 100% Cotton and 100% Linen, each with a Relevance sort dropdown](https://mintcdn.com/gloodai/C66FIUTyOwyi_rxt/images/collection-sort-order-settings.png?fit=max\&auto=format\&n=C66FIUTyOwyi_rxt\&q=85\&s=ee28d38c307ac70b2a2053aac8707348) #### 3. Save Click **Save**. The sort order applies to those collections right away. ## For headless & custom storefronts Once saved, the [Search Config](/api-reference/search/headless/config) endpoint returns the collection's configured ordering in `default_ordering` whenever the request passes `target_page: "collection"` with the collection's `target_id`. Use it as the pre-selected option in your sort control instead of assuming `relevance`. Search requests that omit `sort` resolve the same way β€” the collection's configured sort first, then the shop-wide default, then `relevance`. ## Support Need help configuring sort orders? Contact our support team at [support@glood.ai](mailto:support@glood.ai). # Enable Edge Delivery Source: https://docs.glood.ai/ai-search-merchandising/enable-edge-delivery Serve storefront search from an edge region close to your shoppers for faster results. Edge Delivery serves your storefront search requests from an **edge region geographically close to your shoppers** instead of a single central location. The search results and features are exactly the same β€” only where the request is served from changes β€” so shoppers in those regions get noticeably faster instant search, autocomplete, and search pages. ## Why enable Edge Delivery * **Lower latency, faster search.** Requests are answered from a region near the shopper instead of a round-trip to a central server, so instant-search and autocomplete feel snappier. * **Better experience in specific geographies.** Pick the region(s) that match where most of your shoppers are β€” for example Mumbai for India and Toronto for North America. * **Higher engagement and conversion.** Faster, more responsive search keeps shoppers browsing and reduces drop-off on slow queries. * **No change to results or setup.** Edge serves the same routes, ranking, filters, and merchandising as the default host β€” nothing about your catalog, configuration, or theme needs to change. > [!NOTE] > > Edge Delivery is currently available in **Mumbai (India)** and **Toronto (North America)**. Choose one or both depending on where your shoppers are. ## How to enable Edge Delivery #### 1. Open the Edge Delivery card on your dashboard In the Glood AI Search & Merchandising app, the **Overview** (home) page shows an **Edge Delivery** card with its current status. Click **Manage Edge Regions** to open the setting (or go to **Settings β†’ Edge Regions**). ![Edge Delivery card on the dashboard overview showing status and the Manage Edge Regions button](https://mintcdn.com/gloodai/Sg2BHnIxMzcmuRgY/images/edge-delivery-card.png?fit=max\&auto=format\&n=Sg2BHnIxMzcmuRgY\&q=85\&s=e5322c78e2c0db6b5625173e2bd8d1b9) #### 2. Turn on Edge Delivery and select your regions In the **Edge Regions** section, check **Enable Edge Delivery**, then under **Select Edge Regions** choose the region(s) closest to your shoppers β€” **Mumbai (India)** and/or **Toronto (North America)**. ![Edge Regions settings section with Enable Edge Delivery checked and Mumbai and Toronto region options](https://mintcdn.com/gloodai/Sg2BHnIxMzcmuRgY/images/edge-regions-settings.png?fit=max\&auto=format\&n=Sg2BHnIxMzcmuRgY\&q=85\&s=daf5cbe477913ea0dc4096f24a6eeaf1) #### 3. Save Click **Save**. Your selected regions are provisioned and storefront search starts serving from the edge. #### 4. Confirm it is enabled Return to the **Overview** page β€” the Edge Delivery card now shows an **Enabled** badge. That confirms edge is live for your store. ## For headless & custom storefronts If you use the [Headless Search API](/api-reference/search/introduction), point your client at the regional edge host (for example `https://mum.edge.glood.ai` or `https://tor.edge.glood.ai`) instead of the default `https://search.glood.ai`. The routes and payloads are identical β€” see [Edge URLs](/api-reference/search/introduction#edge-urls) for the full list of hosts and the required Content Security Policy note. ## Support Need help enabling or choosing edge regions? Contact our support team at [support@glood.ai](mailto:support@glood.ai). # FAQ Source: https://docs.glood.ai/ai-search-merchandising/faq Frequently asked questions about Glood AI Search & Merchandising ## Frequently Asked Questions ### General Questions ### Technical Questions ### Billing & Pricing ### Troubleshooting ## Still Have Questions? # Filter by Sales Channel Source: https://docs.glood.ai/ai-search-merchandising/filter-by-sales-channel Return only products published on specific Shopify sales channels, such as Point of Sale or a headless storefront. By default, search returns products that are published to your **Online Store**. If you also sell through other Shopify sales channels, such as **Point of Sale (POS)** or a **headless** storefront, you can ask the search APIs to return only the products published on one of those channels instead. This takes two steps: enable the channels in the app, then pass their ids on the API. ## 1. Enable the channels you want to filter by #### Open Settings β†’ Sales channels In the Glood AI Search & Merchandising app, go to **Settings β†’ Sales channels**. The section lists every sales channel installed on your store (Online Store, Point of Sale, Headless, Google & YouTube, and so on). #### Select channels and save Tick the channels you want to be able to filter by and click **Save**. > [!NOTE] > > Saving a new selection re-indexes the publication ids of every product. This runs in the background and can take a few minutes on large catalogs. The **Jobs** page shows its progress. Requests that pass a publication id for a channel that is not enabled here are rejected with `400`. ## 2. Pass the publication ids on the API Every search endpoint accepts an optional list of publication ids. The field is named in the same case as the rest of that API's fields: | API | Endpoints | Field | | - | - | - | | Headless (snake\_case) | `init`, `config`, `instant-search`, `filters`, `filter-aggregations`, `search`, `image-search` | `publication_ids` | | Theme storefront (camelCase) | The endpoints the storefront search widget calls, such as `/instant/results` | `publicationIds` | A headless request that sends `publicationIds` is rejected with `400` (`"publicationIds" is not allowed`). A publication id is the numeric part of a Shopify publication GID (`gid://shopify/Publication/30085840999` β†’ `30085840999`). You can read it from the Shopify Admin GraphQL `publications` query, and POS and headless integrations can store it once per shop. ```json POST /api/storefront/v1/headless/search theme={null} { "query": "running shoe", "locale": "en-US", "publication_ids": ["30085840999"] } ``` ```bash GET /api/storefront/instant/results (theme storefront) theme={null} ?q=running+shoe&locale=en-US&publicationIds=30085840999 ``` A single id may be sent without the array wrapper. Up to 50 ids are accepted; a product matches if it is published on **any** of them. ## What the filter does | Request | Products returned | | - | - | | No publication ids | Published to the Online Store (unchanged behaviour) | | Publication ids present | Published on at least one of the given channels; the Online Store condition no longer applies | | Publication ids with `market` | Both apply: on the channel **and** in the market's catalog | | Id not enabled in Settings | `400` naming the field you sent, for example `publication_ids not configured for this shop: ` | Facet counts, filter aggregations, trending products and the semantic search fallbacks all honour the same filter, on both the default host and Edge Delivery regions. ## Good to know * The filter applies to **products**. Collections, pages and articles in instant search are not channel-filtered. * Products published to a channel but **not** to the Online Store are not indexed yet, so a POS filter returns the products that are on both. Ask us if you need channel-only products indexed. * Publishing or unpublishing a product on a channel in Shopify updates the index through the normal product webhooks; no re-save is needed in the app. # Get Started Source: https://docs.glood.ai/ai-search-merchandising/get-started Get started with Glood AI Search & Merchandising ## Getting Started with AI Search & Merchandising ### Prerequisites ### Installation ### Quick Start ## Next Steps # AI Search & Merchandising Source: https://docs.glood.ai/ai-search-merchandising/index Intelligent search and merchandising for Shopify stores ## Overview Welcome to the Glood AI Search & Merchandising documentation. ## Key Features ## Getting Started Ready to enhance your store's search? Check out our [Get Started Guide](/ai-search-merchandising/get-started). ## Need Help? * [FAQ](/ai-search-merchandising/faq) - Frequently asked questions * [Changelog](/ai-search-merchandising/changelog) - Latest updates and releases # API reference Source: https://docs.glood.ai/api-reference/introduction Integrate Glood.AI recommendations and search into any storefront Build personalized shopping experiences on Shopify with Glood.AI APIs. Use headless APIs for Hydrogen, mobile apps, and custom storefronts β€” or integrate via partner APIs. ## Product recommendations > [card] [Initialize session](/api-reference/recommendations/headless/init) > > Identify visitors, get shop config, and obtain a storefront token. > [card] [Get sections](/api-reference/recommendations/headless/sections) > > Fetch recommendation sections with full product details for your page. > [card] [Track events](/api-reference/recommendations/headless/events) > > Send tracking events from mobile apps and headless storefronts. > [card] [Query recommendations](/api-reference/recommendations/headless/recommendations) > > Get AI recommendations for specific products using flexible queries. > [card] [Customer recommendations](/api-reference/recommendations/headless/customer-recommendations) > > Get cart, browsing, purchase and trending blocks for a known customer, each with a personalization checkpoint. ## Search > [card] [Search APIs](/api-reference/search/introduction) > > Semantic search, auto-suggestions, and intelligent product discovery. ## Authentication Pass your Shopify store URL in the `x-shop` header on all requests: ```bash theme={null} -H "x-shop: your-store.myshopify.com" ``` For recommendation query endpoints, include the storefront token (obtained from `/init`) as a Bearer token: ```bash theme={null} -H "Authorization: Bearer " ``` # Get Automatic Recommendations Source: https://docs.glood.ai/api-reference/recommendations/headless/automatic-recommendations POST /api/storefront/v3/headless/recommendations/automatic Get automatic recommendations powered using LLMs Each product carries `trending_rank` and `sales_rank` β€” shop-wide ranks refreshed daily; see the field reference. ```json 200 theme={null} { "status": "ok", "serve_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", "pagination": { "cursor": null }, "products": [ { "product_id": 9311227838783, "title": "Classic Cotton T-Shirt", "handle": "classic-cotton-t-shirt", "price": 1025, "compare_at_price": null, "tags": "cotton,casual,bestseller", "product_type": "T-Shirts", "vendor": "BrandName", "image": { "id": "gid://shopify/ProductImage/123456", "url": "https://cdn.shopify.com/s/files/1/example/products/t-shirt.jpg", "altText": "Classic Cotton T-Shirt", "width": 1600, "height": 1600 }, "options": [ { "id": 123, "name": "Title", "position": 1, "values": ["Default Title"] } ], "variants": [ { "variant_id": 48328566276415, "title": "Default Title", "display_name": "Classic Cotton T-Shirt - Default Title", "price": "1025.00", "compare_at_price": null, "sku": "", "position": 1, "is_in_stock": true, "available_for_sale": true, "sellable_online_quantity": 50, "selected_options": [ { "name": "Title", "value": "Default Title" } ] } ], "metafields": [], "trending_rank": 3, "sales_rank": 7 } ] } ``` ```json 400 theme={null} { "errors": [ { "message": "\"product_ids\" is required", "path": ["product_ids"], "type": "any.required", "context": { "label": "product_ids", "key": "product_ids" } } ] } ``` # Get Customer Recommendations Source: https://docs.glood.ai/api-reference/recommendations/headless/customer-recommendations POST /api/storefront/v3/headless/recommendations/customer Four recommendation blocks for one known customer, built from their cart, browsing and purchase history, with a checkpoint on each block saying how much of it is personalized. ## Overview Send who the customer is, and Glood looks up their history server-side and returns four blocks: | Block | Built from | Algorithm | | - | - | - | | `cart` | Products in the customer's cart | Frequently bought together | | `browsing_history` | Products the customer viewed | Similar products | | `purchase_history` | Products the customer bought | Cross-sell | | `trending` | Nothing customer-specific | Trending | No `product_ids` are needed: each block is anchored on the customer's own two most recent products for that signal. This makes the endpoint a fit for marketing emails, CRM and CDP syncs, account pages, and any surface that knows the customer but not the product they are looking at. For recommendations around specific products, use [Query recommendations](/api-reference/recommendations/headless/recommendations). Every block always comes back filled. When a customer has too little data for a block, Glood tops it up with trending products, and the block's [checkpoint](#checkpoints) tells you how much of it is personalized. You can ask for [only some of the blocks](#choosing-blocks), or for [the checkpoints alone](#checkpoints-only) to decide what to show before fetching products. ## Identifying the customer Send **at least one** of these. A request with none of them is rejected with `400`. | Field | Notes | | - | - | | `customer_id` | Shopify customer ID, numeric (`9155793715519`) or GID (`gid://shopify/Customer/9155793715519`), as a string or a number. | | `email` | Case and surrounding whitespace are ignored. Also matched against the Shopify customer record and against orders, so guest checkouts are found. | | `phone` | Formatting is ignored (`+1 (555) 010-9999` matches `+15550109999`). Matched against orders too. | > [!TIP] > > Send `customer_id` whenever you have it. A customer usually browses on several devices, and > `customer_id` reaches all of them. `email` alone reaches only the devices where an email was > captured, plus the customer's orders. > [!WARNING] > > Send one customer's identifiers per request. Identifiers are combined with OR, so an `email` > for one customer and a `phone` for another would merge both customers' histories. Anonymous `client_id` / `user_id` are not accepted here (`400`). For anonymous shoppers, use [Query recommendations](/api-reference/recommendations/headless/recommendations). An identifier that matches nobody is not an error: you get `200` with `customer.identified: false` and three blocks filled from trending. ## What each signal contains | Signal | Source | | - | - | | Browsing history | Products viewed, across every matched device, newest first. | | Cart | `cart_product_ids` if you send it. Otherwise the customer's add-to-cart history, minus anything bought since. | | Purchase history | Orders from the last 365 days (cancelled orders excluded), plus purchases tracked on the storefront. | Each signal keeps at most 10 products. Products that no longer exist in the catalogue are skipped when choosing a block's anchors. ### Sending the live cart If your storefront knows the current cart, send it as `cart_product_ids`: up to 10 product IDs, as an array or a comma-separated string. It **replaces** Glood's add-to-cart history, which cannot see removals. Send `[]` for an empty cart. Leave the field out only when you don't know the cart. ## What is never recommended * Products the customer has bought. * Products in the customer's cart. * Products and tags the merchant excluded in Glood settings. * A block's own anchor products. * The same product twice in one response. Blocks claim products in order: `cart`, then `browsing_history`, then `purchase_history`, then `trending`. The trending block shows the shop's top trending products before any of them are used to top up other blocks. ## Choosing blocks Send `blocks` to get only some of the blocks, for example `["cart", "trending"]`. Valid names are `cart`, `browsing_history`, `purchase_history` and `trending`. Leave it out to get all four. * The response contains only the blocks you asked for, always in the order above, whatever order you send them in. * A block you did not ask for is not computed and claims no products. So a block can contain a product that, in a full response, an earlier block would have taken. * Without `trending`, short blocks are topped up from the very top of the trending list. * `customer.signals` always reports all three signals. ## Checkpoints only Add `?checkpoints_only=true` to the URL to get every block's `checkpoint`, and `customer`, without the products. Each block then has `recommendation_serve_id`, `recommendation_type` and `checkpoint` only. Use it to decide which blocks to show, or whether a customer has enough data for a personalized campaign, before you fetch any products. The checkpoints are the same as in a full response for the same request: Glood still builds the blocks to count their products. The response is smaller, but the request costs the same. It combines with `blocks`. ## Context `context` is an optional list of free-form labels for where the recommendations will be shown, for example `["email", "win_back"]`: up to 20 strings of up to 200 characters each. It does not change which products are returned. ## Checkpoints Every block carries a `checkpoint`: | Field | Meaning | | - | - | | `status` | `personalized`: every product came from the customer's data. `partial`: some did, the rest are trending. `fallback`: none did, all are trending. `trending`: the trending block itself. | | `reason` | Why a block is short of personalized products, or `null`. `no_customer_data`: the customer has no usable data for this signal. `insufficient_results`: there was data, but it produced fewer than `max_recommendations` products not already shown in an earlier block. `error`: this block failed and was filled from trending, while the rest of the response is unaffected. | | `uses_customer_data` | `true` when at least one product came from the customer's data. Always `false` on the trending block. | | `anchor_product_ids` | The customer's products this block was computed from (at most 2). | | `personalized_count` | The **first** `personalized_count` entries of `recommendations` are personalized. | | `fallback_count` | The remaining entries are trending products. | | `filled_from` | `"trending"` when `fallback_count > 0`, otherwise `null`. | `customer.signals` reports how much history was found for each signal (`count`, capped at 10), and `customer.signals.cart.source` says whether the cart came from your request (`request`) or from Glood's tracking (`pixel`). > [!TIP] > > You can render every block as-is. Use the checkpoint to label it (for example "Picked for you" > only when `status` is `personalized`), to show only the first `personalized_count` products, > or to measure how often customers have enough data. ## Sales channels Send `publication_ids` to return only products published on those sales channels, as on the other headless recommendation endpoints. See [Filter by Sales Channel](/guides/product-filtering/filter-by-sales-channel). ## Errors | Status | When | | - | - | | `400` | No usable `customer_id`, `email` or `phone`; an unknown field (such as `client_id`, or `publicationIds` instead of `publication_ids`); `max_recommendations` outside 1–50; more than 10 `cart_product_ids`; a `blocks` list that is empty, repeats a block or names an unknown one; a `context` that is not a list of strings, or has more than 20 entries or one over 200 characters; a `publication_ids` value the shop has not configured; a `checkpoints_only` that is not `true` or `false`; or the shop has no active plan. | | `401` | Missing or invalid storefront token, or missing `x-shop`. | | `429` | Rate limit exceeded for the shop. | ## Examples ```bash Known customer theme={null} curl -sS -X POST 'https://storefront.glood.ai/api/storefront/v3/headless/recommendations/customer' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'x-shop: shop.myshopify.com' \ -d '{ "customer_id": "9155793715519", "email": "shopper@example.com", "max_recommendations": 4, "view": "product_ids" }' ``` ```bash With the live cart theme={null} curl -sS -X POST 'https://storefront.glood.ai/api/storefront/v3/headless/recommendations/customer' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'x-shop: shop.myshopify.com' \ -d '{ "email": "shopper@example.com", "cart_product_ids": [9311227838783, 9311227904319], "max_recommendations": 8 }' ``` ```bash Some blocks theme={null} curl -sS -X POST 'https://storefront.glood.ai/api/storefront/v3/headless/recommendations/customer' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'x-shop: shop.myshopify.com' \ -d '{ "email": "shopper@example.com", "blocks": ["browsing_history", "trending"], "context": ["email", "win_back"], "view": "product_ids" }' ``` ```bash Checkpoints only theme={null} curl -sS -X POST 'https://storefront.glood.ai/api/storefront/v3/headless/recommendations/customer?checkpoints_only=true' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'x-shop: shop.myshopify.com' \ -d '{ "customer_id": "9155793715519" }' ``` ```bash Edge endpoint theme={null} curl -sS -X POST 'https://edge.glood.ai/api/edge/storefront/v3/headless/recommendations/customer' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'x-shop: shop.myshopify.com' \ -d '{ "customer_id": "9155793715519", "view": "product_ids" }' ``` Each product carries `trending_rank` and `sales_rank` β€” shop-wide ranks refreshed daily; see the field reference. ```json 200 - product_ids view theme={null} { "status": "ok", "serve_id": "4f2e9c1a-7d3b-4b8e-9a51-2c6f0d8e1b77", "customer": { "identified": true, "signals": { "browsing_history": { "available": true, "count": 6 }, "cart": { "available": true, "count": 1, "source": "pixel" }, "purchase_history": { "available": false, "count": 0 } } }, "blocks": { "cart": { "recommendation_serve_id": "9a1c2b3d-4e5f-4a6b-8c7d-0e1f2a3b4c5d", "recommendation_type": "bought_together", "checkpoint": { "status": "personalized", "reason": null, "uses_customer_data": true, "anchor_product_ids": [9311227904319], "personalized_count": 4, "fallback_count": 0, "filled_from": null }, "recommendations": [ { "product_id": 9311227838783 }, { "product_id": 9311227871551 }, { "product_id": 9311227937087 }, { "product_id": 9311227969855 } ] }, "browsing_history": { "recommendation_serve_id": "1b2c3d4e-5f6a-4b7c-8d9e-0f1a2b3c4d5e", "recommendation_type": "similar_products", "checkpoint": { "status": "partial", "reason": "insufficient_results", "uses_customer_data": true, "anchor_product_ids": [9311228002623, 9311228035391], "personalized_count": 2, "fallback_count": 2, "filled_from": "trending" }, "recommendations": [ { "product_id": 9311228068159 }, { "product_id": 9311228100927 }, { "product_id": 9311228264767 }, { "product_id": 9311228297535 } ] }, "purchase_history": { "recommendation_serve_id": "2c3d4e5f-6a7b-4c8d-9e0f-1a2b3c4d5e6f", "recommendation_type": "cross_sell", "checkpoint": { "status": "fallback", "reason": "no_customer_data", "uses_customer_data": false, "anchor_product_ids": [], "personalized_count": 0, "fallback_count": 4, "filled_from": "trending" }, "recommendations": [ { "product_id": 9311228330303 }, { "product_id": 9311228363071 }, { "product_id": 9311228395839 }, { "product_id": 9311228428607 } ] }, "trending": { "recommendation_serve_id": "3d4e5f6a-7b8c-4d9e-8f0a-2b3c4d5e6f7a", "recommendation_type": "trending", "checkpoint": { "status": "trending", "reason": null, "uses_customer_data": false, "anchor_product_ids": [], "personalized_count": 0, "fallback_count": 0, "filled_from": null }, "recommendations": [ { "product_id": 9311228133695 }, { "product_id": 9311228166463 }, { "product_id": 9311228199231 }, { "product_id": 9311228231999 } ] } } } ``` ```json 200 - product_details view (one block shown) theme={null} { "status": "ok", "serve_id": "4f2e9c1a-7d3b-4b8e-9a51-2c6f0d8e1b77", "customer": { "identified": true, "signals": { "...": "..." } }, "blocks": { "cart": { "recommendation_serve_id": "9a1c2b3d-4e5f-4a6b-8c7d-0e1f2a3b4c5d", "recommendation_type": "bought_together", "checkpoint": { "status": "personalized", "reason": null, "uses_customer_data": true, "anchor_product_ids": [9311227904319], "personalized_count": 1, "fallback_count": 0, "filled_from": null }, "recommendations": [ { "product_id": 9311227838783, "title": "Classic Cotton T-Shirt", "handle": "classic-cotton-t-shirt", "price": 1025, "compare_at_price": null, "image": { "id": "gid://shopify/ProductImage/123456", "url": "https://cdn.shopify.com/s/files/1/example/products/t-shirt.jpg", "altText": "Classic Cotton T-Shirt", "width": 1600, "height": 1600 }, "tags": "cotton, casual, bestseller", "product_type": "T-Shirt", "vendor": "Example Co", "options": [ { "id": 123, "name": "Title", "position": 1, "values": ["Default Title"] } ], "variants": [ { "variant_id": 48328566276415, "title": "Default Title", "display_name": "Classic Cotton T-Shirt - Default Title", "price": "1025.00", "compare_at_price": null, "sku": "", "position": 1, "is_in_stock": true, "available_for_sale": true, "sellable_online_quantity": 50, "selected_options": [{ "name": "Title", "value": "Default Title" }] } ], "metafields": [], "trending_rank": 3, "sales_rank": 7 } ] }, "browsing_history": { "...": "..." }, "purchase_history": { "...": "..." }, "trending": { "...": "..." } } } ``` ```json 200 - ?checkpoints_only=true theme={null} { "status": "ok", "serve_id": "5a3f0d2b-8e4c-4c9f-a062-3d7e1f9c2c88", "customer": { "identified": true, "signals": { "browsing_history": { "available": true, "count": 6 }, "cart": { "available": true, "count": 1, "source": "pixel" }, "purchase_history": { "available": false, "count": 0 } } }, "blocks": { "cart": { "recommendation_serve_id": "6b4a1e3c-9f5d-4da0-b173-4e8f2a0d3d99", "recommendation_type": "bought_together", "checkpoint": { "status": "personalized", "reason": null, "uses_customer_data": true, "anchor_product_ids": [9311227904319], "personalized_count": 10, "fallback_count": 0, "filled_from": null } }, "browsing_history": { "recommendation_serve_id": "7c5b2f4d-0a6e-4eb1-8284-5f9a3b1e4eaa", "recommendation_type": "similar_products", "checkpoint": { "status": "partial", "reason": "insufficient_results", "uses_customer_data": true, "anchor_product_ids": [9311228002623, 9311228035391], "personalized_count": 6, "fallback_count": 4, "filled_from": "trending" } }, "purchase_history": { "recommendation_serve_id": "8d6c3a5e-1b7f-4fc2-9395-6a0b4c2f5fbb", "recommendation_type": "cross_sell", "checkpoint": { "status": "fallback", "reason": "no_customer_data", "uses_customer_data": false, "anchor_product_ids": [], "personalized_count": 0, "fallback_count": 10, "filled_from": "trending" } }, "trending": { "recommendation_serve_id": "9e7d4b6f-2c80-4ad3-8406-7b1c5d3a6acc", "recommendation_type": "trending", "checkpoint": { "status": "trending", "reason": null, "uses_customer_data": false, "anchor_product_ids": [], "personalized_count": 0, "fallback_count": 0, "filled_from": null } } } } ``` ```json 400 - no customer identifier theme={null} { "errors": [ { "message": "one of customer_id, email or phone is required", "path": [], "type": "customer.identity", "context": { "label": "value", "value": { "max_recommendations": 4, "view": "product_details", "blocks": ["cart", "browsing_history", "purchase_history", "trending"] } } } ] } ``` # Send Headless Events Source: https://docs.glood.ai/api-reference/recommendations/headless/events POST /api/storefront/v3/headless/events Send tracking events from headless, mobile, or hydrogen storefronts. # Headless Init Source: https://docs.glood.ai/api-reference/recommendations/headless/init POST /api/storefront/v3/headless/init Identify a visitor and retrieve shop configuration. Call this once per session before fetching sections or sending events. # Get Headless Recommendations using Query Source: https://docs.glood.ai/api-reference/recommendations/headless/recommendations POST /api/storefront/v3/headless/recommendations Fetch recommendations for up to five queries in one call, personalized to the shopper you identify. ## Identifying the shopper Every identity field is **optional**. Send whichever ones your storefront has, and Glood resolves them to a single visitor profile: | Field | Use when | | - | - | | `client_id` | You have the Shopify `_shopify_y` device cookie. | | `user_id` | You have the Glood-generated user id (returned by [Headless Init](/api-reference/recommendations/headless/init)). | | `customer_id` | The shopper is logged in and you have their Shopify customer ID. | | `email` | You have no `customer_id` β€” resolves to the same profile. | | `phone` | Same as `email`, for storefronts that identify shoppers by phone. | `email` and `phone` exist for storefronts that never see a Shopify `customer_id`. They identify the **same** shopper profile a `customer_id` would, so recommendations are personalized identically either way. > [!TIP] > > Send every identifier you have, not just one. A shopper often has both an anonymous > browsing profile (under `client_id`) and an identified one (under `customer_id` or > `email`). Passing both lets Glood pick whichever holds the richer browsing history. Matching ignores formatting, so you do not need to normalize before sending: * `email` β€” case and surrounding whitespace are ignored (`" Shopper@Example.com "` matches `shopper@example.com`) * `phone` β€” punctuation and spacing are ignored (`+1 (555) 010-9999` matches `+15550109999`) > [!NOTE] > > Sending no identifier at all is valid. You get the same recommendations, just without > personalization β€” no error. An unrecognized `email` or `phone` behaves the same way. ## How personalization works When a request identifies a shopper with browsing history, results are ranked using that history in addition to the products in `product_ids`: * **`similar_products`** β€” stays anchored to the products you asked about; browsing history refines the ordering rather than replacing it. * **`bought_together`** β€” the same blend, applied to co-purchase candidates. Only **browsing** history is used. Purchase and cart history do not affect ranking. To override the automatic behaviour, set `ranking_criteria` on an individual query β€” for example `bestsellers` or `new_arrivals`. Leaving it unset is recommended. > [!NOTE] > > Personalization improves as browsing data accumulates. A shopper Glood has not seen before > receives standard relevance-ranked recommendations. Each product carries `trending_rank` and `sales_rank` β€” shop-wide ranks refreshed daily; see the field reference. ```json 200 - product_details view theme={null} { "status": "ok", "serve_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", "data": { "rec-1": { "recommendation_serve_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "recommendation_type": "similar_products", "max_recommendations": 10, "creation_type": "automatic", "product_ids": [123, 456], "view": "product_details", "recommendations": [ { "product_id": 9311227838783, "title": "Classic Cotton T-Shirt", "handle": "classic-cotton-t-shirt", "product_type": "T-Shirt", "vendor": "Glood Apparel", "price": 1025, "compare_at_price": null, "image": { "id": "gid://shopify/ProductImage/123456", "url": "https://cdn.shopify.com/s/files/1/example/products/t-shirt.jpg", "altText": "Classic Cotton T-Shirt", "width": 1600, "height": 1600 }, "tags": "cotton,casual,bestseller", "options": [ { "id": 123, "name": "Title", "position": 1, "values": ["Default Title"] } ], "variants": [ { "variant_id": 48328566276415, "title": "Default Title", "display_name": "Classic Cotton T-Shirt - Default Title", "price": "1025.00", "compare_at_price": null, "sku": "", "position": 1, "is_in_stock": true, "available_for_sale": true, "sellable_online_quantity": 50, "selected_options": [ { "name": "Title", "value": "Default Title" } ] } ], "metafields": [], "trending_rank": 3, "sales_rank": 7 } ] } } } ``` ```json 200 - product_ids view theme={null} { "status": "ok", "serve_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", "data": { "rec-1": { "recommendation_serve_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "recommendation_type": "similar_products", "max_recommendations": 10, "creation_type": "automatic", "product_ids": [123, 456], "view": "product_ids", "recommendations": [ { "product_id": 9311227838783 }, { "product_id": 9311227838784 } ] } } } ``` ```json 400 theme={null} { "errors": [ { "message": "\"product_ids\" is required", "path": ["queries", 0, "product_ids"], "type": "any.required", "context": { "label": "queries[0].product_ids", "key": "product_ids" } } ] } ``` # Get Headless Sections Source: https://docs.glood.ai/api-reference/recommendations/headless/sections POST /api/storefront/v3/headless/sections Get recommendation sections with full product details for a given page context. Each product carries `trending_rank` and `sales_rank` β€” shop-wide ranks refreshed daily; see the field reference. # Get Top Recommendations Source: https://docs.glood.ai/api-reference/recommendations/headless/top-recommendations POST /api/storefront/v3/headless/recommendations/top Fetch products by a ranking strategy (bestsellers, new arrivals) with rich criteria filters, full-text query, cursor pagination, and facet aggregations. ## Overview The **top recommendations** endpoint lets headless storefronts fetch products **without a seed anchor** β€” unlike `/recommendations` and `/recommendations/automatic`, no `product_ids` are required. It is the right endpoint for: * Catalog / collection landing pages ("Bestsellers", "New arrivals") * Search results constrained by a strategy (e.g. bestsellers matching "wireless charger") * Merchandising widgets that need filtered top-N lists with facet sidebars The filter contract is **identical to `/recommendations/automatic`** β€” same `filter` shape, same Joi schema β€” extended with four additional dimensions (`excluded_tags`, `collections`, `product_types`, `price`). Those extensions are also accepted by the automatic endpoint going forward. > [!NOTE] > > **Authentication.** Pass `Authorization: Bearer ` and `x-shop: ` on every call. See [Get Started β†’ Headless Authentication](/api-reference/recommendations/headless/init) for token provisioning. ## Ranking strategies | Strategy | What it returns | | - | - | | `BESTSELLERS` | Products ranked by revenue over the last 7, 15, or 30 days (selectable via `strategy_options.sales_time_period`, default 7). | | `NEW_ARRIVALS` | Most recently published products. | ## Filter dimensions `filter` is fully optional. Each sub-field is independently optional and combined as an AND: * **`tags`** / **`excluded_tags`** β€” include / exclude by product tag. * **`vendors`** β€” vendor names (exact match). * **`product_types`** β€” product type values. * **`collections`** β€” collection IDs the product must belong to. * **`price.min`** / **`price.max`** β€” price range in shop currency. * **`variants.is_in_stock`**, **`variants.available_for_sale`** β€” variant-level availability (matches any variant). * **`variants.options[]`** β€” variant option matches (e.g. `Color: Black`). * **`variants.sku[]`** β€” variant SKU match. * **`metafields[]`** β€” match by `{namespace, key, value}`; requires a `filterKey` to exist on the indexed product. > [!TIP] > > **Array or comma-separated string.** The list-style fields `tags`, `excluded_tags`, `vendors`, `product_types`, and `collections` accept **either** a JSON array of strings **or** a single comma-separated string. Useful for clients whose query serializers can't construct arrays from variables. Both forms below are equivalent: > > ```json theme={null} > { "filter": { "tags": ["new", "sale", "featured"] } } > { "filter": { "tags": "new,sale,featured" } } > ``` > > Whitespace around commas is trimmed. ## Text query When `query` is provided, a `multi_match` clause is added across `title^3`, `description`, `tags`, `vendor`, `productType` with `operator: AND`, `lenient: true`. The **strategy sort still wins** β€” products matching the text query are ranked by sales (or recency), not by BM25 relevance. For relevance-first text search, use the [AI Search](/api-reference/search/introduction) endpoint instead. ## Facets Pass `facets: ["vendor", "product_type", "tag", "price"]` (any subset) to receive aggregations alongside the products. Each facet returns top values with counts. The `price` facet returns fixed buckets (`0-50`, `50-100`, `100-250`, `250+`). Facet counts are computed using a **post-filter** model β€” each facet's counts ignore that dimension's filter so a sidebar UI can show "all available vendors" even when the user has selected one. Other filters still apply. ## Pagination Cursor-based, matching the rest of the v3 headless surface. The first request can pass `pagination.limit` (1–100, default 24). Subsequent pages pass the `cursor` returned in the previous response. > [!WARNING] > > When paginating with a `cursor`, the `filter`, `query`, and `strategy` must **stay identical** to the request that produced the cursor β€” changing them invalidates the sort context and returns incoherent ordering. The response includes `pagination.total` and `pagination.totalRelation` (`"eq"` or `"gte"`). Elasticsearch caps totals at 10,000 by default β€” when the relation is `"gte"`, the real total is β‰₯ that value. ## Examples ```bash Minimal β€” Bestsellers theme={null} curl -sS -X POST 'https://storefront.glood.ai/api/storefront/v3/headless/recommendations/top' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'x-shop: shop.myshopify.com' \ -d '{ "strategy": "BESTSELLERS", "view": "product_details" }' ``` ```bash New Arrivals + text + price filter theme={null} curl -sS -X POST 'https://storefront.glood.ai/api/storefront/v3/headless/recommendations/top' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'x-shop: shop.myshopify.com' \ -d '{ "strategy": "NEW_ARRIVALS", "view": "product_details", "query": "wireless charger", "filter": { "price": { "min": 20.00, "max": 80.00 }, "variants": { "is_in_stock": true } }, "facets": ["vendor", "price"], "pagination": { "limit": 24 } }' ``` ```bash Bestsellers β€” full filter surface theme={null} curl -sS -X POST 'https://storefront.glood.ai/api/storefront/v3/headless/recommendations/top' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'x-shop: shop.myshopify.com' \ -d '{ "strategy": "BESTSELLERS", "view": "product_details", "query": "cable", "filter": { "tags": ["holiday-2026"], "excluded_tags": ["clearance", "discontinued"], "vendors": ["UGREEN"], "product_types": ["Cable", "Hub"], "collections": ["345678901", "456789012"], "metafields": [ { "namespace": "custom", "key": "gender", "value": "unisex" } ], "variants": { "is_in_stock": true, "available_for_sale": true, "options": [{ "name": "Length", "value": "2m" }] }, "price": { "min": 5.00, "max": 50.00 } }, "facets": ["vendor", "product_type", "tag", "price"], "pagination": { "limit": 24 } }' ``` ```bash Bestsellers β€” 30-day window theme={null} curl -sS -X POST 'https://storefront.glood.ai/api/storefront/v3/headless/recommendations/top' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'x-shop: shop.myshopify.com' \ -d '{ "strategy": "BESTSELLERS", "strategy_options": { "sales_time_period": 30 }, "view": "product_details", "filter": { "collections": ["123456789"] }, "pagination": { "limit": 12 } }' ``` ```bash Paginate β€” second page via cursor theme={null} curl -sS -X POST 'https://storefront.glood.ai/api/storefront/v3/headless/recommendations/top' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'x-shop: shop.myshopify.com' \ -d '{ "strategy": "BESTSELLERS", "view": "product_details", "filter": { "price": { "min": 20.00, "max": 80.00 } }, "pagination": { "cursor": "eyJzIjpbMTIzLjQ1LCI5ODc2NTQzMjEiXSwic2Vzc2lvbiI6IjU1ZGE0NjM5LTUyMTYtNGE4Mi1iMmNlLTUxYTU3MmZjMzVjNCJ9", "limit": 24 } }' ``` ```bash Filter lists as CSV strings theme={null} curl -sS -X POST 'https://storefront.glood.ai/api/storefront/v3/headless/recommendations/top' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'x-shop: shop.myshopify.com' \ -d '{ "strategy": "BESTSELLERS", "view": "product_details", "filter": { "tags": "new,sale,featured", "excluded_tags": "clearance,discontinued", "vendors": "UGREEN,Anker", "product_types": "Cable,Hub", "collections": "345678901,456789012" }, "pagination": { "limit": 24 } }' ``` ```bash IDs only (lightweight) theme={null} curl -sS -X POST 'https://storefront.glood.ai/api/storefront/v3/headless/recommendations/top' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'x-shop: shop.myshopify.com' \ -d '{ "strategy": "BESTSELLERS", "view": "product_ids", "pagination": { "limit": 50 } }' ``` ```bash Edge endpoint theme={null} curl -sS -X POST 'https://edge.glood.ai/api/edge/storefront/v3/headless/recommendations/top' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -H 'x-shop: shop.myshopify.com' \ -d '{ "strategy": "BESTSELLERS", "view": "product_details", "filter": { "variants": { "is_in_stock": true } }, "facets": ["vendor", "price"], "pagination": { "limit": 24 } }' ``` Each product carries `trending_rank` and `sales_rank` β€” shop-wide ranks refreshed daily; see the field reference. ```json 200 theme={null} { "status": "ok", "serve_id": "7c3f5e8a-2b14-49c1-a7d3-93f4e2bb1c8e", "strategy": "BESTSELLERS", "products": [ { "handle": "uno-usb-c-cable-100w", "product_id": 8123456789012, "title": "Uno USB-C to USB-C Cable 100W", "vendor": "UGREEN", "product_type": "Cable", "tags": "cable, usb-c, fast-charge", "price": 9.34, "compare_at_price": 14.99, "image": { "id": "gid://shopify/ImageSource/33459800441029", "url": "https://cdn.shopify.com/s/files/.../cable.jpg", "altText": null, "width": 1600, "height": 1600 }, "variants": [], "options": [], "metafields": [], "trending_rank": 3, "sales_rank": 7 } ], "pagination": { "cursor": "eyJzIjpbMC44Mzc3LCI4MTIzNDU2Nzg5MDEyIl0sInNlc3Npb24iOiI1NWRhNDYzOS01MjE2LTRhODItYjJjZS01MWE1NzJmYzM1YzQifQ==", "hasMore": true, "total": 327, "totalRelation": "eq", "limit": 24 }, "facets": { "vendor": [ { "value": "UGREEN", "count": 142 }, { "value": "Anker", "count": 98 } ], "price": [ { "min": 0, "max": 50, "count": 210 }, { "min": 50, "max": 100, "count": 78 }, { "min": 100, "max": 250, "count": 39 } ] } } ``` ```json 400 theme={null} { "errors": [ { "message": "\"strategy\" is required", "path": ["strategy"], "type": "any.required", "context": { "label": "strategy", "key": "strategy" } } ] } ``` ```json 401 theme={null} { "error": "Invalid authentication" } ``` ```json 429 theme={null} { "error": "Too many requests, please try again later." } ``` # Partner APIs Source: https://docs.glood.ai/api-reference/recommendations/partners/introduction APIs for third-party integrations and partner platforms Partner APIs allow third-party platforms and services to integrate Glood.AI recommendations into their products. > [!NOTE] > > Partner APIs are currently in development. Contact [support@glood.ai](mailto:support@glood.ai) for early access. # Search Config Source: https://docs.glood.ai/api-reference/search/headless/config POST /api/storefront/v1/headless/config Config for all three search features (instant, results page, image) plus filter definitions, filter tree, shop, analytics, translations and the Shopify storefront token. No Liquid templates and no widget css/js. Auth: `Authorization: Bearer ` + `x-shop`. ```json 200 theme={null} { "config": { "instant_search_enabled": true, "search_result_page_enabled": true, "image_search_enabled": true, "personalization_enabled": false, "personalization_config": null, "auto_spell_correct_enabled": true, "instant_search_objects": ["product", "collection", "page", "auto_suggestion"], "exclude_out_of_stock": false, "move_out_of_stock_at_end": true, "site_wide_search": {}, "search_result_count": 10, "default_ordering": "relevance", "minimum_type_ahead_input_count": 2, "default_search_result_page_size": 20, "search_page_autocomplete_enabled": true, "search_page_handle": "search", "image_search_pages": null, "settings": {} }, "filters": [ { "id": 1, "key": "color", "title": "Color", "type": "color", "attribute_type": "option", "position": 1, "expanded": true, "visible": true, "operator": "or", "settings": { "multi_select": true, "show_count": true, "collapsible": true, "searchable": false, "show_more": true, "max_display": 10 }, "min": null, "max": null, "step": null, "unit": null, "suffix": null, "values": [ { "value": "red", "label": "Red", "count": null, "position": 1, "hex": "#ff0000", "image": null, "order": null } ] } ], "filter_tree": { "id": 1, "target_page": "search", "target_ids": [], "is_default": true, "title": "Search filters", "settings": {}, "data": [], "translations": {} }, "shop": { "currency_format": "${{amount}}", "primary_locale": "en", "currency": "USD" }, "analytics": { "enabled": true, "tracking_id": null }, "translations": {}, "token": "shpat_xxx", "metadata": { "region": "toronto", "locale": "en-US", "market": null } } ``` ```json 400 theme={null} { "error": [ { "message": "\"target_page\" must be one of [search, collection]", "path": ["target_page"], "type": "any.only", "context": { "label": "target_page", "key": "target_page" } } ], "ok": false } ``` # Send Search Events Source: https://docs.glood.ai/api-reference/search/headless/events POST /api/storefront/v1/headless/events Ingest storefront / personalization events (standard Shopify pixel events and custom `glood:search:*` attribution events). Shop is taken from `x-shop`. Auth: `Authorization: Bearer ` + `x-shop`. ```json 200 theme={null} { "ok": true } ``` ```json 400 - missing identity theme={null} { "ok": false, "error": "At least one of visitor_id or client_id is required" } ``` ```json 400 - validation theme={null} { "ok": false, "error": [ { "message": "\"channel\" must be one of [HYDROGEN, HEADLESS, MOBILE]", "path": ["channel"], "type": "any.only", "context": { "label": "channel", "key": "channel" } } ] } ``` ## Event payload structure Every request posts one event in the same envelope. All fields are snake\_case. The full request body: ```json theme={null} { "channel": "HEADLESS", "visitor_id": "gl_s_uid_9f2c", "client_id": "c_18a4", "customer_id": "7234891234567", "session_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", "page_type": "search", "page_url": "https://your-store.com/search?q=shoe", "cart_identifier": "cart-token?key=abc123", "cart": { "cost": { "totalAmount": { "amount": 49.99, "currencyCode": "USD" } } }, "customer": { "id": "7234891234567", "email": "jane@example.com", "phone": "+14155550100" }, "customer_privacy": { "analytics_processing_allowed": true, "marketing_allowed": true, "preferences_processing_allowed": true, "sale_of_data_allowed": false }, "event": { "id": "b7f91c2e-1d44-4b50-8888-8dd25736052a", "client_id": "c_18a4", "name": "", "type": "standard | custom", "timestamp": "2026-08-05T10:30:00.000Z", "context": { "document": { "title": "Search", "referrer": "https://your-store.com/", "character_set": "UTF-8", "location": { "href": "https://your-store.com/search?q=shoe", "pathname": "/search", "search": "?q=shoe", "hash": "", "host": "your-store.com", "hostname": "your-store.com", "origin": "https://your-store.com", "port": "", "protocol": "https:" } }, "navigator": { "user_agent": "Mozilla/5.0 ...", "language": "en-US", "languages": ["en-US", "en"], "cookie_enabled": true }, "window": { "screen": { "width": 1920, "height": 1080 } } }, "data": {}, "custom_data": {} } } ``` ### Top-level fields | Field | Type | Required | Description | | - | - | - | - | | `channel` | string | βœ“ | `HYDROGEN`, `HEADLESS`, or `MOBILE` | | `event` | object | βœ“ | The event envelope (below) | | `visitor_id` | string | βœ“\* | Anonymous persistent visitor UID. \*At least one of `visitor_id` / `client_id` is required | | `client_id` | string | βœ“\* | Client/device id, persists across sessions | | `customer_id` | string | β€” | Shopify customer id when logged in | | `session_id` | string | β€” | Browsing-session id β€” the unit of funnel and attribution analytics. The server generates a UUID when absent; send a stable one per visit for accurate analytics | | `page_type` | string | β€” | Page type the event fired from | | `page_url` | string | β€” | URL the event fired from | | `cart_identifier` | string | β€” | Cart token/key identifier (`?key=`) | | `cart` | object | β€” | Cart state at event time (Shopify cart shape) | | `customer` | object | β€” | Customer info at event time (`id`, `email`, `phone`) | | `customer_privacy` | object | β€” | Consent flags: `analytics_processing_allowed`, `marketing_allowed`, `preferences_processing_allowed`, `sale_of_data_allowed` (booleans) | ### The `event` object | Field | Type | Required | Description | | - | - | - | - | | `id` | string | βœ“ | Unique event id (UUID) | | `name` | string | βœ“ | Event name β€” a standard Shopify event name or a `glood:` custom event name (see below) | | `type` | string | βœ“ | `standard` or `custom` | | `timestamp` | string | βœ“ | ISO 8601 event time, must be within Β±2 days of now | | `context` | object | βœ“ | Browser context β€” see below | | `data` | object | βœ“ when `type=standard` | The Shopify standard event payload (may be `{}`) | | `custom_data` | object | βœ“ when `type=custom` | Must contain a `track` object (see [Glood search events](#glood-search-events)) | | `client_id` | string | β€” | Client id carried on the event; defaults from the top-level identity | ### The `context` object All context keys are snake\_case on the wire. Unknown keys are accepted but only the fields marked as persisted below are stored on the event; anything else is discarded at ingestion. | Field | Required | Persisted | Description | | - | - | - | - | | `navigator.user_agent` | βœ“ | βœ“ | Client user-agent string β€” browser, OS, and device are derived from it server-side | | `navigator.language` | β€” | βœ“ | Client language (e.g. `en-US`) | | `navigator.cookie_enabled` | β€” | βœ“ | Whether cookies are enabled | | `navigator.languages` | β€” | β€” | Accepted, not persisted | | `document.location` | β€” | βœ“ | Full URL breakdown β€” `href`, `pathname`, `search`, `hash`, `host`, `hostname`, `origin`, `port`, `protocol` β€” persisted as sent. Not validated as required, but always send it: analytics scope page and session funnels by `document.location.pathname` (e.g. a `page_viewed` under `/search` counts toward the search-page funnel). Events without it are accepted but can't be attributed to a surface | | `document.title` | β€” | βœ“ | Page title | | `document.referrer` | β€” | βœ“ | Referring URL | | `document.character_set` | β€” | βœ“ | Document character set (e.g. `UTF-8`) | | `window.screen` | β€” | βœ“ | Screen dimensions (`width`, `height`) | | `window.inner_width`, `window.inner_height`, `window.outer_width`, `window.outer_height`, `window.page_x_offset`, `window.page_y_offset`, `window.screen_x`, `window.screen_y`, `window.scroll_x`, `window.scroll_y`, `window.location`, `window.origin` | β€” | β€” | Accepted, not persisted | > [!WARNING] > > Shopify's web pixel emits context in **camelCase** (`userAgent`, `cookieEnabled`, > `characterSet`). The headless API is snake\_case: a body sent with `navigator.userAgent` is > **rejected** with `"navigator.user_agent" is required`, and camelCase fields like > `characterSet` pass validation but are silently dropped. Convert the pixel context to > snake\_case before posting. What changes per event is `event.name`, `event.type`, and where the payload lives: * **Standard events** β€” Shopify standard (pixel) events. `type: "standard"`, payload in `event.data`. * **Glood search events** β€” custom attribution events emitted by the Glood search app. `type: "custom"`, payload in `event.custom_data.track`. ### Standard search events Any [Shopify standard event](https://shopify.dev/docs/api/web-pixels-api/standard-events) can be forwarded: `page_viewed`, `product_viewed`, `collection_viewed`, `cart_viewed`, `search_submitted`, `product_added_to_cart`, `product_removed_from_cart`, `checkout_started`, `checkout_completed`, and the other checkout events. `event.data` carries the standard event's payload as defined by Shopify. Some standard events (`page_viewed`) have an empty `data` by design β€” their information lives in `event.context.document`. ```json search_submitted theme={null} { "channel": "HEADLESS", "visitor_id": "gl_s_uid_9f2c", "event": { "id": "b7f91c2e-1d44-4b50-8888-8dd25736052a", "name": "search_submitted", "type": "standard", "timestamp": "2026-08-05T10:30:00.000Z", "context": { "document": { "title": "Search", "location": { "href": "https://your-store.com/search?q=shoe", "pathname": "/search", "search": "?q=shoe" } }, "navigator": { "user_agent": "Mozilla/5.0 ..." }, "window": { "screen": { "width": 1920, "height": 1080 } } }, "data": { "searchResult": { "query": "shoe" } } } } ``` ### Glood search events Custom attribution events use `type: "custom"` and carry a `track` object under `event.custom_data`. All `track` fields are optional; always send `request_id` (from the search response) when you have it β€” it ties the interaction back to the serve. | Field | Type | Description | | - | - | - | | `request_id` | string | `request_id` from the search response | | `search_term` | string | The search term | | `search_type` | string | `text` or `image` | | `source` | string | Where the interaction originated (e.g. `instant`, `search_page`) | | `page_type` | string | Page type of the interaction | | `products` | array | `{ product_id, variant_id?, quantity? }` β€” products involved | | `filters` | array | `{ key, value }` β€” filter selections (`value` is an array, or `null` when nothing is selected) | | `checkout_token` | string | Checkout token, for conversion attribution | | `campaign` | string | Campaign identifier | The examples below show `event.name` and `event.custom_data` β€” the rest of the envelope is identical to the one above. #### glood:search\_result\_rendered Send when search results are rendered / enter the viewport. `products` lists the rendered results; include `filters` when the result set was rendered with facets applied: ```json theme={null} { "name": "glood:search_result_rendered", "type": "custom", "custom_data": { "track": { "request_id": "req_01j8x2v9", "search_term": "shoe", "search_type": "text", "source": "search_page", "page_type": "search", "products": [ { "product_id": "9311227838783" }, { "product_id": "9311227838784" } ], "filters": [{ "key": "color", "value": ["red"] }] } } } ``` #### glood:search\_result\_clicked Send when a result is clicked. `products` carries the clicked product; include the filters active at click time: ```json theme={null} { "name": "glood:search_result_clicked", "type": "custom", "custom_data": { "track": { "request_id": "req_01j8x2v9", "search_term": "shoe", "search_type": "text", "source": "search_page", "products": [ { "product_id": "9311227838783", "variant_id": "48792371233087" } ], "filters": [{ "key": "color", "value": ["red"] }] } } } ``` #### glood:search\_filter\_appeared Send when the filter UI is rendered for a result set. `filters` lists the facets shown, with `value: null` while nothing is selected: ```json theme={null} { "name": "glood:search_filter_appeared", "type": "custom", "custom_data": { "track": { "request_id": "req_01j8x2v9", "search_term": "shoe", "search_type": "text", "source": "search_page", "filters": [ { "key": "color", "value": null }, { "key": "price", "value": null } ] } } } ``` #### glood:search\_filter\_updated Send when a facet is applied or changed. `filters` carries the full current selection (not the delta): ```json theme={null} { "name": "glood:search_filter_updated", "type": "custom", "custom_data": { "track": { "request_id": "req_01j8x2v9", "search_term": "shoe", "search_type": "text", "source": "search_page", "filters": [{ "key": "color", "value": ["red", "blue"] }] } } } ``` > [!NOTE] > > The same `track` shape is used by the other custom search events > (`glood:instant_search_triggered`, `glood:instant_search_rendered`, > `glood:image_search_triggered`, `glood:image_search_results_rendered`, > `glood:search:add_to_cart`) β€” see the `event.name` enum in the schema for the full list. # Filter Aggregations Source: https://docs.glood.ai/api-reference/search/headless/filter-aggregations POST /api/storefront/v1/headless/filter-aggregations Live Elasticsearch facet counts for a given query + applied filters. Auth: `Authorization: Bearer ` + `x-shop`. ```json 200 theme={null} { "aggregations": { "color": { "type": "terms", "data_type": "option", "buckets": [ { "value": "red", "label": "Red", "count": 42, "enabled": true, "is_others": false }, { "value": "blue", "label": "Blue", "count": 30, "enabled": true, "is_others": false } ], "has_more": false, "other_count": 0 }, "price": { "type": "range", "data_type": "price", "buckets": [ { "value": "0-50", "label": "$0 – $50", "count": 100 } ], "stats": { "min": 5, "max": 499, "avg": 60, "sum": 14400, "count": 240 } } }, "facets": [ { "id": 1, "key": "color", "title": "Color", "data_type": "option", "attribute_type": "option" }, { "id": 2, "key": "price", "title": "Price", "data_type": "number", "attribute_type": "price" } ], "tree": { "id": 5, "target_page": "search", "target_id": 10, "is_default": false }, "metadata": { "total_products": 240, "query_time": 30, "region": "toronto" } } ``` ```json 400 theme={null} { "error": [ { "message": "\"applied_filters[0].key\" is required", "path": ["applied_filters", 0, "key"], "type": "any.required", "context": { "label": "applied_filters[0].key", "key": "key" } } ], "ok": false } ``` # Filters Source: https://docs.glood.ai/api-reference/search/headless/filters POST /api/storefront/v1/headless/filters DB-driven facet (filter) definitions for the resolved filter tree. No live counts (see filter-aggregations). Auth: `Authorization: Bearer ` + `x-shop`. ```json 200 theme={null} { "facets": [ { "id": 1, "key": "color", "title": "Color", "type": "color", "attribute_type": "option", "position": 1, "expanded": true, "visible": true, "operator": "or", "settings": { "multi_select": true, "show_count": true, "collapsible": true, "searchable": false, "show_more": true, "max_display": 10 }, "min": null, "max": null, "step": null, "unit": null, "suffix": null, "values": [ { "value": "red", "label": "Red", "count": null, "position": 1, "hex": "#ff0000", "image": null, "order": null } ] }, { "id": 2, "key": "price", "title": "Price", "type": "number", "attribute_type": "price", "position": 2, "expanded": true, "visible": true, "operator": "or", "settings": { "multi_select": false, "show_count": true, "collapsible": true, "searchable": false, "show_more": false, "max_display": 10 }, "min": 0, "max": 1000, "step": 1, "unit": "$", "suffix": "", "values": [] } ], "tree": { "id": 5, "target_page": "search", "target_ids": [10], "is_default": false, "title": "Search filters", "settings": {} }, "metadata": { "locale": "en-US", "market": null, "region": "toronto", "total_facets": 2 } } ``` ```json 200 - no tree configured theme={null} { "facets": [], "tree": { "id": null, "target_page": "search", "target_ids": [], "is_default": true, "title": "Filters", "settings": {} }, "metadata": { "locale": "en-US", "market": null, "region": "toronto", "total_facets": 0 } } ``` ```json 400 theme={null} { "error": [ { "message": "\"tree\" must be a number", "path": ["tree"], "type": "number.base", "context": { "label": "tree", "key": "tree" } } ], "ok": false } ``` # Image Search Source: https://docs.glood.ai/api-reference/search/headless/image-search POST /api/storefront/v1/headless/image-search Visual (image) search. Accepts a multipart file OR a JSON base64 image / data: URL / http(s) image URL (exactly one source). Images are strictly validated before search. Auth: `Authorization: Bearer ` + `x-shop`. ```json 200 theme={null} { "status": "ok", "products": [ { "product_id": 9311227838783, "title": "Running Shoe", "handle": "running-shoe", "product_type": "Shoes", "vendor": "Acme", "tags": ["sale", "summer"], "price": 49.99, "compare_at_price": 69.99, "display_price": 49.99, "display_compare_at_price": 69.99, "display_currency": "USD", "original_currency": "USD", "currency_rate": 1, "available_for_sale": true, "is_in_stock": true, "total_inventory": 42, "trending_rank": 3, "sales_rank": 7, "image": { "id": "gid://shopify/ProductImage/1", "url": "https://cdn.shopify.com/s/files/1/shoe.jpg", "width": 800, "height": 800, "alt_text": "Running Shoe" }, "featured_media": null, "media": [], "options": [ { "id": 111, "name": "Size", "position": 1, "values": ["S", "M", "L"] } ], "variants": [], "metafields": [] } ], "pagination": { "total": 60, "page": 1, "limit": 20, "total_pages": 3, "has_next_page": true, "has_prev_page": false }, "search_metadata": { "processing_time": 340, "search_type": "image_vector", "image_analysis": null, "image_caption": "a red running shoe", "search_text": "red running shoe", "has_embedding": true, "errors": [], "dominant_colors": ["#ff0000"] } } ``` ```json 400 - invalid image theme={null} { "error": "Image must be one of jpeg, png, webp" } ``` # Headless Search Init Source: https://docs.glood.ai/api-reference/search/headless/init POST /api/storefront/v1/headless/init Session bootstrap for the search suite. Call once per session (the `@glood/hydrogen` GloodProvider runs it automatically on mount) before instant/full search. Resolves the visitor, returns their history (browsed / cart / purchased product ids), a lean feature-flag config (no filter definitions, no filter tree, no templates), the Shopify storefront token and a fresh `visit_id`. Auth: `Authorization: Bearer ` + `x-shop`. ```json 200 theme={null} { "visit_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", "visitor_id": "gl_s_uid_9f2c", "client_id": "c_18a4", "customer_id": null, "visitor": { "browsed_products": [9311227838783, 9311227838784], "cart_products": [9311227838785], "purchased_products": [] }, "config": { "instant_search_enabled": true, "search_result_page_enabled": true, "image_search_enabled": true, "personalization_enabled": false, "personalization_config": null, "auto_spell_correct_enabled": true, "instant_search_objects": ["product", "collection", "page", "auto_suggestion"], "exclude_out_of_stock": false, "move_out_of_stock_at_end": true, "site_wide_search": {}, "search_result_count": 10, "default_ordering": "relevance", "minimum_type_ahead_input_count": 2, "default_search_result_page_size": 20, "search_page_autocomplete_enabled": true, "search_page_handle": "search", "image_search_pages": null, "settings": {} }, "token": "shpat_xxx", "metadata": { "region": "toronto", "locale": "en-US", "market": null } } ``` ```json 400 theme={null} { "error": [ { "message": "\"page_type\" must be one of [product_page, collection, home, cart, order_confirm, blog, ajax_cart, 404, checkout, returns, search, other]", "path": ["page_type"], "type": "any.only", "context": { "label": "page_type", "key": "page_type" } } ], "ok": false } ``` # Instant Search Source: https://docs.glood.ai/api-reference/search/headless/instant-search POST /api/storefront/v1/headless/instant-search Type-ahead search in a single call: products / collections / pages / articles + keyword suggestions + autocorrect, plus an empty-state trending block. Auth: `Authorization: Bearer ` + `x-shop`. ```json 200 - product_details view theme={null} { "query": "sho", "corrected_query": "shoe", "autocorrect": { "original_query": "sho", "corrected_query": "shoe", "confidence": 0.92, "corrections": [], "alternatives": [] }, "suggestions": [ { "text": "shoes", "type": "keyword", "object_count": 120, "search_count": 45 } ], "products": { "results": [ { "product_id": 9311227838783, "title": "Running Shoe", "handle": "running-shoe", "product_type": "Shoes", "vendor": "Acme", "tags": ["sale", "summer"], "price": 49.99, "compare_at_price": 69.99, "display_price": 49.99, "display_compare_at_price": 69.99, "display_currency": "USD", "original_currency": "USD", "currency_rate": 1, "available_for_sale": true, "is_in_stock": true, "total_inventory": 42, "trending_rank": 3, "sales_rank": 7, "image": { "id": "gid://shopify/ProductImage/1", "url": "https://cdn.shopify.com/s/files/1/shoe.jpg", "width": 800, "height": 800, "alt_text": "Running Shoe" }, "featured_media": null, "media": [], "options": [ { "id": 111, "name": "Size", "position": 1, "values": ["S", "M", "L"] } ], "variants": [ { "variant_id": 456, "title": "M", "display_name": "Running Shoe - M", "sku": "RS-M", "position": 1, "price": 49.99, "compare_at_price": 69.99, "available_for_sale": true, "is_in_stock": true, "sellable_online_quantity": 10, "selected_options": [ { "name": "Size", "value": "M" } ], "image": null } ], "metafields": [ { "namespace": "custom", "key": "material", "value": "leather" } ] } ], "total": 120 }, "collections": { "results": [ { "collection_id": 1, "title": "Shoes", "handle": "shoes", "image": null } ], "total": 3 }, "pages": { "results": [ { "page_id": 1, "title": "Size Guide", "handle": "size-guide" } ], "total": 1 }, "articles": { "results": [], "total": 0 }, "trending": { "searches": [], "products": [] }, "metadata": { "query_time": 12, "locale": "en-US", "market": null, "min_query_length": 2 } } ``` ```json 200 - empty query (trending) theme={null} { "query": "", "corrected_query": null, "autocorrect": null, "suggestions": [], "products": { "results": [], "total": 0 }, "collections": { "results": [], "total": 0 }, "pages": { "results": [], "total": 0 }, "articles": { "results": [], "total": 0 }, "trending": { "searches": [ { "term": "sale", "translated_term": "sale", "search_count": 300 } ], "products": [] }, "metadata": { "query_time": 8, "locale": "en-US", "market": null, "min_query_length": 2 } } ``` ```json 400 theme={null} { "error": [ { "message": "\"limit\" must be less than or equal to 100", "path": ["limit"], "type": "number.max", "context": { "limit": 100, "value": 500, "label": "limit", "key": "limit" } } ], "ok": false } ``` When `publication_ids` is sent, the empty-query trending products are ordered by trending within those sales channels. # Search Source: https://docs.glood.ai/api-reference/search/headless/search POST /api/storefront/v1/headless/search Full product search (hybrid text + vector) with applied facets, sort, page-based pagination and optional inline aggregations. Auth: `Authorization: Bearer ` + `x-shop`. ```json 200 - product_details view theme={null} { "status": "ok", "request_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", "products": [ { "product_id": 9311227838783, "title": "Running Shoe", "handle": "running-shoe", "product_type": "Shoes", "vendor": "Acme", "tags": ["sale", "summer"], "price": 49.99, "compare_at_price": 69.99, "display_price": 49.99, "display_compare_at_price": 69.99, "display_currency": "USD", "original_currency": "USD", "currency_rate": 1, "available_for_sale": true, "is_in_stock": true, "total_inventory": 42, "trending_rank": 3, "sales_rank": 7, "image": { "id": "gid://shopify/ProductImage/1", "url": "https://cdn.shopify.com/s/files/1/shoe.jpg", "width": 800, "height": 800, "alt_text": "Running Shoe" }, "featured_media": null, "media": [], "options": [ { "id": 111, "name": "Size", "position": 1, "values": ["S", "M", "L"] } ], "variants": [ { "variant_id": 456, "title": "M", "display_name": "Running Shoe - M", "sku": "RS-M", "position": 1, "price": 49.99, "compare_at_price": 69.99, "available_for_sale": true, "is_in_stock": true, "sellable_online_quantity": 10, "selected_options": [ { "name": "Size", "value": "M" } ], "image": null } ], "metafields": [ { "namespace": "custom", "key": "material", "value": "leather" } ] } ], "pagination": { "total": 240, "page": 1, "limit": 20, "total_pages": 12, "has_next_page": true, "has_prev_page": false, "next_page": 2, "prev_page": null }, "facets": [ { "key": "color", "type": "terms", "aggregation": { "buckets": [ { "value": "red", "count": 42, "selected": true } ] } } ], "metadata": { "query_time": 40, "total_time": 55, "region": "toronto", "search_type": "hybrid" } } ``` ```json 200 - product_ids view theme={null} { "status": "ok", "request_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", "products": [ { "product_id": 9311227838783 }, { "product_id": 9311227838784 } ], "pagination": { "total": 240, "page": 1, "limit": 20, "total_pages": 12, "has_next_page": true, "has_prev_page": false, "next_page": 2, "prev_page": null }, "facets": [], "metadata": { "query_time": 38, "total_time": 41, "region": "toronto", "search_type": "hybrid" } } ``` ```json 400 theme={null} { "error": [ { "message": "\"sort\" must be one of [relevance, title_asc, title_desc, price_asc, price_desc, best_selling, oldest, newest, collection_default]", "path": ["sort"], "type": "any.only", "context": { "label": "sort", "key": "sort" } } ], "ok": false } ``` # Search APIs Source: https://docs.glood.ai/api-reference/search/introduction Versioned, Bearer-authenticated headless APIs for AI-powered search and discovery Glood.AI Search APIs expose the storefront search and discovery engine as a set of **versioned, self-contained headless APIs** (`POST /api/storefront/v1/headless/*`). Consumers β€” the `@glood/hydrogen` SDK, mobile apps, and custom storefronts β€” call them directly and get everything they need in one response (full product objects, facets, pagination), with no re-hydration from Shopify required. ## Authentication Every endpoint requires two headers: | Header | Value | | - | - | | `Authorization` | `Bearer ` storefront token | | `x-shop` | `your-store.myshopify.com` (the shop is resolved from this header only) | Request and response bodies are **snake\_case**. Product-returning endpoints accept a `view` of `product_details` (default) or `product_ids`, and an optional identity triple (`visitor_id`, `client_id`, `customer_id`) for personalization. > [!NOTE] > > Send the same anonymous `visitor_id` before and after login, and add `customer_id` > when the shopper is authenticated. Never overwrite `visitor_id` with the customer id β€” > the two are linked server-side into one visitor profile. ## Base URLs Search runs on its own host, independent of the recommendations API. Every endpoint is a path (`/api/storefront/v1/headless/*`) on one of these hosts β€” the path, headers, and request/response bodies are **identical** regardless of which host you call. Only the origin changes. These are the same URLs the Glood Search Shopify app embed uses, so a headless integration and a theme integration hit exactly the same routes. | Purpose | Base URL | | - | - | | Default (global) | `https://search.glood.ai` | | Edge (regional) | `https://.edge.glood.ai` | Use the default host unless you have been asked to route to the edge. Point your client at one base URL and prefix it to every endpoint path, e.g. `POST https://search.glood.ai/api/storefront/v1/headless/search`. ### Edge URLs Edge hosts serve requests from a location close to the shopper for lower latency. They expose the same routes as the default host β€” swap `search.glood.ai` for `.edge.glood.ai` and nothing else changes. Available regions: | Region | Base URL | | - | - | | Mumbai | `https://mum.edge.glood.ai` | | Toronto | `https://tor.edge.glood.ai` | Edge must be turned on for the shop from the Glood admin before these hosts serve results β€” see [Enable Edge Delivery](/ai-search-merchandising/enable-edge-delivery) for the steps and the regions available. > [!NOTE] > > Add whichever host(s) you call to your Content Security Policy `connect-src` β€” the default > `https://search.glood.ai` and/or any `https://.edge.glood.ai` you route to β€” or the > browser blocks the requests. ## Endpoints > [card] [Init](/api-reference/search/headless/init) > > Session bootstrap β€” resolve the visitor, load their history, and get lean feature flags + the storefront token in one call. > [card] [Config](/api-reference/search/headless/config) > > Feature flags, filter definitions, filter tree, shop, analytics, translations and the storefront token. > [card] [Instant Search](/api-reference/search/headless/instant-search) > > Type-ahead products / collections / pages / articles + suggestions + autocorrect + trending. > [card] [Filters](/api-reference/search/headless/filters) > > DB-driven facet (filter) definitions for the resolved tree β€” no live counts. > [card] [Filter Aggregations](/api-reference/search/headless/filter-aggregations) > > Live Elasticsearch facet counts for a query + applied filters. > [card] [Search](/api-reference/search/headless/search) > > Full hybrid (text + vector) product search with facets, sort, pagination and inline aggregations. > [card] [Image Search](/api-reference/search/headless/image-search) > > Visual search from a multipart file, base64 image, data: URL, or http(s) image URL. > [card] [Events](/api-reference/search/headless/events) > > Ingest standard Shopify events and custom `glood:search:*` attribution events. ## Using the SDK If you build on Shopify Hydrogen, the [`@glood/hydrogen` Search SDK](/for-developers/glood-hydrogen-sdk/search) wraps every endpoint with typed hooks (`useSearch`, `useInstantSearch`, `useSearchConfig`), standalone `fetch*` functions for SSR, and automatic event forwarding. # Personalized Recommendations Source: https://docs.glood.ai/features/ai-personalized-recommendations Drive more sales with intelligent product recommendations tailored to each shopper Transform your Shopify store into a personalized shopping experience with Glood.AI's intelligent recommendation engine. Our AI technology analyzes customer behavior in real-time to deliver highly relevant product suggestions that boost engagement and sales. ## Key Benefits ### Increased Conversion Rates * Convert up to 3x more browsers into buyers with personalized recommendations * Show the right products to the right customers at the right time * Reduce bounce rates by keeping shoppers engaged with relevant suggestions ### Higher Average Order Value * Boost AOV by 20-30% through intelligent cross-selling * Surface complementary products that make sense for each customer * Encourage larger cart sizes with "Complete the Look" recommendations ### Enhanced Customer Experience * Create a personalized shopping journey for every visitor * Help customers discover products they'll love * Build loyalty through relevant product discovery ## Powerful Features ### Smart Product Discovery * Real-time behavioral analysis * Purchase history-based recommendations * Similar product suggestions * "Frequently Bought Together" bundles * Category affinity detection ### Flexible Placement Options * Homepage personalized sections * Product detail page recommendations * Cart page suggestions * Collection page recommendations * Custom placement anywhere in your store ### Advanced Customization * Fully customizable widget design * Mobile-optimized layouts * A/B testing capabilities * Product filtering rules * Custom recommendation algorithms ## Easy Setup & Management Getting started with Glood.AI recommendations takes minutes: 1. Install the Glood.AI app from the Shopify App Store 2. Enable the app embed in your theme settings 3. Create your first recommendation section using our visual editor 4. Watch your conversion rates improve No coding required - our visual editor makes it easy to add and customize recommendation sections throughout your store. ## Proven ROI Glood.AI customers typically see: * 15-30% increase in revenue * 2-3x higher conversion rates * 20-30% larger average order values * ROI of 10-20x on app investment > [!NOTE] > > Our AI engine continuously learns and optimizes recommendations based on your store's unique data, delivering better results over time. ## Start Personalizing Today Join thousands of successful Shopify merchants using Glood.AI to deliver personalized shopping experiences. Our free plan lets you try all features risk-free. Ready to boost your sales with AI-powered recommendations? [Install Glood.AI](https://apps.shopify.com/recommendation-kit) today and see the difference personalization can make for your store. # AI Search & Merchandising Source: https://docs.glood.ai/features/ai-search-merchandising Optimize your store search and product placement with AI-powered merchandising Transform your store's search experience with Glood.AI's intelligent search and merchandising capabilities. Our AI technology helps shoppers find exactly what they're looking for while strategically promoting your most profitable products. ## Key Benefits ### Improved Search Relevance * Deliver more accurate search results using AI-powered semantic understanding * Handle misspellings and variations automatically * Support natural language queries for better results * Boost conversion rates with relevant product suggestions ### Smart Merchandising * Automatically promote high-margin products * Surface trending and popular items * Customize product rankings based on your business goals * Balance inventory levels through strategic placement ### Enhanced Shopping Experience * Reduce search abandonment with instant results * Help customers discover relevant products faster * Provide personalized search suggestions * Support faceted navigation and filtering ## Powerful Features ### Intelligent Search * Natural language processing * Typo tolerance * Synonym matching * Search analytics and insights * Multi-language support ### Advanced Merchandising Rules * Custom ranking strategies * Automated product boosting * Category-specific rules * Seasonal promotions * Inventory-aware placement ### Visual Search * Image-based product search * Similar product recommendations * Style matching * Visual filters ## Easy Setup Getting started with Glood.AI search takes minutes: 1. Install the Glood.AI app from the Shopify App Store 2. Enable search functionality in your settings 3. Configure your merchandising rules 4. Watch your search conversion rates improve No coding required - our visual interface makes it easy to optimize your store's search and merchandising. > [!NOTE] > > For advanced customization options and API access, check out our [Developer Guide](/for-developers/introduction). # AI Upsell Bundles Source: https://docs.glood.ai/features/ai-upsell-bundles Boost sales with intelligent product bundles and upsell recommendations Transform your Shopify store's upselling strategy with Glood.AI's intelligent bundle recommendations. Our AI technology analyzes purchase patterns and product relationships to create compelling bundle offers that increase average order value and conversion rates. ## Key Benefits ### Increased Average Order Value * Boost AOV by 25-35% through strategic bundle offers * Create compelling multi-product discounts * Encourage larger purchases with personalized bundle suggestions * Optimize pricing strategies for maximum revenue ### Higher Conversion Rates * Convert more browsers into buyers with targeted bundle offers * Show the most relevant product combinations * Reduce decision fatigue with curated bundles * Build trust through intelligent recommendations ### Automated Bundle Creation * Let AI identify the best product combinations * Save time with automated bundle suggestions * Update bundles based on real-time data * Maintain optimal inventory balance ## Powerful Features ### Smart Bundle Generation * AI-powered product matching * Purchase pattern analysis * Complementary product detection * Price optimization algorithms * Inventory-aware recommendations ### Flexible Display Options * Product page bundle offers * Cart page upsells * Collection page bundles * Custom placement anywhere * Mobile-optimized layouts ### Advanced Customization * Fully customizable bundle displays * Dynamic pricing rules * Bundle exclusion controls * A/B testing capabilities * Seasonal promotion support ## Easy Setup & Management Getting started with Glood.AI bundles is simple: 1. Install the Glood.AI app from the Shopify App Store 2. Enable bundle recommendations in your settings 3. Configure your bundle rules and displays 4. Watch your average order value grow No coding required - our visual interface makes it easy to create and manage product bundles throughout your store. > [!NOTE] > > For advanced customization options and API access, check out our [Developer Guide](/for-developers/introduction). # Images and Embeds Source: https://docs.glood.ai/features/checkout-upsell Add image, video, and other HTML elements ![](https://mintlify-assets.b-cdn.net/bigbend.jpg) ## Image ### Using Markdown The [markdown syntax](https://www.markdownguide.org/basic-syntax/#images) lets you add images using the following code ```md theme={null} ![title](/path/image.jpg) ``` Note that the image file size must be less than 5MB. Otherwise, we recommend hosting on a service like [Cloudinary](https://cloudinary.com/) or [S3](https://aws.amazon.com/s3/). You can then use that URL and embed. ### Using Embeds To get more customizability with images, you can also use [embeds](/writing-content/embed) to add images ```html theme={null} ``` ## Embeds and HTML elements [YouTube video player](https://www.youtube.com/embed/4KzFe50RQkQ) > [!TIP] > > Mintlify supports [HTML tags in Markdown](https://www.markdownguide.org/basic-syntax/#html). This is helpful if you prefer HTML tags to Markdown syntax, and lets you create documentation with infinite flexibility. ### iFrames Loads another HTML page within the document. Most commonly used for embedding videos. ```html theme={null} ``` # Navigation Source: https://docs.glood.ai/features/discounts The navigation field in mint.json defines the pages that go in the navigation menu The navigation menu is the list of links on every website. You will likely update `mint.json` every time you add a new page. Pages do not show up automatically. ## Navigation syntax Our navigation syntax is recursive which means you can make nested navigation groups. You don't need to include `.mdx` in page names. ```json Regular Navigation theme={null} "navigation": [ { "group": "Getting Started", "pages": ["quickstart"] } ] ``` ```json Nested Navigation theme={null} "navigation": [ { "group": "Getting Started", "pages": [ "quickstart", { "group": "Nested Reference Pages", "pages": ["nested-reference-page"] } ] } ] ``` ## Folders Simply put your MDX files in folders and update the paths in `mint.json`. For example, to have a page at `https://yoursite.com/your-folder/your-page` you would make a folder called `your-folder` containing an MDX file called `your-page.mdx`. > [!WARNING] > > You cannot use `api` for the name of a folder unless you nest it inside another folder. Mintlify uses Next.js which reserves the top-level `api` folder for internal server calls. A folder name such as `api-reference` would be accepted. ```json Navigation With Folder theme={null} "navigation": [ { "group": "Group Name", "pages": ["your-folder/your-page"] } ] ``` ## Hidden Pages MDX files not included in `mint.json` will not show up in the sidebar but are accessible through the search bar and by linking directly to them. # Upsell Promotions Source: https://docs.glood.ai/features/upsell-promotions Drive AOV with two new promotion types β€” Product Upsell (Buy X Get Y) and Free Gift on cart value β€” surfaced on PDP and in the cart drawer. Glood **Upsell Promotions** add two merchant-controlled promotion types to your store that live on the PDP and inside the cart drawer / cart page. Both are powered by Shopify Functions (one Discount Function per type plus a shared Cart Transform Function), so the discount and gift logic survive checkout authoritatively. ## The two promotion types > [card] Product Upsell (Buy X Get Y) > > Trigger by a specific product. When a customer buys X, they can add 1+ pool items (Y) at a configured price: flat price, percent off, or a fixed amount off. Per-pool-item pricing overrides supported. > [card] Free Gift (cart-value tiers) > > Trigger by cart subtotal crossing one or more thresholds. The chosen gift variant is auto-added to the cart at €0 by the Cart Transform Function β€” no manual checkout step. Each promotion type registers as its own entry in Shopify's "Select discount type" modal so the merchant always knows which one they're creating: * **Glood Product Upsell (Buy X Get Y)** β€” pick offers * **Glood Free Gift** β€” cart-value tier offers ## What the customer sees ### On the product page When a merchant has placed the **Glood Upsell for PDP** theme block: * **Title + subtitle** describing the offer (e.g. "+€1 Add-On Gifts β€” Choose premium accessories for just €1 with your NAS purchase"). * **Slot meter** β€” "You have **1** add-on gift slot." | "**1 / 1** Selected" β€” adapts live as the customer changes the main-product quantity (slot count = `slotsPerMainQty Γ— qty`, capped at `maxSlots`). * **Pool item cards** β€” checkbox + thumbnail + product name + price (struck-through compare price). The selected card expands to reveal a quantity stepper and, if the product has multiple variants, a variant selector. * **Free-gift section** β€” one panel per active free-gift offer (highest priority wins if multiple exist). Each tier renders as a card with three states: * **Locked** β€” "Spend €X more to unlock" * **Auto-added** (eligible, server-side Cart Transform pending) * **βœ“ In cart** (gift line confirmed present) ### In the cart drawer / cart page The **Glood Upsell for Cart** block surfaces: * Free-gift progress and "Auto-added" / "βœ“ In cart" states (same as PDP). * Pick offers triggered by the current cart contents but not yet redeemed ("Complete your order with…"). ## How offers are wired | Layer | Pick offer (Buy X Get Y) | Free-gift offer (cart-value) | | - | - | - | | Shopify Discount Function | `upsell-offer-discount` β€” applies per-pool-item pricing | `upsell-free-gift-discount` β€” applies 100% off on auto-injected gift line | | Cart Transform Function | β€” | `upsell-cart-transform` β€” injects the gift variant at \$0 when threshold met | | Storefront-readable data | `product.metafields.glood.upsell_pick_offers` (json, on each trigger product) | `shop.metaobjects.glood.values` filtered by `key == 'upsell_free_gift'` | The canonical JSON shape is the same across admin API, Shopify metafields, and the storefront blocks β€” see `web/backend/common/services/upsellOfferDiscount.js#toCanonicalPayload` in the app codebase. ## Setup 1. Install the Glood app and ensure your plan includes the **Upsell Promotions** feature. 2. From the Glood admin β†’ **Upsell Offers** β†’ create a pick or free-gift offer. Save and set status to **Active**. 3. In the Shopify theme editor: * Open a product template β†’ click your product-info section β†’ **Add block** β†’ search **"Glood Upsell for PDP"** β†’ drag under the description. * Open the cart-drawer section (and/or `/cart` page section) β†’ **Add block** β†’ search **"Glood Upsell for Cart"** β†’ drop in. 4. Visit a triggering product page or add a triggering product to the cart β€” the block renders the offer. > [!NOTE] > > Shopify's Cart Transform Function requires at least one **existing cart line** to anchor the injected gift. Configure free-gift offers with `minSubtotal > 0` so the customer has added something before they qualify. ## Multi-tier free gifts Free-gift offers support either **cumulative** or **exclusive** tier stacking: * **Cumulative** β€” every qualifying tier grants its reward. Customer crossing €50 and €100 thresholds gets both gifts. * **Exclusive** β€” only the highest qualifying tier grants its reward. Customer crossing both thresholds gets only the €100 gift. Set the mode in the Glood admin per offer. ## Combinations with other discounts Each promotion's `combinesWith` flags map directly to Shopify's discount-stacking model: | Glood admin field | Shopify `combinesWith.*` | | - | - | | Combine with other Glood offers | `productDiscounts: true` (lets multiple Glood offer lines coexist) | | Combine with Shopify automatic discounts | `productDiscounts / orderDiscounts: true` | | Combine with Shopify discount codes | `productDiscounts: true` (Shopify's automatic-vs-code rule lets a code stack on top) | ## Next steps > [card] [Theme integration & JS hooks](/for-developers/upsell-blocks-integration) > > Wire the block into custom themes, integrate the native variant + quantity selectors, and use the `window.Glood.upsell` pub/sub bus to react to selections, qty changes, and cart updates from your own theme code. # Default CSS Source: https://docs.glood.ai/for-developers/bundles/default-css Default bundle CSS template code reference # Default Bundle CSS The CSS template for bundle sections uses Liquid variables to enable dynamic theming. Colors, fonts, sizes, and spacing are all pulled from the template settings, allowing merchants to customize the appearance without editing CSS directly. The template applies different styles based on the active layout (`bundle` vs `bundle_component`) using Liquid conditionals. ```css theme={null} {% if config.layout == 'bundle_component' %} {% assign setting = template.settings.bundleComponent %} {% else %} {% assign setting = template.settings.bundle %} {% endif %} #gloodai_bundle_component_container { display: flex; flex-direction: column; gap: 2rem; border-radius: 0.3rem; font-family: 'Futura'; {% if config.layout == "bundle_component" %} border-top: 1px solid #DDDDDD; padding-top: 1.5rem; {% endif %} padding-bottom: 1.5rem; border-bottom: 1px solid #DDDDDD; } .rk-bundle-card { transition: all 0.3s ease-in-out; {% if config.layout == "bundle_component" %} background-color: {{ setting.backgroundColor | default: '#F9F9FA' }}; padding: 1.5rem 2.5rem 2.5rem 2.5rem; {% endif %} } .rk-p-c-product-image { width: {{ setting.productCard.image.width | default: 110 }}px; height: {{ setting.productCard.image.height | default: 133 }}px; object-fit: {{ setting.productCard.image.objectFit | default: 'cover' }}; background-repeat: no-repeat; background-size: {{ setting.productCard.image.objectFit | default: 'cover' }}; background-position: center; aspect-ratio: {{ setting.productCard.image.aspectRatio | replace: ":","/" }} } .rk-bundle-comp-title { margin: 0; display: block; font-size: {{ setting.productCard.title.size | default: '16px' }}; font-weight: {{ setting.productCard.title.weight | default: 500 }}; font-family: {{ setting.productCard.title.font | default: 'Futura' }}; letter-spacing: 0; text-align: left; color: {{ setting.productCard.title.color | default: '#000000' }}; } .rk-add-to-cart { background-color: {{ setting.atcBtn.backgroundColor | default: '#000000' }}; color: {{ setting.atcBtn.text.color | default: '#FFFFFF' }}; font-size: {{ setting.atcBtn.text.size | default: '12px' }}; font-weight: {{ setting.atcBtn.text.weight | default: 500 }}; font-family: {{ setting.atcBtn.text.font | default: "Futura" }}; width: 100%; border-radius: 4px; text-transform: uppercase; padding: 1.5rem 0 1.5rem 0; } .rk-product-price { font-weight: {{ setting.productCard.price.weight | default: 500 }}; font-size: {{ setting.productCard.price.size | default: '14px' }}; color: {{ setting.productCard.price.color | default: '#666666' }}; display: block; font-family: {{ setting.productCard.price.font | default: 'Futura' }}; } .rk-total-product { {% if config.layout=='bundle'%} font-size: 20px; {% else %} font-size: 16px; {% endif %} font-weight: 500; color: #000001; display: block; } ``` ## Key Styling Patterns ### Dynamic Theming with Liquid Variables All visual properties (colors, fonts, sizes) are pulled from `setting.productCard` and `setting.atcBtn`, allowing full customization through the [Settings](/for-developers/bundles/settings) configuration. ### Layout-Conditional Styles The CSS adapts based on `config.layout`: * **`bundle`** layout: Minimal container styling, larger title font (20px) * **`bundle_component`** layout: Background color, padding, border, smaller title font (16px) ### Image Handling Product images use configurable dimensions with `object-fit` and `aspect-ratio` from settings, ensuring consistent display across different product photos. # Default JavaScript Source: https://docs.glood.ai/for-developers/bundles/default-js Default bundle JavaScript hooks code reference # Default Bundle JavaScript The JavaScript template contains the lifecycle hooks that power bundle interactivity. Each hook is called at a specific point in the bundle's lifecycle and receives the bundle data along with utility functions. ```js theme={null} "use strict"; return { OnBundleRender: function OnBundleRender(bundle, utils, states) { const totalPrice = utils.currencyFormatter( bundle.products.reduce((acc, product) => { return ( acc + parseFloat( utils.getComponentPrice(product.id, states.selectedProductOptions, bundle) ) ) }, 0) ) const translations = utils.getTranslations({ data: bundle, productsCount: utils.getTotalProductsInbundles(bundle), totalPrice, }) const products = (bundle?.products ?? []).map((product) => ({ title: product.title, options: [ { name: 'Type', value: utils.getProductOptions(product.id, bundle) .map((option) => option.value) .join(', '), }, ], variants: utils.getProductOptions(product.id, bundle), image: product?.featuredImage?.url, dropdownPlaceholder: 'Select product', handle: product.handle, id: product.id, })) ?? [] return { products: products, translations } }, OnConfigLoad: function OnConfigLoad(bundle, utils) { return bundle }, OnVariantChange: function OnVariantChange(variantId, utils) { function changeVariantId(variantId) { const url = new URL(window.location); url.searchParams.set('variant', variantId); window.history.replaceState({}, '', url); } changeVariantId(variantId) }, OnAddToCart: function OnAddToCart(variantId, utils) { console.log('added', utils); }, OnAddedToCart: function OnAddedToCart(variantId, utils) { console.log('added to cart', utils); } }; ``` ## Hook Functions ### OnBundleRender The primary rendering hook. Transforms raw bundle data into the format consumed by the Liquid template. Calculates total price, resolves translations, and maps products with their options and variants. ### OnConfigLoad Called when bundle configuration is first loaded. Use this to modify or enrich the bundle data before any rendering occurs. By default, returns the bundle unchanged. ### OnVariantChange Fired when a customer selects a different variant. By default, updates the URL query parameter to reflect the selected variant ID. ### OnAddToCart Called immediately when the add-to-cart action is triggered, before the cart API request. Use this for pre-cart validation or UI updates. ### OnAddedToCart Called after a successful add-to-cart API response. Use this for post-cart actions like showing confirmation messages or triggering analytics. > [!NOTE] > > See the [Hooks](/for-developers/bundles/hooks) page for detailed parameter documentation and use cases for each hook. # Default Template Source: https://docs.glood.ai/for-developers/bundles/default-template Default bundle Liquid template code reference # Default Bundle Template The main Liquid template file for rendering bundle sections. The template handles two layout types (`bundle` and `bundle_component`) and includes loading skeleton states, product cards with variant selectors, pricing, and add-to-cart functionality. ## Template Structure The template is organized into these key sections: 1. **Layout detection** β€” assigns the correct settings based on `config.layout` 2. **Bundle component header** β€” collapsible header for the `bundle_component` layout 3. **Loading skeleton** β€” placeholder UI shown while bundle data loads 4. **Product cards** β€” image, title, price, variant/option selectors for each product 5. **Pricing and ATC** β€” total price display and add-to-cart container (component layout only) ```liquid theme={null} {% assign productComponentTitle = template.translations.productComponentTitle | replace: "{{count}}", bundle.images.length %} {% if config.layout == 'bundle_component' %} {% assign setting = template.settings.bundleComponent %} {% else %} {% assign setting = template.settings.bundle %} {% endif %} {% if config.layout == 'bundle_component' %}
{{ template.translations.productComponentTitle | replace: '{{count}}', bundle.productComponents.length }}
{% endif %}
{% if loading %} {% if bundle.optionsType == "product" and bundle.bundleType == "custom" %} {% if config.layout == "bundle" %} {{ template.translations.bundleSectionTitle | replace: "{{count}}", bundle.productComponents.length }} {% endif %} {% if config.layout == "bundle_component" %} {{ bundle.title }} {% endif %}
{% for component in bundle.productComponents %}
{{ component.image }} image
{% if forloop.index < products.size %} + {% endif %} {% endfor %}
{% endif %} {% else %} {% if bundle.optionsType == "product" and bundle.bundleType == "custom" %}
{% if config.layout == "bundle" %} {{ template.translations.bundleSectionTitle | replace: "{{count}}", components.length }} {% endif %} {% if config.layout == "bundle_component" %} {{ bundle.title }} {% endif %}
{% if bundle.data.discountConfig.bundleDiscount %} {{ template.translations.discountLabelText | replace: "{{percent}}", bundle.data.discountConfig.bundleDiscount }} {% endif %}
{% for product in components %} {% assign productIndex = forloop.index0 %}
{% if product.image %}
{{ product.title }} image
{% endif %}
{{ product.title }} {{ product.price }}
{% if forloop.index < products.size %} + {% endif %} {% endfor %} {% if config.layout == "bundle_component" %}
{% if bundle.data.discountConfig.bundleDiscount %} {{ template.translations.bundleDiscount | replace: "{{percent}}", bundle.data.discountConfig.bundleDiscount }} {% endif %}
{% endif %}
{% endif %} {% endif %}
``` # Hooks Source: https://docs.glood.ai/for-developers/bundles/hooks Complete guide to bundle hooks in Glood.AI # Bundle Hooks Bundle hooks let you customize the behavior of Glood.AI bundles at key lifecycle points. There are five hooks available, each called at a specific stage of the bundle's lifecycle. ## Hook Lifecycle Flow ### 1. Configuration Phase * `OnConfigLoad` is called when bundle data is first loaded * Modify or enrich bundle configuration * Set up initial state ### 2. Rendering Phase * `OnBundleRender` transforms bundle data for the Liquid template * Map products with options and variants * Calculate pricing * Resolve translations ### 3. Interaction Phase * `OnVariantChange` handles variant selection changes * Update URL parameters * Trigger UI updates ### 4. Cart Operations Phase * `OnAddToCart` fires before the cart API request * Validate cart operations * Pre-cart UI updates * `OnAddedToCart` fires after successful cart addition * Post-cart confirmations * Analytics tracking ## Available Hooks ### 1. OnConfigLoad **Purpose:** Modify bundle data when it is first loaded, before any rendering occurs. **Parameters:** | Parameter | Type | Description | | - | - | - | | `bundle` | Object | The raw bundle data object containing products, variants, and configuration | | `utils` | Object | Utility functions (see [Available Utilities](#available-utilities)) | **Returns:** The modified (or unmodified) bundle object. **Example:** ```javascript theme={null} OnConfigLoad: function OnConfigLoad(bundle, utils) { // Filter out-of-stock products bundle.products = bundle.products.filter(p => p.availableForSale); return bundle; } ``` **Use Cases:** * Filter products before rendering * Enrich bundle data with additional information * Override default configuration *** ### 2. OnBundleRender **Purpose:** Transform raw bundle data into the format consumed by the Liquid template. This is the primary hook for controlling what gets rendered. **Parameters:** | Parameter | Type | Description | | - | - | - | | `bundle` | Object | Bundle data with `products`, `variants`, `template`, and `data` properties | | `utils` | Object | Utility functions (see [Available Utilities](#available-utilities)) | | `states` | Object | Current UI state including `selectedProductOptions` array | **Returns:** An object with `products` (array) and `translations` (object). **Example:** ```javascript theme={null} OnBundleRender: function OnBundleRender(bundle, utils, states) { const totalPrice = utils.currencyFormatter( bundle.products.reduce((acc, product) => { return acc + parseFloat( utils.getComponentPrice(product.id, states.selectedProductOptions, bundle) ); }, 0) ); const translations = utils.getTranslations({ data: bundle, productsCount: utils.getTotalProductsInbundles(bundle), totalPrice, }); const products = (bundle?.products ?? []).map((product) => ({ title: product.title, options: [{ name: 'Type', value: utils.getProductOptions(product.id, bundle) .map((option) => option.value) .join(', '), }], variants: utils.getProductOptions(product.id, bundle), image: product?.featuredImage?.url, handle: product.handle, id: product.id, })); return { products, translations }; } ``` **Use Cases:** * Custom product mapping and data transformation * Price calculation logic * Custom translation resolution * Adding computed fields to products *** ### 3. OnVariantChange **Purpose:** Handle variant selection changes when a customer picks a different option. **Parameters:** | Parameter | Type | Description | | - | - | - | | `variantId` | Number | The selected variant ID | | `utils` | Object | Utility functions (see [Available Utilities](#available-utilities)) | **Returns:** void **Example:** ```javascript theme={null} OnVariantChange: function OnVariantChange(variantId, utils) { // Update URL with selected variant const url = new URL(window.location); url.searchParams.set('variant', variantId); window.history.replaceState({}, '', url); // Custom tracking console.log('Variant changed to:', variantId); } ``` **Use Cases:** * Update URL query parameters * Trigger custom analytics events * Update external UI elements * Sync variant selection with other page components *** ### 4. OnAddToCart **Purpose:** Called immediately when the add-to-cart button is clicked, before the cart API request is made. **Parameters:** | Parameter | Type | Description | | - | - | - | | `variantId` | Number | The variant ID being added to cart | | `utils` | Object | Utility functions (see [Available Utilities](#available-utilities)) | **Returns:** void **Example:** ```javascript theme={null} OnAddToCart: function OnAddToCart(variantId, utils) { // Show loading state document.querySelector('.custom-loader').classList.add('active'); // Fire analytics event window.dataLayer?.push({ event: 'bundle_add_to_cart', variantId: variantId }); } ``` **Use Cases:** * Pre-cart validation * Loading state UI updates * Analytics event firing * Custom cart payload modifications *** ### 5. OnAddedToCart **Purpose:** Called after a successful add-to-cart API response. **Parameters:** | Parameter | Type | Description | | - | - | - | | `variantId` | Number | The variant ID that was added to cart | | `utils` | Object | Utility functions (see [Available Utilities](#available-utilities)) | **Returns:** void **Example:** ```javascript theme={null} OnAddedToCart: function OnAddedToCart(variantId, utils) { // Show success notification alert('Bundle added to cart!'); // Open mini-cart document.querySelector('cart-drawer')?.classList.add('active'); } ``` **Use Cases:** * Show success notifications * Open mini-cart or cart drawer * Redirect to cart page * Fire conversion tracking events * Update cart count in header *** ## Available Utilities The `utils` object passed to each hook provides these functions: | Function | Description | | - | - | | `currencyFormatter(amount)` | Formats a numeric amount using the store's currency settings | | `getComponentPrice(productId, selectedOptions, bundle)` | Returns the price of a specific component based on the currently selected options | | `getProductOptions(productId, bundle)` | Returns available options/variants for a product within the bundle | | `getVariantIdFromComponents(variants, selectedComponents)` | Resolves the variant ID from the current component selections | | `getTranslations(options)` | Returns resolved translation strings with interpolated values | | `getTotalProductsInbundles(bundle)` | Returns the total number of products in the bundle | ## Support If you need help with creating or customizing bundle hooks, contact our support team at [support@glood.ai](mailto:support@glood.ai) # Introduction Source: https://docs.glood.ai/for-developers/bundles/introduction Learn about bundle templates in Glood.AI # Bundle Templates Bundle templates in Glood.AI control how product bundles are displayed in your Shopify store. Similar to [section templates](/for-developers/section-template/introduction), they use Liquid templating with JavaScript hooks and CSS, rendered via Preact and LiquidJS. ## What are Bundle Templates? Bundle templates are modular components that determine how your product bundles appear to customers. They are: 1. **Liquid-Powered**: Use Liquid templating for dynamic content rendering, consistent with Shopify's template language. 2. **JavaScript-Enhanced**: Templates include JS hooks that run at key lifecycle points β€” configuration load, render, variant change, and cart operations. 3. **Preact-Rendered**: The bundle storefront uses Preact for efficient UI rendering and state management. 4. **Multi-Component Structure**: Each template consists of: * Liquid template for markup * JavaScript hooks for interactivity * CSS (with Liquid variables) for styling * Settings JSON for configuration * Translation strings for internationalization ## Layout Types Bundle templates support two layout types: | Layout | Value | Description | | - | - | - | | **Bundle** | `bundle` | Full bundle display on the product page, showing all bundled products together | | **Bundle Component** | `bundle_component` | Component selector view, allowing customers to customize bundle selections | The template conditionally renders different markup and applies different settings based on the active layout: ```liquid theme={null} {% if config.layout == 'bundle_component' %} {% assign setting = template.settings.bundleComponent %} {% else %} {% assign setting = template.settings.bundle %} {% endif %} ``` ## Template Components Overview ### Liquid Template The main markup defining bundle structure β€” product cards, images, titles, prices, variant selectors, and add-to-cart elements. See [Default Template](/for-developers/bundles/default-template). ### JavaScript Hooks Five lifecycle hooks for customizing bundle behavior: * `OnConfigLoad` β€” modify bundle data at load time * `OnBundleRender` β€” transform product data before rendering * `OnVariantChange` β€” respond to variant selections * `OnAddToCart` β€” intercept add-to-cart actions * `OnAddedToCart` β€” handle post-cart operations See [Hooks](/for-developers/bundles/hooks) for full documentation. ### CSS Template Liquid-powered CSS that uses template settings for dynamic theming β€” colors, fonts, sizes, and spacing are all configurable. See [Default CSS](/for-developers/bundles/default-css). ### Settings JSON configuration controlling display mode, product card styling, pricing, colors, spacing, and mobile behavior. See [Settings](/for-developers/bundles/settings). ### Translations Localized text strings for all user-facing bundle UI elements. See [Translations](/for-developers/bundles/translations). ## Extension Points Customize bundle behavior through JavaScript hooks: ```javascript theme={null} return { OnBundleRender: function(bundle, utils, states) { // Transform product data before rendering }, OnVariantChange: function(variantId, utils) { // Handle variant selection changes } }; ``` ## Libraries The bundle template system uses the following core libraries: * **Preact** (`^10.22.1`) β€” Lightweight UI library for rendering bundle components * **LiquidJS** (`^10.19.0`) β€” Template engine for rendering Liquid markup on the client side ## Next Steps * View the [Default Template](/for-developers/bundles/default-template) markup * Explore [Hooks](/for-developers/bundles/hooks) for lifecycle customization * Check [Settings](/for-developers/bundles/settings) for configuration options * Review [Translations](/for-developers/bundles/translations) for localization ## Support If you need help with creating or customizing bundle templates, contact our support team at [support@glood.ai](mailto:support@glood.ai) # Settings Source: https://docs.glood.ai/for-developers/bundles/settings Default bundle settings configuration reference # Default Bundle Settings The settings JSON controls all configurable aspects of the bundle template β€” display mode, product card styling, pricing behavior, colors, spacing, and mobile layout. Settings are split into two layout-specific sections (`bundle` and `bundleComponent`) plus shared global settings. ```json theme={null} { "displayMode": "frequently-bought-together", "maxBundleSize": 3, "showSavings": true, "showTotalPrice": true, "allowCustomization": true, "bundleLayout": "horizontal", "bundle": { "backgroundColor": "#F9F9FA", "productCard": { "image": { "width": 110, "height": 133, "objectFit": "cover", "aspectRatio": "3:4" }, "title": { "size": "16px", "weight": 500, "font": "Futura", "color": "#000000", "multipleLines": true }, "price": { "weight": 500, "size": "14px", "color": "#666666", "font": "Futura" } }, "atcBtn": { "backgroundColor": "#000000", "text": { "color": "#FFFFFF", "size": "12px", "weight": 500, "font": "Futura" } } }, "bundleComponent": { "backgroundColor": "#F9F9FA", "productCard": { "image": { "width": 110, "height": 133, "objectFit": "cover", "aspectRatio": "3:4" }, "title": { "size": "16px", "weight": 500, "font": "Futura", "color": "#000000", "multipleLines": true }, "price": { "weight": 500, "size": "14px", "color": "#666666", "font": "Futura" } }, "atcBtn": { "backgroundColor": "#000000", "text": { "color": "#FFFFFF", "size": "12px", "weight": 500, "font": "Futura" } } }, "showProductOptions": true, "pricing": { "showIndividualPrices": true, "showBundlePrice": true, "showSavingsAmount": true, "showSavingsPercentage": true, "priceCalculation": "sum", "discountType": "percentage", "discountValue": 10 }, "appearance": { "layout": "card", "showPlusIcons": true, "showEqualIcon": true, "highlightSavings": true, "stickyAddToCart": false }, "colors": { "background": "#f8f8f8", "cardBackground": "#ffffff", "text": "#333333", "price": "#000000", "originalPrice": "#999999", "savingsText": "#00a650", "savingsBackground": "#e6f4ea", "button": "#000000", "buttonText": "#ffffff", "plusIcon": "#666666", "border": "#e0e0e0" }, "spacing": { "containerPadding": "30px", "itemGap": "20px", "sectionMargin": "50px", "cardPadding": "15px" }, "behavior": { "autoSelectAll": true, "updatePriceOnSelection": true, "showOutOfStock": false, "replaceOutOfStock": true, "minimumItems": 2, "trackingEnabled": true }, "mobile": { "layout": "vertical", "showImages": true, "compactMode": true } } ``` ## Settings Reference ### Global Settings | Setting | Type | Default | Description | | - | - | - | - | | `displayMode` | String | `"frequently-bought-together"` | Bundle display mode | | `maxBundleSize` | Number | `3` | Maximum products in a bundle | | `showSavings` | Boolean | `true` | Show savings amount to customer | | `showTotalPrice` | Boolean | `true` | Display total bundle price | | `allowCustomization` | Boolean | `true` | Allow customers to modify bundle | | `bundleLayout` | String | `"horizontal"` | Layout direction (`horizontal` / `vertical`) | | `showProductOptions` | Boolean | `true` | Show product option selectors | ### Layout-Specific Settings (`bundle` / `bundleComponent`) Both layouts share the same structure with independent values: #### Product Card β€” Image | Setting | Type | Default | Description | | - | - | - | - | | `width` | Number | `110` | Image width in pixels | | `height` | Number | `133` | Image height in pixels | | `objectFit` | String | `"cover"` | CSS object-fit value | | `aspectRatio` | String | `"3:4"` | Image aspect ratio | #### Product Card β€” Title | Setting | Type | Default | Description | | - | - | - | - | | `size` | String | `"16px"` | Font size | | `weight` | Number | `500` | Font weight | | `font` | String | `"Futura"` | Font family | | `color` | String | `"#000000"` | Text color | | `multipleLines` | Boolean | `true` | Allow title to wrap to multiple lines | #### Product Card β€” Price | Setting | Type | Default | Description | | - | - | - | - | | `weight` | Number | `500` | Font weight | | `size` | String | `"14px"` | Font size | | `color` | String | `"#666666"` | Price text color | | `font` | String | `"Futura"` | Font family | #### Add to Cart Button | Setting | Type | Default | Description | | - | - | - | - | | `backgroundColor` | String | `"#000000"` | Button background color | | `text.color` | String | `"#FFFFFF"` | Button text color | | `text.size` | String | `"12px"` | Button text size | | `text.weight` | Number | `500` | Button text weight | | `text.font` | String | `"Futura"` | Button text font | ### Pricing | Setting | Type | Default | Description | | - | - | - | - | | `showIndividualPrices` | Boolean | `true` | Show price per product | | `showBundlePrice` | Boolean | `true` | Show combined bundle price | | `showSavingsAmount` | Boolean | `true` | Show savings in currency | | `showSavingsPercentage` | Boolean | `true` | Show savings as percentage | | `priceCalculation` | String | `"sum"` | How to calculate bundle price | | `discountType` | String | `"percentage"` | Discount type (`percentage` / `fixed`) | | `discountValue` | Number | `10` | Discount value | ### Appearance | Setting | Type | Default | Description | | - | - | - | - | | `layout` | String | `"card"` | Product card layout style | | `showPlusIcons` | Boolean | `true` | Show "+" icons between products | | `showEqualIcon` | Boolean | `true` | Show "=" icon before total | | `highlightSavings` | Boolean | `true` | Visually highlight savings | | `stickyAddToCart` | Boolean | `false` | Make ATC button sticky on scroll | ### Behavior | Setting | Type | Default | Description | | - | - | - | - | | `autoSelectAll` | Boolean | `true` | Auto-select all products on load | | `updatePriceOnSelection` | Boolean | `true` | Recalculate price on selection change | | `showOutOfStock` | Boolean | `false` | Show out-of-stock products | | `replaceOutOfStock` | Boolean | `true` | Replace OOS products with alternatives | | `minimumItems` | Number | `2` | Minimum items required for bundle | | `trackingEnabled` | Boolean | `true` | Enable analytics tracking | ### Mobile | Setting | Type | Default | Description | | - | - | - | - | | `layout` | String | `"vertical"` | Mobile layout direction | | `showImages` | Boolean | `true` | Show product images on mobile | | `compactMode` | Boolean | `true` | Use compact mobile layout | # Translations Source: https://docs.glood.ai/for-developers/bundles/translations Default bundle translations reference # Default Bundle Translations The translations object defines all user-facing text strings for bundle sections. Translations are organized by locale, with `en` (English) as the primary locale. ```json theme={null} { "en": { "heading_text": "Frequently Bought Together", "subheading_text": "Customers who bought this item also bought", "bundle_price_text": "Bundle Price", "total_price_text": "Total Price", "you_save_text": "You Save", "add_bundle_to_cart": "Add Bundle to Cart", "adding_bundle_text": "Adding Bundle...", "added_bundle_text": "Bundle Added!", "select_all_text": "Select All", "deselect_all_text": "Deselect All", "this_item_text": "This Item", "plus_text": "+", "equals_text": "=", "bundle_discount_text": "Bundle Discount", "original_price_text": "Original Price", "remove_item_text": "Remove", "out_of_stock_text": "Out of Stock", "quantity_text": "Qty", "variant_text": "Variant", "customize_bundle_text": "Customize Your Bundle", "minimum_items_text": "Select at least {count} items", "maximum_items_text": "Maximum {count} items allowed", "productComponentTitle": "Bundle with {{count}} products", "bundleSectionTitle": "Bundle {{count}} items together", "discountLabelText": "{{percent}}% off", "bundleDiscount": "Save {{percent}}%" } } ``` ## Translation Keys ### Headings & Labels | Key | Default Value | Description | | - | - | - | | `heading_text` | "Frequently Bought Together" | Main bundle section heading | | `subheading_text` | "Customers who bought this item also bought" | Section subheading | | `this_item_text` | "This Item" | Label for the current product | | `productComponentTitle` | "Bundle with \{\{count}} products" | Component selector title | | `bundleSectionTitle` | "Bundle \{\{count}} items together" | Bundle layout title | ### Pricing | Key | Default Value | Description | | - | - | - | | `bundle_price_text` | "Bundle Price" | Bundle price label | | `total_price_text` | "Total Price" | Total price label | | `original_price_text` | "Original Price" | Original price label | | `you_save_text` | "You Save" | Savings label | | `bundle_discount_text` | "Bundle Discount" | Discount label | | `discountLabelText` | "\{\{percent}}% off" | Discount badge text | | `bundleDiscount` | "Save \{\{percent}}%" | Savings percentage text | ### Cart Actions | Key | Default Value | Description | | - | - | - | | `add_bundle_to_cart` | "Add Bundle to Cart" | ATC button text | | `adding_bundle_text` | "Adding Bundle..." | Loading state text | | `added_bundle_text` | "Bundle Added!" | Success state text | ### Selection | Key | Default Value | Description | | - | - | - | | `select_all_text` | "Select All" | Select all products | | `deselect_all_text` | "Deselect All" | Deselect all products | | `remove_item_text` | "Remove" | Remove item from bundle | | `customize_bundle_text` | "Customize Your Bundle" | Customization prompt | ### Product Details | Key | Default Value | Description | | - | - | - | | `out_of_stock_text` | "Out of Stock" | OOS status text | | `quantity_text` | "Qty" | Quantity label | | `variant_text` | "Variant" | Variant selector label | | `minimum_items_text` | "Select at least \{count} items" | Minimum items warning | | `maximum_items_text` | "Maximum \{count} items allowed" | Maximum items warning | ### Symbols | Key | Default Value | Description | | - | - | - | | `plus_text` | "+" | Plus icon between products | | `equals_text` | "=" | Equals icon before total | ## Dynamic Placeholders Some translation strings use placeholders that are replaced at render time: * `{{count}}` β€” replaced with the number of products or components * `{{percent}}` β€” replaced with the discount percentage * `{count}` β€” replaced with min/max item counts * `{{total_price}}` β€” replaced with the formatted total price ## Adding Custom Translations To add translations for additional locales, add a new key to the translations object: ```json theme={null} { "en": { ... }, "fr": { "heading_text": "FrΓ©quemment achetΓ©s ensemble", "add_bundle_to_cart": "Ajouter le lot au panier", ... } } ``` # Default Template CSS Source: https://docs.glood.ai/for-developers/default-code/css-liquid Default Template CSS code reference The main Template CSS file for styling recommendation sections. ```liquid theme={null} {% comment %} for grid layout {% endcomment %} {% assign section_id = section.id %} {% assign settings = template.settings %} {% assign layout_settings = settings[section.layout] %} {% assign product_card_settings = settings.product_card %} [data-gai-section-id="{{ section_id }}"] ._gai-grid { grid-template-columns: repeat({{- settings.breakpoints.small.cards_per_view -}},1fr); gap: {{ settings.breakpoints.small.gutter | default: 10 }}px; } [data-gai-section-id="{{ section_id }}"] ._gai-prod-prc { color: {{ product_card_settings.price_color }}; font-size: {{ settings.breakpoints.small.price_font_size }}px; } [data-gai-section-id="{{ section_id }}"] ._gai-sec-tit { display: -webkit-box; -webkit-box-orient: vertical; overflow: hidden; -webkit-line-clamp: {{ settings.breakpoints.small.max_section_title_rows }}; font-size: {{ settings.breakpoints.small.widget_title_font_size }}px; text-align: {{ settings.breakpoints.small.widget_title_alignment }}; } [data-gai-section-id="{{ section_id }}"] ._gai-prod-vndr { font-size: {{ settings.breakpoints.small.product_vendor_font_size }}px; } [data-gai-section-id="{{ section_id }}"] ._gai-prod-tit { color: {{ product_card_settings.title_color }}; display: -webkit-box; -webkit-box-orient: vertical; font-weight: bold; overflow: hidden; font-family: {{ product_card_settings.product_title_font_family }}; -webkit-line-clamp: {{ settings.breakpoints.small.max_product_title_rows }}; text-align: {{ settings.breakpoints.small.product_title_alignment }}; font-size: {{ settings.breakpoints.small.product_title_font_size }}px; } [data-gai-section-id="{{ section_id }}"] ._gai-prod-prc--compare-at { color: {{ product_card_settings.price_color_compare }}; {% if settings.breakpoints.small.compare_price_visible or section.layout == "amazon_bought_together" %} display: block; {% else %} display: none; {% endif %} } [data-gai-section-id="{{ section_id }}"] ._gai-dis-txt { color: {{ product_card_settings.discount_color }}; font-size: {{ settings.breakpoints.small.section_subtitle_font_size }}px; } [data-gai-section-id="{{ section_id }}"] ._gai-prod-vndr--above-title { {% if product_card_settings.vendor_position == 'above' %} display: block; {% else %} display: none; {% endif %} } [data-gai-section-id="{{ section_id }}"] ._gai-prod-vndr--below-title { {% if product_card_settings.vendor_position == 'below' %} display: block; {% else %} display: none; {% endif %} } {% assign aspect_ratio_parts = product_card_settings.image_aspect_ratio | split: ':' %} [data-gai-section-id="{{ section_id }}"] ._gai-prod-img { aspect-ratio: {{ aspect_ratio_parts[0] }}/{{ aspect_ratio_parts[1] }}; object-fit: {{ product_card_settings.image_object_fit }}; } [data-gai-section-id="{{ section_id }}"] _gai-prod-img-wrap { aspect-ratio: {{ aspect_ratio_parts[0] }}/{{ aspect_ratio_parts[1] }}; } [data-gai-section-id="{{ section_id }}"] ._gai-dis-cnt { {% if section.layout == 'amazon_bought_together' %} justify-content: start; {% else %} justify-content: {{ settings.breakpoints.small.justify_widget_subtitle }}; {% endif %} background-color: {{ product_card_settings.discount_background }}; {% if product_card_settings.discount_visible == true %} display: flex; {% else %} display: none; {% endif %} } [data-gai-section-id="{{ section_id }}"] ._gai-atc-btn { background-color: {{ product_card_settings.add_to_cart_background | default: '#797068' }}; color: {{ product_card_settings.add_to_cart_color | default: '#ffffff' }}; border: none; border-radius:{{ product_card_settings.add_to_cart_border_radius | default: 0 }}px; } [data-gai-section-id="{{ section_id }}"] ._gai-atc-btn:disabled { background-color: {{ product_card_settings.disabled_add_to_cart_background | default: '#ada7a1' }}; } [data-gai-section-id="{{ section_id }}"]{ font-family: {{ settings.font_family }}; } [data-gai-section-id="{{ section_id }}"] ._gai-prod-card { background-color: {{ product_card_settings.background_color | default: 'transparent' }}; {% if product_card_settings.font_family != blank %} font-family: {{ product_card_settings.font_family }}; {% endif %} } ._gai-container[data-gai-section-id="{{ section_id }}"] { {% if settings.section.background_color %} background-color: {{ settings.section.background_color }}; {% endif %} } [data-gai-section-id="{{ section_id }}"] { ._gai-oos { background-color: {{ template.settings.out_of_stock.background_color | default: '#000' }}; color: {{ template.settings.out_of_stock.text_color | default: '#fff' }}; } ._gai-bestseller { background-color: {{ template.settings.labels.bestseller.background_color | default: '#222222' }}; color: {{ template.settings.labels.bestseller.text_color | default: '#fff' }}; } ._gai-new { background-color: {{ template.settings.labels.new.background_color | default: '#333' }}; color: {{ template.settings.labels.new.text_color | default: '#fff' }}; } ._gai-trending{ background-color: {{ template.settings.labels.trending.background_color | default: '#444' }}; color: {{ template.settings.labels.trending.text_color | default: '#fff' }}; } ._gai-bndl-sec { justify-content: {{ template.settings.amazon_bought_together.justify | default: 'start' }}; } } [data-gai-section-id="{{ section_id }}"] ._gai-dis{ background-color: {{ product_card_settings.discount_label_background }}; opacity: 0.85; color: {{ product_card_settings.discount_label_color }}; } @media (min-width: {{ settings.breakpoints.medium.screen_size | default: 768 }}px) { [data-gai-section-id="{{ section_id }}"] ._gai-grid { grid-template-columns: repeat({{- settings.breakpoints.medium.cards_per_view | default: 3 -}},1fr); gap: {{ settings.breakpoints.medium.gutter | default: 20 }}px; } {% assign n = products.length %} [data-gai-section-id="{{ section_id }}"] ._gai-bundle-products { grid-template-columns: repeat({{ n }}, minmax(0, 1fr) 20px); } [data-gai-section-id="{{ section_id }}"] ._gai-dis-cnt { {% if section.layout == 'amazon_bought_together' %} justify-content: center; {% else %} justify-content: {{ settings.breakpoints.medium.justify_widget_subtitle }}; {% endif %} } [data-gai-section-id="{{ section_id }}"] ._gai-prod-prc { font-size: {{ settings.breakpoints.medium.price_font_size }}px; } [data-gai-section-id="{{ section_id }}"] ._gai-sec-tit { -webkit-line-clamp: {{ settings.breakpoints.medium.max_section_title_rows }}; font-size: {{ settings.breakpoints.medium.widget_title_font_size }}px; text-align: {{ settings.breakpoints.medium.widget_title_alignment }}; } [data-gai-section-id="{{ section_id }}"] ._gai-prod-vndr { font-size: {{ settings.breakpoints.medium.product_vendor_font_size }}px; } [data-gai-section-id="{{ section_id }}"] ._gai-prod-tit { -webkit-line-clamp: {{ settings.breakpoints.medium.max_product_title_rows }}; text-align: {{ settings.breakpoints.medium.product_title_alignment }}; font-size: {{ settings.breakpoints.medium.product_title_font_size }}px; } [data-gai-section-id="{{ section_id }}"] ._gai-prod-prc--compare-at { {% if section.layout == "amazon_bought_together" or settings.breakpoints.medium.compare_price_visible == true %} display: block {% else %} display: block; {% endif %} } [data-gai-section-id="{{ section_id }}"] ._gai-dis-txt { color: {{ product_card_settings.discount_color }}; font-size: {{ settings.breakpoints.medium.section_subtitle_font_size }}px; } } @media (min-width: {{ settings.breakpoints.large.screen_size | default: 1024 }}px) { [data-gai-section-id="{{ section_id }}"] ._gai-grid { grid-template-columns: repeat({{- settings.breakpoints.large.cards_per_view -}},1fr); gap: {{ settings.breakpoints.large.gutter | default: 20 }}px; } [data-gai-section-id="{{ section_id }}"] ._gai-prod-prc { font-size: {{ settings.breakpoints.large.price_font_size }}px; } [data-gai-section-id="{{ section_id }}"] ._gai-sec-tit { -webkit-line-clamp: {{ settings.breakpoints.large.max_section_title_rows }}; font-size: {{ settings.breakpoints.large.widget_title_font_size }}px; text-align: {{ settings.breakpoints.large.widget_title_alignment }}; } [data-gai-section-id="{{ section_id }}"] ._gai-prod-vndr { font-size: {{ settings.breakpoints.large.product_vendor_font_size }}px; } [data-gai-section-id="{{ section_id }}"] ._gai-prod-tit { -webkit-line-clamp: {{ settings.breakpoints.large.max_product_title_rows }}; text-align: {{ settings.breakpoints.large.product_title_alignment }}; font-size: {{ settings.breakpoints.large.product_title_font_size }}px; } [data-gai-section-id="{{ section_id }}"] ._gai-prod-prc--compare-at { {% if settings.breakpoints.large.compare_price_visible or section.layout == "amazon_bought_together" %} display: block; {% else %} display: none; {% endif %} } [data-gai-section-id="{{ section_id }}"] ._gai-dis-txt { color: {{ product_card_settings.discount_color }}; font-size: {{ settings.breakpoints.large.section_subtitle_font_size }}px; } [data-gai-section-id="{{ section_id }}"] .gai-dis-cnt { {% if section.layout == 'amazon_bought_together' %} justify-content: center; {% else %} justify-content: {{ settings.breakpoints.small.justify_widget_subtitle }}; {% endif %} } } ._gai-amz-tit { text-align: center; } [data-gai-section-id="{{ section_id }}"] ._gai-prod-price-wrp{ {% if template.settings.product_card.price_compare_at_mode == 'after'%} flex-direction: row-reverse; justify-content: start; {% endif %} } {% assign should_disable = product_card_settings.variant_selector_type == "swatch_with_atc" or product_card_settings.disable_add_to_cart_button %} {% if section.layout != 'amazon_bought_together' and should_disable %} [data-gai-section-id="{{ section_id }}"] { ._gai-atc-btn { display: none !important; } ._gai-skl-atc { display: none !important; } } {% endif %} ``` # Default Template Javascript Source: https://docs.glood.ai/for-developers/default-code/section-js Default Template Javascript code reference This Template Javascript contains the essential JavaScript hooks required for the proper functioning of the V3 storefront. Each hook serves a specific purpose in the recommendation engine's lifecycle. ```js theme={null} // @ts-ignore return { initSwiper: ( Swiper, templateSettings, container, params, defaultSettings, utils ) => { const carouselContainer = container.querySelector('._gai-crz-cnt') if (!carouselContainer) { console.error( 'GLOOD.AI:ERROR: Carousel container not found for section', params.recommendation.section.id ) return } const settings = templateSettings?.carousel?.swiperConfig || {} const swiperConfig = utils.merge(defaultSettings, settings) const breakpoints = Object.values(templateSettings.breakpoints).reduce( (acc, curr) => ({ ...acc, [curr.screenSize]: { slidesPerView: curr.cardsPerView, spaceBetween: curr.gutter, }, }), {} ) const swiper = new Swiper( carouselContainer, utils.merge(swiperConfig, { breakpoints, }) ) return swiper }, onSectionInit: (args, cb, gloodUtils) => { const { recommendation, engine, initEnginePayload } = args cb({ recommendation, engine, initEnginePayload, }) }, onSectionRenderComplete: (args, utils) => {}, onVariantChange: (args, utils) => {}, onSwatchChange: (args, utils) => {}, validateCartOperation: async (payload, recommendation, utils, gloodUtils) => { return { payload, error: null, href: false, } }, onCartOperationComplete: (args, utils, gloodUtils) => {}, onProductDataReceived: (args, utils) => {}, getProductDetailsQuery: (recommendation, glood) => { // use graphql variables to pass the country and language return ` featuredImage{ url } handle id title availableForSale priceRange { minVariantPrice { amount currencyCode } } compareAtPriceRange { minVariantPrice { amount currencyCode } } options(first: 10){ name optionValues{ name swatch{ color image{ previewImage{ url } } } } } variants(first:250){ nodes{ compareAtPrice{ amount currencyCode } id image{ url } price{ amount currencyCode } currentlyNotInStock title quantityAvailable availableForSale selectedOptions{ name value } } pageInfo{ endCursor } } images(first: 2){ nodes{ url } } vendor variantsCount{ count } tags availableForSale ` }, transformProductData: (product) => { return { featuredImage: product.featuredImage.url ? { src: product.featuredImage.url, } : null, handle: product.handle, id: parseInt(product.id.replace('gid://shopify/Product/', '')), title: product.title, vendor: product.vendor, images: product.images.nodes.map((image) => ({ src: image.url, })), variants: product.variants.nodes.map((variant) => ({ id: parseInt(variant.id.replace('gid://shopify/ProductVariant/', '')), compareAtPrice: variant.compareAtPrice?.amount || null, price: variant.price.amount, image: variant.image?.url ? { src: variant.image.url, } : null, currentlyNotInStock: variant.currentlyNotInStock, title: variant.title, quantityAvailable: variant.quantityAvailable, availableForSale: variant.availableForSale, selectedOptions: variant.selectedOptions, })), available: product.availableForSale, compareAtPrice: product.compareAtPriceRange.minVariantPrice.amount, price: product.priceRange.minVariantPrice.amount, variantsCount: product.variantsCount.count, tags: product.tags, availableForSale: product.availableForSale, options: product.options.map((option) => ({ name: option.name, optionValues: option.optionValues.map( (optionValue) => optionValue.name ), swatches: option.optionValues.map( (optionValue) => optionValue.swatch ) })), } }, onAmazonProductSelect: (args)=>{ } } ``` # Default Template liquid Source: https://docs.glood.ai/for-developers/default-code/section-liquid Default Template liquid code reference The main Template file for rendering recommendation sections. ```liquid theme={null} {%- assign translations = template.translations %} {%- assign translations_discount_label_text = 'discount_label_text' | t: translations, '' -%} {% assign root_url = glood.shopify.root_url %} {% assign section_discount_str = section.discount_config.value | section_discount: section.discount_config.type, section.discount_config.widget_message, glood.localization.language.locale, glood.shop.money_format %} {% assign section_title = section.translations[glood.localization.language.locale].title | default: section.title %} {% capture quantity_selector %} {% if template.settings.product_card.show_quantity_selector %}
{% endif %} {% endcapture %} {% capture spinner_loader %} {% endcapture %}
{% if section.layout != 'amazon_bought_together' %}

{{ section_title }}

{% if section_discount_str.length > 0 %}
{{ section_discount_str }}
{% endif %}
{% endif %} {% if section.layout != 'amazon_bought_together' %}
{% for product in products %} {% assign product_url = root_url | product_url: product.handle, glood.product.id, section.layout %} {% assign first_available_variant = -1 %} {% assign available_variants_count = 0 %} {% for variant in product.variants %} {% if variant.available_for_sale %} {% if available_variants_count == 0 %} {% assign first_available_variant = variant %} {% endif %} {% assign available_variants_count = available_variants_count | plus: 1 %} {% endif %} {% endfor %} {% if first_available_variant == -1 %} {% assign first_available_variant = product.variants[0] %} {% endif %} {% assign multiple_variants = available_variants_count > 1 %} {% capture swatch_component %} {% assign should_enable_swatch = template.settings.product_card.variant_selector_type == 'swatch' or template.settings.product_card.variant_selector_type == 'swatch_with_atc' %} {% if should_enable_swatch and product.variants.size > 1 %} {% assign options = product.options %}
{% for swatch in template.settings.swatches %} {% assign allowed_names = swatch.option_names %} {% assign found_option = false %} {% for option in options %} {% assign found = false %} {% for name in allowed_names %} {% if name == option.name %} {% assign found_option = option %} {% assign found = true %} {% break %} {% endif %} {% endfor %} {% if found %} {% break %} {% endif %} {% endfor %} {% if found_option != false %} {% assign translation_key = "swatch_label_" | append: found_option.name %}
{% assign selected_option = first_available_variant.selected_options | find: 'name', found_option.name %}
{% for value in found_option.option_values %} {% assign swatch_img_url = found_option.swatches[forloop.index0].image.preview_image.url %} {% assign swatch_color = found_option.swatches[forloop.index0].color %} {% if swatch_color == blank %} {% assign swatch_color = value | color_value: template.settings.color_mapping %} {% endif %} {% if swatch.type == "size" %}{{ value }}{% endif %} {% endfor %}
{% endif %} {% endfor %}
{% endif %} {% endcapture %} {% capture variant_selector %} {% assign size = available_variants_count %} {% if size > 1 %} {% endif %} {% endcapture %}
{% if available_variants_count == 0 %} {{ translations.oos_text | default: 'Out Of Stock' }} {% endif %} {% assign labels_cnt = 0 %} {% for label in template.settings.labels %} {% if labels_cnt < template.settings.max_labels_count and product.tags contains label.name %} {{- translations[label.name] | default: label.name -}} {% assign labels_cnt = labels_cnt | plus: 1 %} {% endif %} {% endfor %} {% assign product_discount = product | product_discount: section.discount_config, translations.discount_label_text, glood.shop.money_format %} {% if product_discount.length > 0 and template.settings.product_card.show_discount_pill %} {{ product_discount }} {% endif %}
{{ product.title }} {% if product.images[1].src %} {{ product.title }} {% endif %}
{{ translations.added_to_cart_text | default: 'Added to cart' }}
{{ translations.atc_error_text | default: 'Error while add to cart' }}
{% if template.settings.product_card.add_to_cart_mode == 'image_hover' %}
{% if template.settings.product_card.variant_selector_type == 'integrated' %} {{ variant_selector }} {% endif %}
{% endif %}
{% if template.settings.product_card.vendor_position == 'above' %}
{{ product.vendor }}
{% endif %} {{ product.title }}
{% if template.settings.product_card.vendor_position == 'below' %}
{{ product.vendor }}
{% endif %}
{% assign compare_at_price = first_available_variant.compare_at_price | times: 1.0 %} {% if template.settings.product_card.price_compare_at_mode != 'none' and compare_at_price > 0 %} {{ first_available_variant.compare_at_price | format_money: glood.shop.money_format }} {% endif %} {{ first_available_variant.price | format_money: glood.shop.money_format }}
{% assign save_text = product | save_amount: section.discount_config, translations.discount_save_text, glood.shop.money_format %} {% if save_text.length > 0 %}
{{ save_text }}
{% endif %}
{{ swatch_component }} {{ quantity_selector }} {% if template.settings.product_card.variant_selector_type == 'selector' %} {{ variant_selector }} {% endif %} {% if template.settings.product_card.add_to_cart_mode != 'image_hover' %}
{% if template.settings.product_card.variant_selector_type == 'integrated' %} {{ variant_selector }} {% endif %}
{% endif %}
{% endfor %}
{% if section.layout == 'carousel'%}
_
{% if template.settings.carousel.show_pagination %}
{% endif %} {% endif %}
{% else %}

{{ section.title }}

{% if section_discount_str.length > 0 %}
{{ section_discount_str }}
{% endif %}
{% for product in products %} {% assign first_available_variant = -1 %} {% assign available_variants_count = 0 %} {% for variant in product.variants %} {% if variant.available_for_sale %} {% if available_variants_count == 0 %} {% assign first_available_variant = variant %} {% endif %} {% assign available_variants_count = available_variants_count | plus: 1 %} {% endif %} {% endfor %} {% if first_available_variant == -1 %} {% assign first_available_variant = product.variants[0] %} {% endif %} {% assign multiple_variants = available_variants_count > 1 %} {% assign product_url = root_url | product_url: product.handle, glood.product.id, section.layout %}
{% if available_variants_count == 0 %} {{ translations.oos_text | default: 'Out Of Stock' }} {% endif %} {% assign labels_cnt = 0 %} {% for label in template.settings.labels %} {% if labels_cnt < template.settings.max_labels_count and product.tags contains label.name %} {{- translations[label.name] | default: label.name -}} {% assign labels_cnt = labels_cnt | plus: 1 %} {% endif %} {% endfor %} {% assign product_discount = product | product_discount: section.discount_config, translations.discount_label_text, glood.shop.money_format %}
βœ”οΈ {% if product.images[1].src %} {{ product.title }} {% endif %}
{% if template.settings.product_card.vendor_position == 'above' %}
{{ product.vendor }}
{% endif %} {{ product.title }}
{% if template.settings.product_card.vendor_position == 'below' %}
{{ product.vendor }}
{% endif %} {% assign save_text = product | save_amount: section.discount_config, translations.fbt_save_text, glood.shop.money_format %} {% if save_text.length > 0 %}
{{ save_text }}
{% endif %}
{% assign compare_at_price = first_available_variant.compare_at_price | times: 1.0 %} {% if template.settings.product_card.price_compare_at_mode != 'none' and compare_at_price > 0 %} {{ first_available_variant.compare_at_price | format_money: glood.shop.money_format }} {% endif %} {{ first_available_variant.price | format_money: glood.shop.money_format }}
{% assign options = product.options %} {% assign should_enable_swatch = template.settings.product_card.variant_selector_type == 'swatch' or template.settings.product_card.variant_selector_type == 'swatch_with_atc' %} {% if should_enable_swatch and product.variants.size > 1 %} {% assign options = product.options %}
{% for swatch in template.settings.swatches %} {% assign allowed_names = swatch.option_names %} {% assign found_option = false %} {% for option in options %} {% assign found = false %} {% for name in allowed_names %} {% if name == option.name %} {% assign found_option = option %} {% assign found = true %} {% break %} {% endif %} {% endfor %} {% if found %} {% break %} {% endif %} {% endfor %} {% if found_option != false %} {% assign translation_key = 'swatch_label_' | append: found_option.name %}
{% assign selected_option = first_available_variant.selected_options | find: 'name', found_option.name %}
{% for value in found_option.option_values %} {% assign swatch_img_url = found_option.swatches[forloop.index0].image.preview_image.url %} {% assign swatch_color = found_option.swatches[forloop.index0].color %} {% if swatch_color == blank %} {% assign swatch_color = value | color_value: template.settings.color_mapping %} {% endif %} {% if swatch.type == "size" %}{{ value }}{% endif %} {% endfor %}
{% endif %} {% endfor %}
{% elsif available_variants_count > 1 %} {% endif %}
{% if forloop.index != products.length %} {% endif %} {% endfor %}

{{ section.title }}

{% if section_discount_str.length > 0 %}
{{ section_discount_str }}
{% endif %}
{% if translations.total_price_text.length > 0 %}
{{ translations.total_price_text }}
{% endif %}
{% endif %}
``` # Default Template Settings Source: https://docs.glood.ai/for-developers/default-code/settings-json Default Template Settings configuration reference The main Settings configuration file for recommendation sections. ```json theme={null} { "breakpoints": { "small": { "gutter": 10, "cardsPerView": 2, "widgetTitleAlignment": "left", "productTitleAlignment": "left", "comparePriceVisible": false, "imageWidth": 600, "imageHeight": 600, "justifyWidgetSubtitle": "left" }, "medium": { "gutter": 20, "cardsPerView": 3, "widgetTitleAlignment": "center", "productTitleAlign": "center", "comparePriceVisible": true, "imageWidth": 600, "imageHeight": 600, "justifyWidgetSubtitle": "center" }, "large": { "gutter": 20, "cardsPerView": 4, "widgetTitleAlignment": "center", "productTitleAlign": "center", "comparePriceVisible": true, "imageWidth": 600, "imageHeight": 600, "justifyWidgetSubtitle": "center" } }, "labels": [ { "name": "new", "textColor": "#ffffff", "backgroundColor": "#333333" }, { "name": "trending", "textColor": "#ffffff", "backgroundColor": "#444444" }, { "name": "bestseller", "textColor": "#ffffff", "backgroundColor": "#222222" } ], "maxLabelsCount": 2, "outOfStock": { "textColor": "#ffffff", "backgroundColor": "#000" }, "carousel": { "library": "swiper", "showPagination": true }, "productCard": { "color": "#222", "priceColor": "#222", "titleColor": "#222", "discountColor": "#000", "vendorPosition": "hidden", "addToCartMode": "card_hover", "backgroundColor": "transparent", "discountVisible": true, "imageHoverMode": "secondary", "imageObjectFit": "contain", "addToCartColor": "#fff", "imageAspectRatio": "1:1", "showDiscountPill": true, "discountBackground": "transparent", "priceColorCompare": "#aaa", "discountLabelColor": "#ffffff", "priceColorOriginal": "#5C5C5C", "priceCompareAtMode": "before", "addToCartBackground": "#000", "showQuantitySelector": false, "discountLabelVisible": true, "discountLabelPosition": "center", "discountLabelBackground": "#ff0000", "redirectAfterAddToCart": true, "variantSelectorType": "integrated", "comparePriceVisibilityMobile": "before", "disabledAddToCartBackground": "#00000070", "disableAddToCartButton": false }, "colorMapping": {}, "horizontalGrid": {}, "amazonBoughtTogether": { "priceCompareAtMode": "before", "buttonBackgroundColor": "#000" }, "swatches": [ { "type": "color", "key": "color", "optionNames": [ "Color", "Colour", "color", "colour" ] }, { "type": "size", "key": "size", "optionNames": [ "Size", "sizes" ] } ] } ``` # Default Translations Source: https://docs.glood.ai/for-developers/default-code/translations Default translations object reference # Default Translations The main translations object for recommendation sections. ```json theme={null} { "primary_locale": { "oos_text": "Out of stock", "bestseller_text": "Bestseller", "new_text": "New", "trending_text": "Trending", "discount_text": "Get Flat Discount of {percentage}", "discount_label_text": "Save {amount}", "added_to_cart_text": "Added to cart", "atc_text": "Add to cart", "atc_error_text": "Error adding to cart", "discount_save_text": "Save {amount}", "fbt_add_to_cart_text": "Add to cart", "fbt_added_to_cart_text": "Added to cart", "fbt_save_text": "Save {percent}", "total_price_text": "Total Price" } } ``` This translations object contains all the default text strings used throughout the recommendation sections. The strings can include placeholders (like `{amount}` or `{percentage}`) which will be replaced with actual values when rendered. # App Modules Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/api-reference/app-modules Complete reference for the recommendations() and search() app modules # App Modules App modules provide modular functionality for Glood features. Each module is registered with the Glood client via `.use()`. ## Overview The SDK ships two app modules: * **`recommendations()`** - Product recommendations and personalization (v3) * **`search()`** - AI search & discovery (v1) The module follows this architecture: * **Main Endpoint** - API endpoint for app features and functionality * **Pixel Endpoint** - Separate endpoint for analytics tracking * **Event Subscriptions** - Shopify Analytics events the app listens to * **Consent Requirements** - Privacy consent types required for pixel tracking ## recommendations() Enables product recommendations and personalization features. ### Signature ```typescript theme={null} function recommendations(): GloodAppModule ``` ### Default Configuration ```typescript theme={null} { endpoint: 'https://storefront.glood.ai', pixel: { enabled: true, endpoint: 'https://storefront.glood.ai', consent: ['analytics', 'marketing'], }, } ``` ### Basic Usage ```typescript theme={null} import { createGlood, recommendations } from '@glood/hydrogen'; const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', }).use(recommendations()); // Use default configuration ``` ### Custom Configuration Endpoints and pixel settings are customized at the client level via the `apps.recommendations` config block: ```typescript theme={null} import { createGlood, recommendations, CONSENT_TYPES } from '@glood/hydrogen'; const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', apps: { recommendations: { endpoint: 'https://custom-recommendations.glood.ai', pixel: { enabled: true, endpoint: 'https://custom-recommendations.glood.ai', consent: [CONSENT_TYPES.ANALYTICS], // Only analytics consent }, subscribedEvents: ['product_viewed', 'cart_viewed'], // Limited events }, }, }).use(recommendations()); ``` ### Tracked Events The recommendations app subscribes to these Shopify Analytics events by default: | Event | Description | Pixel Data Sent | | - | - | - | | `page_viewed` | Any page navigation | Page URL, title, referrer | | `product_viewed` | Product page views | Product details, variant info, pricing | | `collection_viewed` | Collection page views | Collection details, product count | | `cart_viewed` | Shopping cart views | Cart contents, total value, line items | | `product_added_to_cart` | Items added to cart | Product details, quantity, price | | `product_removed_from_cart` | Items removed from cart | Product details, previous quantity | | `search_submitted` | Search queries | Search term, results count, product matches | | `custom_promotion_viewed` | Promotional content | Promotion details, context | ## RecommendationsApp Methods Get the app instance from the client and call its methods to fetch recommendations and record attribution. ```typescript theme={null} const app = glood.getApp('recommendations'); ``` > [!NOTE] > > Methods marked **v3** require a version-3 client (the default). Calling a v3-only > method such as `getInit` on a `version: 2` client throws. ### getSections() Fetch recommendation sections (with full product data) for the current visitor. **v3.** ```typescript theme={null} getSections(params: GetSectionsParams): Promise ``` ```typescript theme={null} const { sections } = await app.getSections({ pageType: 'product_page', productId: 123456789, }); ``` ### getInit() Bootstrap a headless session β€” server-issued ids, visitor history, shop config, and storefront token. **v3 only** (throws for v2 clients). ```typescript theme={null} getInit(params?: InitParams): Promise ``` ```typescript theme={null} const init = await app.getInit({ pageType: 'home' }); console.log(init.visit_id, init.visitor.browsed_products); ``` ### getRecommendations() Fetch anchor-based recommendations. **Version-aware** β€” uses the client's configured API version. v3 returns `RecommendationsResponse`; v2 returns the legacy `V2RecommendationsResponse` shape. ```typescript theme={null} getRecommendations( params: RecommendationsParams ): Promise ``` ```typescript theme={null} const res = await app.getRecommendations({ queries: [ { id: 'pdp-similar', recommendationType: 'similar_products', productIds: [123456789], view: 'product_details', }, ], }); ``` ### getAutomaticRecommendations() Fetch single-anchor, cursor-paginated similar-products recommendations. **v3.** ```typescript theme={null} getAutomaticRecommendations( params: AutomaticRecommendationsParams ): Promise ``` ```typescript theme={null} const res = await app.getAutomaticRecommendations({ productIds: [123456789], view: 'product_details', pagination: { limit: 12 }, }); ``` ### getTopRecommendations() Fetch anchorless, strategy-ranked, faceted catalog recommendations. **v3.** ```typescript theme={null} getTopRecommendations( params: TopRecommendationsParams ): Promise ``` ```typescript theme={null} const res = await app.getTopRecommendations({ strategy: 'BESTSELLERS', // 'BESTSELLERS' | 'NEW_ARRIVALS' (uppercase) view: 'product_details', facets: ['vendor', 'product_type'], }); ``` ### sendEvent() Send a single interaction event to the headless events endpoint. **v3.** ```typescript theme={null} sendEvent(params: HeadlessEventParams): Promise ``` ```typescript theme={null} await app.sendEvent({ event: { id: crypto.randomUUID(), name: 'product_viewed', type: 'standard', timestamp: new Date().toISOString(), data: { productId: '123456789' }, }, }); ``` ### Attribution Tracking The following helpers emit `glood:section:*` custom events to attribute interactions back to a rendered section. Each takes a `SectionTrack` and returns `void`. ```typescript theme={null} trackRender(track: SectionTrack): void // section rendered in the DOM trackView(track: SectionTrack): void // section entered the viewport trackClick(track: SectionTrack): void // click on a recommended product trackAddToCart(track: SectionTrack): void // add-to-cart of a recommended product ``` ```typescript theme={null} app.trackClick({ section: '42', sectionServeId: section.section_serve_id, requestId: sectionsResponse.request_id, page: 'product', products: [{ productId: '123456789', variantId: '987654321' }], }); ``` ## search() Enables AI search & discovery β€” instant search, full search results, filters, and image search. Search is a **v1** headless API on its own host, independent of the client's global `version`. ### Signature ```typescript theme={null} function search(options?: { events?: EventType[] }): GloodAppModule ``` `options.events` narrows which Shopify standard events are forwarded to the search backend (default: **all** events). ### Default Configuration ```typescript theme={null} { apiVersion: 1, // pinned β€” always v1, even on a v2/v3 client endpoint: 'https://search.glood.ai', pixel: { enabled: true, endpoint: 'https://search.glood.ai/api/storefront/event', consent: ['analytics'], }, } ``` ### Basic Usage ```typescript theme={null} import { createGlood, search } from '@glood/hydrogen'; const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', }).use(search()); // Narrow forwarded events: const glood2 = createGlood({ apiKey, myShopifyDomain }) .use(search({ events: ['search_submitted', 'product_added_to_cart'] })); ``` ### SearchApp Methods Get the app instance and call its methods: ```typescript theme={null} const app = glood.getApp('search'); // SearchApp ``` | Method | Signature | | - | - | | `config` | `(params?: SearchConfigParams) => Promise` | | `instantSearch` | `(params: InstantSearchParams) => Promise` | | `filters` | `(params?: FiltersParams) => Promise` | | `search` | `(params?: SearchParams) => Promise` | | `imageSearch` | `(params: ImageSearchParams) => Promise` | Plus the attribution helpers `trackSearch`, `trackResultView`, `trackResultClick`, `trackAddToCart`, `trackFilter` β€” each takes a `SearchTrack` and emits a `glood:search:*` custom event. See the [Search API Reference](/for-developers/glood-hydrogen-sdk/api-reference/search-api#searchapp) for full details. ## App Configuration Interface The recommendations app config structure: ```typescript theme={null} interface RecommendationsAppConfig { /** Main API endpoint for app features */ endpoint: string; /** Pixel tracking configuration */ pixel: { /** Enable/disable pixel tracking */ enabled: boolean; /** Pixel tracking endpoint */ endpoint: string; /** Required consent types */ consent: ConsentType[]; }; /** Events this app should subscribe to (optional) */ subscribedEvents?: EventType[]; } ``` ### Consent Types Available consent types for pixel tracking: ```typescript theme={null} import { CONSENT_TYPES } from '@glood/hydrogen'; CONSENT_TYPES.ANALYTICS // 'analytics' - Basic analytics CONSENT_TYPES.MARKETING // 'marketing' - Marketing and ads CONSENT_TYPES.PREFERENCES // 'preferences' - Personalization CONSENT_TYPES.SALE_OF_DATA // 'sale_of_data' - Data selling ``` ### Event Types Available event types for subscriptions: ```typescript theme={null} type EventType = | 'page_viewed' | 'product_viewed' | 'collection_viewed' | 'cart_viewed' | 'search_submitted' | 'product_added_to_cart' | 'product_removed_from_cart' | 'custom_promotion_viewed'; ``` ## Client Override Configuration The recommendations app configuration can be overridden at the client level: ```typescript theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', apps: { recommendations: { endpoint: 'https://custom-storefront.glood.ai', pixel: { enabled: false, endpoint: 'https://custom-storefront.glood.ai', consent: ['analytics'], }, }, }, }).use(recommendations()); // Will use overridden configuration ``` ## Accessing Apps at Runtime Get app instances from the client: ```typescript theme={null} // Get specific app const recommendationsApp = glood.getApp('recommendations'); if (recommendationsApp) { console.log('Recommendations endpoint:', recommendationsApp.endpoint); console.log('Pixel enabled:', recommendationsApp.pixel.enabled); } // Get all enabled apps const enabledApps = glood.getEnabledApps(); console.log('Enabled apps:', enabledApps.map(app => app.name)); // Check app configuration enabledApps.forEach(app => { console.log(`${app.name}:`, { endpoint: app.endpoint, pixelEnabled: app.pixel.enabled, events: app.subscribedEvents, }); }); ``` ## Best Practices ### 1. Privacy Compliance Set appropriate consent requirements: ```typescript theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', apps: { recommendations: { endpoint: 'https://storefront.glood.ai', pixel: { enabled: true, endpoint: 'https://storefront.glood.ai', consent: ['analytics', 'marketing'], }, }, }, }).use(recommendations()); ``` ### 2. Performance Optimization Disable pixel tracking in development: ```typescript theme={null} const isDev = process.env.NODE_ENV === 'development'; const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', apps: { recommendations: { endpoint: 'https://storefront.glood.ai', pixel: { enabled: !isDev, endpoint: 'https://storefront.glood.ai', consent: ['analytics'], }, }, }, }).use(recommendations()); ``` ## See Also * [Client API](/for-developers/glood-hydrogen-sdk/api-reference/client) - createGlood() and GloodClient * [Event System](/for-developers/glood-hydrogen-sdk/api-reference/event-system) - Event tracking and transformation * [Types Reference](/for-developers/glood-hydrogen-sdk/api-reference/types) - TypeScript interfaces * [Configuration Guide](/for-developers/glood-hydrogen-sdk/configuration) - Detailed configuration options # Client API Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/api-reference/client Complete reference for createGlood() function and GloodClient interface # Client API The client API provides the core functionality for creating and configuring your Glood SDK instance. ## createGlood() Creates a new Glood client instance with the specified configuration. ### Signature ```typescript theme={null} function createGlood(config: GloodConfig): GloodClient ``` ### Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `config` | `GloodConfig` | Yes | Configuration object for the Glood client | ### Basic Usage ```typescript theme={null} import { createGlood, recommendations } from '@glood/hydrogen'; const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', }).use(recommendations()); ``` ### Advanced Usage ```typescript theme={null} import { createGlood, recommendations, CONSENT_TYPES } from '@glood/hydrogen'; const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // 2 | 3 β€” defaults to 3 apps: { recommendations: { endpoint: 'https://storefront.glood.ai', pixel: { enabled: true, endpoint: 'https://storefront.glood.ai', consent: [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING], }, }, }, debug: process.env.NODE_ENV === 'development', settings: { customKey: 'customValue', }, }).use(recommendations()); ``` > [!NOTE] > > The `version` option selects the headless API version. **Version `3` (default)** is > the full suite β€” init, sections, events, and the recommendations variants. > **Version `2`** is legacy and only supports recommendations, authenticating by shop > header alone (no bearer token). ### Error Handling The function throws errors for invalid configurations: ```typescript theme={null} // Throws: "Glood: apiKey is required and must be a non-empty string" createGlood({ myShopifyDomain: 'store.myshopify.com' }); // Throws: "Glood: myShopifyDomain is required and must be a valid Shopify domain" createGlood({ apiKey: 'key' }); // Throws when version is not 2 or 3 createGlood({ apiKey: 'key', myShopifyDomain: 'store.myshopify.com', version: 4, // ❌ only 2 or 3 are valid }); // Warns: Domain format doesn't match typical Shopify format createGlood({ apiKey: 'key', myShopifyDomain: 'custom-domain.com' }); ``` ## GloodConfig Interface Configuration object for creating a Glood client. ### Properties | Property | Type | Required | Default | Description | | - | - | - | - | - | | `apiKey` | `string` | Yes | - | Your Glood API key for authentication | | `myShopifyDomain` | `string` | Yes | - | Your Shopify domain (e.g., 'store-name.myshopify.com') | | `version` | `2 \| 3` | No | `3` | Headless API version. Throws if not 2 or 3. | | `apps` | `object` | No | Auto-generated | App-specific configurations | | `debug` | `boolean` | No | `false` | Enable debug logging | | `settings` | `Record` | No | `{}` | Additional custom settings | ### App Configuration The `apps` property allows per-app customization: ```typescript theme={null} interface GloodConfig { apps?: { recommendations?: RecommendationsAppConfig; }; } ``` The recommendations app config has this structure: ```typescript theme={null} interface RecommendationsAppConfig { endpoint: string; // Main API endpoint pixel: { enabled: boolean; // Enable/disable pixel tracking endpoint: string; // Pixel tracking endpoint consent: ConsentType[]; // Required consent types }; subscribedEvents?: EventType[]; // Events to subscribe to (optional) } ``` ### Default App Configuration When `apps` is not provided, these defaults are used: ```typescript theme={null} { recommendations: { endpoint: 'https://storefront.glood.ai', pixel: { enabled: true, endpoint: 'https://storefront.glood.ai', consent: ['analytics', 'marketing'], }, }, } ``` ## GloodClient Interface The client instance returned by `createGlood()`. ### Properties | Property | Type | Description | | - | - | - | | `config` | `GloodConfig` | The configuration used to create this client | | `debug` | `boolean` | Whether debug mode is enabled | | `apps` | `Map` | Map of registered app instances | ### Methods #### use() Registers an app module with the client. ```typescript theme={null} use(appModuleOrFactory: GloodAppModule | ((config?: any) => GloodAppModule)): GloodClient ``` **Parameters:** * `appModuleOrFactory`: App module function or factory **Returns:** The client instance (for method chaining) **Usage:** ```typescript theme={null} import { recommendations } from '@glood/hydrogen'; const glood = createGlood(config) .use(recommendations()); ``` #### getEnabledApps() Returns all registered app instances. ```typescript theme={null} getEnabledApps(): GloodApp[] ``` **Returns:** Array of enabled app instances **Usage:** ```typescript theme={null} const apps = glood.getEnabledApps(); console.log('Enabled apps:', apps.map(app => app.name)); ``` #### getApp() Gets a specific app by name. ```typescript theme={null} getApp(name: AppName): GloodApp | undefined ``` **Parameters:** * `name`: App name ('recommendations') **Returns:** App instance or `undefined` if not found **Usage:** ```typescript theme={null} const recommendationsApp = glood.getApp('recommendations'); if (recommendationsApp) { console.log('Recommendations endpoint:', recommendationsApp.endpoint); } ``` #### getInitData() Reads the `/v3/headless/init` response saved after the page-load session init. This is the synchronous, non-React counterpart to the [`useGloodInit()`](/for-developers/glood-hydrogen-sdk/api-reference/components#usegloodinit) hook. ```typescript theme={null} getInitData(): InitResponse | null ``` **Returns:** The `InitResponse` once init has resolved, or `null` if init hasn't run yet or the client is configured for `version: 2` (init is v3-only). **Usage:** ```typescript theme={null} const session = glood.getInitData(); if (session) { console.log('visit:', session.visit_id, 'user:', session.user_id); console.log('currency:', session.config?.shop?.currency); } ``` > [!NOTE] > > Read-only for app code. The value is written only by the SDK's page-load init > flow (`runHeadlessInit`, run automatically by `GloodProvider` for v3 clients). ## Configuration Examples ### Basic Setup Minimal configuration with defaults: ```typescript theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', }).use(recommendations()); ``` ### Environment-Specific Setup Different configurations for different environments: ```typescript theme={null} const isDevelopment = process.env.NODE_ENV === 'development'; const isStaging = process.env.NODE_ENV === 'staging'; const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: process.env.SHOPIFY_DOMAIN!, apps: { recommendations: { endpoint: isDevelopment ? 'https://dev-storefront.glood.ai' : isStaging ? 'https://staging-storefront.glood.ai' : 'https://storefront.glood.ai', pixel: { enabled: !isDevelopment, // Disable pixels in development endpoint: 'https://storefront.glood.ai', consent: ['analytics', 'marketing'], }, }, }, debug: isDevelopment, }).use(recommendations()); ``` ### Legacy v2 Setup Pin the client to the legacy v2 recommendations API: ```typescript theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 2, // legacy β€” recommendations only }).use(recommendations()); ``` ## Error Handling The client provides comprehensive error handling: ### Validation Errors ```typescript theme={null} try { const glood = createGlood({ apiKey: '', // Invalid: empty string myShopifyDomain: 'invalid-domain', }); } catch (error) { console.error('Configuration error:', error.message); // "Glood: apiKey must be a non-empty string" } ``` ### Runtime Errors ```typescript theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', debug: true, // Enable debug logging }); // Errors will be logged with full details in debug mode ``` ### Domain Validation ```typescript theme={null} // Valid Shopify domains createGlood({ apiKey: 'key', myShopifyDomain: 'store.myshopify.com', // βœ… Valid }); createGlood({ apiKey: 'key', myShopifyDomain: 'store.shopify.com', // βœ… Valid (Shopify Plus) }); // Warning for non-standard domains createGlood({ apiKey: 'key', myShopifyDomain: 'custom-domain.com', // ⚠️ Warning logged }); ``` ## Best Practices ### 1. Environment Variables Always use environment variables for sensitive data: ```typescript theme={null} // βœ… Good const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: process.env.SHOPIFY_DOMAIN!, }); // ❌ Bad - hardcoded credentials const glood = createGlood({ apiKey: 'hardcoded_key', myShopifyDomain: 'hardcoded_domain.myshopify.com', }); ``` ### 2. Debug Mode Enable debug mode in development: ```typescript theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: process.env.SHOPIFY_DOMAIN!, debug: process.env.NODE_ENV === 'development', }); ``` ### 3. Error Handling Wrap client creation in try-catch for production: ```typescript theme={null} try { const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: process.env.SHOPIFY_DOMAIN!, }); } catch (error) { console.error('Failed to initialize Glood client:', error); // Handle gracefully or use fallback } ``` ### 4. Method Chaining Use method chaining for cleaner code: ```typescript theme={null} const glood = createGlood(config) .use(recommendations()); ``` ## See Also * [React Components](/for-developers/glood-hydrogen-sdk/api-reference/components) - GloodProvider and hooks * [App Modules](/for-developers/glood-hydrogen-sdk/api-reference/app-modules) - recommendations() * [Configuration Guide](/for-developers/glood-hydrogen-sdk/configuration) - Detailed configuration options * [Types Reference](/for-developers/glood-hydrogen-sdk/api-reference/types) - TypeScript interface definitions # React Components Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/api-reference/components Complete reference for GloodProvider and the useGloodAnalytics, useGloodInit, and useRecommendations hooks # React Components The SDK provides React components and hooks for seamless integration with your Hydrogen application. ## Lifecycle On page load the SDK's components and hooks fire in a fixed sequence. `GloodProvider` bootstraps the session first (v3 init), and `useRecommendations` waits for that to settle before fetching sections β€” so recommendations are always attributed to the init-issued visitor. ```mermaid theme={null} sequenceDiagram participant Page as Page load participant GP as GloodProvider participant API as Glood API (v3) participant UR as useRecommendations participant UI as Your component Page->>GP: mount (inside Analytics.Provider) GP->>API: POST /v3/headless/init Note over GP: also subscribes to Shopify analytics events API-->>GP: InitResponse (user_id, visit_id, config, token) Note over GP: useGloodInit() gets data; useGloodInitReady() becomes true GP-->>UR: init ready UR->>API: POST /v3/headless/sections (carries init user_id) API-->>UR: sections + experience UR-->>UI: { sections, loading: false } UI->>API: trackRender / View / Click β†’ POST /v3/headless/events ``` **Sequence of hooks:** 1. **`GloodProvider` mounts** β€” subscribes to Shopify analytics and, for a v3 client, calls `/v3/headless/init` once. (v2 clients skip init.) 2. **`useGloodInit()`** β€” returns the init response once it resolves (`null` until then, and always `null` for v2). Also readable synchronously via `client.getInitData()`. 3. **`useGloodInitReady()`** β€” flips to `true` when init settles (or immediately for v2 / no client). This is the gate the next step waits on. 4. **`useRecommendations(params)`** β€” holds in `loading` until `useGloodInitReady()` is `true`, then fetches `/v3/headless/sections`. The request carries the init-issued `user_id`. 5. **`useGloodAnalytics()` + `trackRender/View/Click/AddToCart`** β€” fire attribution events (through the recommendations app) to `/v3/headless/events` as the visitor interacts. > [!NOTE] > > For a **v2** client there is no init call: `useGloodInitReady()` is `true` immediately, so `useRecommendations` fetches without waiting. Events route to `/api/storefront/event` instead of `/v3/headless/events`. ## GloodProvider A React context provider that automatically subscribes to Shopify Analytics events, manages pixel tracking for the recommendations app, and β€” for v3 clients β€” fires the headless session init on mount. ### Signature ```typescript theme={null} function GloodProvider({ client, loaderData, children }: GloodProviderProps): React.ReactElement ``` ### Props | Prop | Type | Required | Description | | - | - | - | - | | `client` | `GloodClient` | Yes | Glood client instance created with `createGlood()` | | `loaderData` | `unknown` | No | Route loader data forwarded to enabled apps | | `children` | `React.ReactNode` | Yes | Child components to wrap | ### Basic Usage ```tsx theme={null} import { Analytics } from '@shopify/hydrogen'; import { GloodProvider, createGlood, recommendations } from '@glood/hydrogen'; const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // 2 | 3, default 3 }).use(recommendations()); export default function App() { return ( ); } ``` ### How It Works The `GloodProvider` component: 1. **Creates React Context** - Provides the Glood client to all child components 2. **Fires Headless Init** - On mount, a v3 client calls `POST /api/storefront/v3/headless/init` once to bootstrap the session. The response is exposed via [`useGloodInit()`](#usegloodinit). For a v2 client this is a no-op. 3. **Subscribes to Analytics** - Uses Hydrogen's `useAnalytics()` hook to receive events 4. **Distributes Events** - Routes events to the recommendations app based on its subscriptions 5. **Checks Consent** - Verifies customer privacy permissions before sending pixels 6. **Handles Errors** - Provides comprehensive error handling and debug logging > [!NOTE] > > The headless init runs exactly once per provider mount and only when the client is configured for API version 3 (the default). It replays a persisted visitor id, creates a per-visit id, and returns the shop config, storefront token, and visitor history. Init failures are logged but never block rendering. ### Event Subscription Flow ```mermaid theme={null} graph TD A[Shopify Analytics] --> B[GloodProvider] B --> C[Event Distribution] C --> D[Consent Check] D --> E[Pixel Transmission] E --> F[Glood Endpoints] ``` ### Error Handling The provider includes comprehensive error handling: ```tsx theme={null} // Invalid client handling // Logs: "[Glood] GloodProvider: client is required" // Renders children without Glood functionality // Debug mode error logging const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', debug: true, // Enable detailed error logging }); ``` ### Server-Side Rendering The provider automatically handles SSR β€” analytics subscriptions only run in the browser: ```tsx theme={null} // Only runs on client-side useEffect(() => { if (typeof window === 'undefined' || !analytics?.customerPrivacy) { if (debug) { console.log('[Glood Debug] Skipping analytics setup: not in browser'); } return; } // Setup analytics subscriptions }, [clientConfig, analytics]); ``` ## useGloodAnalytics A React hook that provides access to the Glood client from context. ### Signature ```typescript theme={null} function useGloodAnalytics(): GloodClient | null ``` ### Returns | Type | Description | | - | - | | `GloodClient \| null` | The Glood client instance or `null` if used outside provider | ### Usage ```tsx theme={null} import { useGloodAnalytics } from '@glood/hydrogen'; function MyComponent() { const glood = useGloodAnalytics(); if (!glood) { // Component used outside GloodProvider return
Glood not available
; } // Access client properties const isDebugMode = glood.debug; const enabledApps = glood.getEnabledApps(); return (

Debug mode: {isDebugMode ? 'On' : 'Off'}

Enabled apps: {enabledApps.map(app => app.name).join(', ')}

); } ``` ## useGloodInit A React hook that returns the `/v3/headless/init` response fired by `GloodProvider` on mount. ### Signature ```typescript theme={null} function useGloodInit(): InitResponse | null ``` ### Returns | Type | Description | | - | - | | `InitResponse \| null` | The headless init response. `null` until init resolves, and always `null` for v2 clients (init is v3-only). | The `InitResponse` carries the server-issued session identity and shop context: the echoed `user_id`, the per-visit `visit_id`, `visitor` history (browsed / cart / purchased), the shop `config` (currency, money format, storefront GraphQL version, integrations, analytics enabled), and the storefront `token`. ### Usage ```tsx theme={null} import { useGloodInit } from '@glood/hydrogen'; function CurrencyBadge() { const init = useGloodInit(); // null until init resolves, and always null for v2 clients if (!init) return null; return Currency: {init.config?.shop?.currency}; } ``` > [!NOTE] > > Outside React, read the same value synchronously with > [`client.getInitData()`](/for-developers/glood-hydrogen-sdk/api-reference/client#getinitdata). ## useGloodInitReady A React hook that reports whether the page-load headless init has **settled** β€” resolved, failed, or skipped (v2 / no client). `useRecommendations` waits on this internally so the init call lands before the first sections request; you can use it to gate your own init-dependent calls. ### Signature ```typescript theme={null} function useGloodInitReady(): boolean ``` ### Returns | Type | Description | | - | - | | `boolean` | `false` while a v3 init is in flight; `true` once it settles (or immediately for v2 / no client, which have no init to wait for). | ### Usage ```tsx theme={null} import { useGloodInitReady, useGloodAnalytics } from '@glood/hydrogen'; function useRecommendationsAfterInit(params) { const ready = useGloodInitReady(); const client = useGloodAnalytics(); useEffect(() => { if (!ready) return; // hold until init has run client?.getApp('recommendations')?.getRecommendations(params); }, [ready]); } ``` ## useRecommendations A React hook that fetches recommendation sections client-side (in the browser). Prefer this for client-side rendering; use `fetchRecommendationSections(options, params)` in SSR route loaders instead. Must be used within a `GloodProvider` whose client has the recommendations app registered. > [!NOTE] > > **Ordering:** for a v3 client the hook waits for the page-load > `/v3/headless/init` call to settle before fetching sections (it stays in the > `loading` state until then). This guarantees init runs first and the sections > request carries the init-issued visitor id. For v2 clients there is no init, > so sections fetch immediately. Full signature, parameters, and return fields are documented in the [Recommendations API](/for-developers/glood-hydrogen-sdk/api-reference/recommendations-api#userecommendations). ### Usage ```tsx theme={null} import { useRecommendations } from '@glood/hydrogen'; function ProductRecommendations({ productId }: { productId: string }) { const { sections, loading, error, trackClick } = useRecommendations({ pageType: 'product_page', productId, }); if (loading) return
Loading…
; if (error) return null; return ( <> {sections.map(section => (

{section.title}

{section.products.map(product => ( trackClick({ section, product })} > {product.title} ))}
))} ); } ``` ## Provider Placement ### Correct Placement The `GloodProvider` must be placed correctly in your component tree: ```tsx theme={null} // βœ… Correct - Inside Analytics, wrapping application routes import { Analytics } from '@shopify/hydrogen'; export default function App() { return ( ); } ``` ### Incorrect Placement ```tsx theme={null} // ❌ Incorrect - Outside Analytics component export default function App() { return ( ); } // ❌ Incorrect - Inside individual routes export default function ProductPage() { return ( ); } ``` ## Debug Logging Enable debug mode to see detailed component behavior: ```tsx theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', debug: process.env.NODE_ENV === 'development', }).use(recommendations()); ``` Debug logs include: ``` [Glood Debug] Setting up event subscriptions for apps: ['recommendations'] [Glood Debug] Set analytics instance on recommendations app [Glood Debug] App recommendations subscribes to events: ['page_viewed', 'product_viewed', ...] [Glood Debug] All unique event types: ['page_viewed', 'product_viewed', ...] [Glood Debug] Setting up centralized subscription for page_viewed [Glood Debug] Received page_viewed event, distributing to interested apps [Glood Debug] Apps interested in page_viewed: ['recommendations'] [Glood Debug] Processing page_viewed event for recommendations: { url: '/products/shirt', ... } [Glood Debug] Consent granted for recommendations, processing event [Glood Debug] Headless init complete: { user_id: '…', visit_id: '…', config: { … } } ``` ## Performance Considerations ### Memoization The provider uses React's `useMemo` to prevent unnecessary re-renders: ```tsx theme={null} const clientConfig = useMemo(() => ({ debug: client.debug, enabledApps: client.getEnabledApps(), appsKeys: Array.from(client.apps.keys()) }), [client]); ``` ### Event Deduplication Events are subscribed to only once per event type, regardless of how many apps are interested: ```tsx theme={null} // Subscribe once per event type allEventTypes.forEach((eventType: EventType) => { subscribe(eventType, (eventData: any) => { // Distribute to all interested apps const interestedApps = enabledAppsWithPixel.filter(app => app.subscribedEvents.includes(eventType) ); interestedApps.forEach(app => { app.handleEvent(eventType, eventData, client); }); }); }); ``` ### Lazy Loading Analytics setup is deferred to prevent blocking: ```tsx theme={null} useEffect(() => { const timer = setTimeout(() => { // Setup analytics subscriptions }, 0); return () => clearTimeout(timer); }, [clientConfig, analytics]); ``` ## Error Scenarios ### Missing Analytics ```tsx theme={null} // Hydrogen analytics not available if (!analytics?.customerPrivacy) { if (debug) { console.log('[Glood Debug] Skipping analytics setup: analytics not available'); } return; } ``` ### Network Errors ```tsx theme={null} // Pixel transmission errors are handled gracefully try { app.handleEvent(eventType, eventData, client); } catch (error) { console.error('[Glood] Error processing event:', error); if (debug) { console.error('[Glood Debug] Event data:', eventData); } } ``` ### Consent Denial ```tsx theme={null} // Events are not processed if consent is not granted if (checkConsent(app.pixel.consent, canTrack, analytics)) { app.handleEvent(eventType, eventData, client); } else { if (debug) { console.log(`[Glood Debug] Consent not granted for ${app.name}, skipping event`); } } ``` ## Best Practices ### 1. Single Provider Instance Use only one `GloodProvider` at the root of your application: ```tsx theme={null} // βœ… Good - Single provider at root // ❌ Bad - Multiple providers
``` ### 2. Client Stability Create the client outside of the component to prevent recreating: ```tsx theme={null} // βœ… Good - Client created once const glood = createGlood(config).use(recommendations()); export default function App() { return ( ); } // ❌ Bad - Client recreated on every render export default function App() { const glood = createGlood(config).use(recommendations()); return ( ); } ``` ### 3. Conditional Hook Usage Always check for null when using the hook: ```tsx theme={null} function MyComponent() { const glood = useGloodAnalytics(); // βœ… Good - Check for null if (!glood) { return ; } // Use glood safely const apps = glood.getEnabledApps(); } ``` ### 4. Error Boundaries Wrap the provider in error boundaries for production: ```tsx theme={null} import { ErrorBoundary } from 'react-error-boundary'; function ErrorFallback({ error }) { return (

Glood Error

{error.message}
); } export default function App() { return ( ); } ``` ## See Also * [Client API](/for-developers/glood-hydrogen-sdk/api-reference/client) - createGlood() and GloodClient * [App Modules](/for-developers/glood-hydrogen-sdk/api-reference/app-modules) - App configuration and usage * [Event System](/for-developers/glood-hydrogen-sdk/api-reference/event-system) - Event tracking and pixel transmission * [Examples](/for-developers/glood-hydrogen-sdk/examples/recommendations) - Complete working recommendations page # Event System Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/api-reference/event-system Complete guide to event tracking, transmission, and analytics integration # Event System The Glood SDK's event system automatically transforms Shopify Analytics events into Glood event data and transmits them to the versioned headless events API with full privacy compliance. > [!NOTE] > > Events are routed by the client's configured `version` off the recommendations app's **main endpoint** β€” they are no longer sent to a separate `events.glood.ai` host. See [Event Destination](#event-destination) below. ## Architecture Overview The event system follows this flow: ```mermaid theme={null} graph TD A[Shopify Analytics] --> B[GloodProvider] B --> C[Event Distribution] C --> D[Event Transformation] D --> E[Consent Check] E --> F[Event Queue] F --> G[HTTP Transmission] G --> H[Versioned Events API] ``` ### Components 1. **Event Subscription** - Automatically subscribes to Shopify Analytics events 2. **Event Distribution** - Routes events to interested apps 3. **Data Transformation** - Converts Shopify data to Glood pixel format 4. **Consent Checking** - Verifies customer privacy permissions 5. **Pixel Queue** - Manages immediate transmission with retry logic 6. **Error Handling** - Comprehensive error handling and logging ## Event Types The SDK tracks these Shopify Analytics events: ### Core Events | Event Type | Description | Triggered When | | - | - | - | | `page_viewed` | Page navigation | User visits any page | | `product_viewed` | Product page view | User views product details | | `collection_viewed` | Collection page view | User browses product collections | | `cart_viewed` | Shopping cart view | User opens shopping cart | ### Commerce Events | Event Type | Description | Triggered When | | - | - | - | | `product_added_to_cart` | Add to cart | User adds product to cart | | `product_removed_from_cart` | Remove from cart | User removes product from cart | | `custom_promotion_viewed` | Promotion view | User sees promotional content | ### Attribution Events (Custom) Unlike the standard events above (which are fully automatic), attribution events are sent by calling the track helpers when a visitor interacts with a recommendation section. They use `event.type: 'custom'` and carry the interaction details in `event.customData.track`: | Event Type | Description | Sent By | | - | - | - | | `glood:section:render` | Section rendered in the DOM | `trackRender(track)` | | `glood:section:view` | Section scrolled into viewport | `trackView(track)` | | `glood:section:click` | Recommended product clicked | `trackClick(track)` | | `glood:section:add_to_cart` | Recommended product added to cart | `trackAddToCart(track)` | Attribution events flow through the **same versioned events API** as standard events (see [Event Destination](#event-destination)) β€” on a v3 client they `POST` to `/api/storefront/v3/headless/events` with `event.type: 'custom'`. See the [Recommendations API](/for-developers/glood-hydrogen-sdk/api-reference/recommendations-api#sectiontrack-object) for the `SectionTrack` payload shape. ### Search Events When the search app is registered (`.use(search())`), it behaves the same way, but forwards events to the **search backend** (v1, `https://search.glood.ai`) instead: * **Standard events** β€” `SearchApp` subscribes to all Shopify standard events by default, so `GloodProvider` forwards `product_viewed`, `search_submitted`, `product_added_to_cart`, `collection_viewed`, `cart_viewed`, … to `POST /api/storefront/v1/headless/events` automatically. Narrow them with `search({ events: [...] })`. * **Custom attribution events** β€” the `SearchApp` track helpers (also returned by `useSearch`) emit `glood:search:*` custom events: | Event Type | Description | Sent By | | - | - | - | | `glood:instant_search_triggered` | Search / results rendered | `trackSearch(track)` | | `glood:search_result_rendered` | Result scrolled into viewport | `trackResultView(track)` | | `glood:search_result_clicked` | Result clicked | `trackResultClick(track)` | | `glood:search:add_to_cart` | Result added to cart | `trackAddToCart(track)` | | `glood:search_filter_updated` | Facet applied / changed | `trackFilter(track)` | Each takes a [`SearchTrack`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#searchtrack-object) (`request_id`, `search_term`, `search_type`, `products`, `filters`, `source`, `page_type`). To send a search event manually (SSR / non-React), use [`sendSearchEvent(options, params)`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#sendsearchevent), the v1 analogue of `sendHeadlessEvent`. The events body uses `channel` values `'HYDROGEN' | 'HEADLESS' | 'MOBILE'` and requires at least one of `visitor_id` / `client_id` (defaulted from cookies in the browser). ## Event Transformation The SDK transforms Shopify Analytics events into Glood pixel format using sophisticated data transformation: ### Shopify β†’ Glood Transformation ```typescript theme={null} // Shopify Analytics Event { eventType: 'product_viewed', products: [{ id: 'gid://shopify/Product/123', title: 'Cool T-Shirt', price: '29.99', variantId: 'gid://shopify/ProductVariant/456', // ... other Shopify data }], shop: { currency: 'USD' }, // ... other event data } // Transformed to Glood Pixel { event: { id: 'evt_abc123', name: 'product_viewed', type: 'standard', timestamp: '2024-03-15T10:30:00.000Z', clientId: 'client_xyz789', context: { page: { url: '/products/cool-t-shirt', title: 'Cool T-Shirt' }, userAgent: 'Mozilla/5.0...', screen: { width: 1920, height: 1080 } }, data: { productVariant: { id: '456', title: 'Cool T-Shirt', price: { amount: 29.99, currencyCode: 'USD' }, product: { id: '123', title: 'Cool T-Shirt', url: '/products/cool-t-shirt' } } } }, rkUid: 'rk_user_id', data: { customer: null, cart: null, shop: { name: 'My Store', myshopifyDomain: 'my-store.myshopify.com', paymentSettings: { currencyCode: 'USD' } } }, customerPrivacy: { analyticsProcessingAllowed: true, marketingAllowed: true, preferencesProcessingAllowed: true, saleOfDataAllowed: false }, sessionId: 'session_def456', experience: '27647', // A/B experience id from localStorage `gai_s_e` cartIdentifier: null } ``` > [!NOTE] > > The `experience` field carries the A/B experience id assigned by the recommendations API. The SDK persists it to localStorage (key `gai_s_e`) after every sections fetch, and every event includes it automatically β€” this is how analytics segment by experience. It is `null` until the first sections fetch. ### Event-Specific Transformations #### Product Viewed ```typescript theme={null} // Extracted product data data: { productVariant: { id: '456', title: 'Cool T-Shirt - Blue', price: { amount: 29.99, currencyCode: 'USD' }, product: { id: '123', title: 'Cool T-Shirt', vendor: 'Fashion Brand', url: '/products/cool-t-shirt', type: 'Apparel' }, sku: 'TSH-BLUE-M', image: { src: 'https://example.com/image.jpg' } } } ``` #### Cart Viewed ```typescript theme={null} // Complete cart contents data: { cart: { id: 'cart_123', cost: { totalAmount: { amount: 89.97, currencyCode: 'USD' } }, lines: [ { cost: { totalAmount: { amount: 29.99, currencyCode: 'USD' } }, merchandise: { id: '456', title: 'Cool T-Shirt - Blue', price: { amount: 29.99, currencyCode: 'USD' }, product: { id: '123', title: 'Cool T-Shirt', url: '/products/cool-t-shirt' } }, quantity: 1 } // ... more cart lines ], totalQuantity: 3 } } ``` ## Event Destination Events (both the automatic standard events and the custom attribution events) are routed by the client's configured `version` off the recommendations app's **main endpoint** (default `https://storefront.glood.ai`). There is no separate events host. > [tab] v3 (default) > > ``` > POST {endpoint}/api/storefront/v3/headless/events > ``` > > **Headers** > > ``` > Content-Type: application/json > Authorization: Bearer > x-shop: your-store.myshopify.com > ``` > > **Payload** β€” the headless events schema: > > ```typescript theme={null} > { > event: { > id: 'evt_abc123', > name: 'product_viewed', // or 'glood:section:click', etc. > type: 'standard', // 'custom' for attribution events > timestamp: '2024-03-15T10:30:00.000Z', > data: { /* event-specific data */ }, > customData: { track } // present on custom/attribution events > }, > channel: 'hydrogen', > session_id: 'session_def456', > client_id: 'client_xyz789', > user_id: 'user_...', > experience: '27647', > customer_privacy: { /* consent flags */ }, > cart: null, > customer: null, > page_url: '/products/cool-t-shirt' > } > ``` > [tab] v2 (legacy) > > ``` > POST {endpoint}/api/storefront/event > ``` > > **Headers** > > ``` > Content-Type: application/json > x-shop-myshopify-domain: your-store.myshopify.com > ``` > > v2 sends the legacy event payload (no bearer token; authenticated by shop header alone). > [!NOTE] > > Need to send a v3 event manually (outside the automatic analytics flow)? Use `sendHeadlessEvent(options, params)` or the recommendations app's `sendEvent(params)` β€” both `POST` to `/api/storefront/v3/headless/events`. ## Event Transmission ### Immediate Transmission The SDK uses immediate transmission with retry logic: ```typescript theme={null} class PixelQueue { add(item: PixelEvent): void { // Build headers from item.headers, falling back to the shop-domain header const headers = item.headers ?? { 'Content-Type': 'application/json', 'x-shop-myshopify-domain': item.shopDomain ?? '', }; // Send event immediately with retry logic this.sendEventWithRetry(item.endpoint, headers, item.data, 0); } private async sendEventWithRetry( endpoint: string, headers: Record, event: Record, retryCount: number ): Promise { try { const response = await fetch(endpoint, { method: 'POST', headers, body: JSON.stringify(event), keepalive: true, }); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } } catch (error) { // Retry with exponential backoff if (retryCount < this.retryDelays.length) { setTimeout(() => { this.sendEventWithRetry(endpoint, headers, event, retryCount + 1); }, this.retryDelays[retryCount]); } } } } ``` ### Retry Strategy * **Retry Delays**: `[1000, 2000, 4000, 8000]` milliseconds * **Max Retries**: 4 attempts total (initial + 3 retries) * **Backoff**: Exponential backoff strategy * **Error Logging**: Comprehensive error logging with debug details ### Network Resilience ```typescript theme={null} // Automatic retry on network failures const retryDelays = [1000, 2000, 4000, 8000]; // 1s, 2s, 4s, 8s // Error scenarios handled: // - Network timeouts // - HTTP 5xx server errors // - HTTP 4xx client errors (logged but not retried) // - JSON serialization errors // - CORS issues ``` ## Consent Management ### Automatic Consent Checking The SDK automatically checks customer consent before sending pixels: ```typescript theme={null} function checkConsent( requiredConsents: ConsentType[], canTrack: any, analytics: any ): boolean { if (!requiredConsents || requiredConsents.length === 0) { return true; // No consent required } return requiredConsents.every(consentType => { switch (consentType) { case 'analytics': return analytics.customerPrivacy?.analyticsProcessingAllowed(); case 'marketing': return analytics.customerPrivacy?.marketingAllowed(); case 'preferences': return analytics.customerPrivacy?.preferencesProcessingAllowed(); case 'sale_of_data': return analytics.customerPrivacy?.saleOfDataAllowed(); default: return false; } }); } ``` ### Consent Requirements by App | App | Default Consent Requirements | Description | | - | - | - | | **Recommendations** | `['analytics', 'marketing']` | Analytics for tracking + marketing for personalization | | **Search** | `['analytics']` | Analytics only β€” search events fire under analytics consent | ### Privacy Scenarios ```typescript theme={null} // Example consent scenarios const consentScenarios = { noConsent: { analyticsProcessingAllowed: false, marketingAllowed: false, preferencesProcessingAllowed: false, saleOfDataAllowed: false, }, analyticsOnly: { analyticsProcessingAllowed: true, marketingAllowed: false, preferencesProcessingAllowed: false, saleOfDataAllowed: false, }, fullConsent: { analyticsProcessingAllowed: true, marketingAllowed: true, preferencesProcessingAllowed: true, saleOfDataAllowed: true, }, }; // Results for recommendations: // Recommendations: noConsent ❌, analyticsOnly ❌, fullConsent βœ… ``` ## Session & Identity Management Identity is stored in cookies (`CookieStorage`). The cookie key names are: | Cookie | Purpose | Lifetime | | - | - | - | | `_glood_client_id` | Persistent client id | 1 year | | `_shopify_s` | Session id | 30 minutes | | `rk_uid` | Analytics user id (RK UID) | 1 year with full consent, session-only otherwise | | `_glood_user_id` | Server-issued visitor id from `/v3/headless/init` | 1 year | | `_glood_visit_id` | Server-issued per-visit id from `/v3/headless/init` | 30 minutes | ### Client ID Generation ```typescript theme={null} class CookieStorage { static getOrGenerateClientId(): string { const existingId = this.getCookie('_glood_client_id'); if (existingId) return existingId; const newId = generateClientId(); this.setCookie('_glood_client_id', newId); // default max-age 1 year return newId; } } ``` ### Session Management ```typescript theme={null} // Session ID (30-minute cookie, not sessionStorage) static getOrGenerateSessionId(): string { const existingId = this.getCookie('_shopify_s'); if (existingId) return existingId; const newId = generateSessionId(); this.setCookie('_shopify_s', newId, 30 * 60); // 30 minutes return newId; } ``` ## Debug Logging ### Debug Mode Events Enable debug mode to see detailed event flow: ```typescript theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', debug: true, // Enable debug logging }); ``` ### Debug Log Examples ``` [Glood Debug] Setting up event subscriptions for apps: ['recommendations'] [Glood Debug] App recommendations subscribes to events: ['page_viewed', 'product_viewed', ...] [Glood Debug] All unique event types: ['page_viewed', 'product_viewed', ...] [Glood Debug] Setting up centralized subscription for product_viewed [Glood Debug] Received product_viewed event, distributing to interested apps [Glood Debug] Apps interested in product_viewed: ['recommendations'] [Glood Debug] Processing product_viewed event for recommendations: { products: [...] } [Glood Debug] Consent granted for recommendations, processing event [Glood Debug] recommendations app sending event: { event: { ... } } [Glood Debug] Sending event immediately: { endpoint: 'https://storefront.glood.ai/api/storefront/v3/headless/events', data: {...} } [Glood Debug] Sending event to https://storefront.glood.ai/api/storefront/v3/headless/events (attempt 1): { event: {...} } [Glood Debug] Successfully sent event to https://storefront.glood.ai/api/storefront/v3/headless/events ``` ### Error Debug Logs ``` [Glood Debug] Consent not granted for recommendations, skipping event [Glood Debug] Retrying event in 2000ms (attempt 2) [Glood Debug] Failed event: { event: {...} } [Glood] Failed to send pixel event after all retries: NetworkError ``` ## Performance Considerations ### Event Deduplication Events are subscribed to only once per event type: ```typescript theme={null} // Single subscription per event type, distributed to multiple apps allEventTypes.forEach((eventType: EventType) => { subscribe(eventType, (eventData: any) => { // Find all interested apps const interestedApps = enabledAppsWithPixel.filter(app => app.subscribedEvents.includes(eventType) ); // Distribute to all interested apps interestedApps.forEach(app => { app.handleEvent(eventType, eventData, client); }); }); }); ``` ### Immediate Transmission No batching delays - events are sent immediately: ```typescript theme={null} // No queuing delays pixelQueue.add({ endpoint: `${base}/api/storefront/v3/headless/events`, data: transformedEventData, }); // Sends immediately ``` ### Memory Management * **No accumulation** - Events are not stored in memory * **Immediate processing** - Events are transformed and sent immediately * **Cleanup** - Event handlers are properly cleaned up on unmount ## Error Handling ### Network Errors ```typescript theme={null} // Automatic retry with exponential backoff catch (error) { if (retryCount < this.retryDelays.length) { const delay = this.retryDelays[retryCount]; setTimeout(() => { this.sendEventWithRetry(endpoint, headers, event, retryCount + 1); }, delay); } else { console.error('[Glood] Failed to send pixel event after all retries:', error); } } ``` ### Consent Errors ```typescript theme={null} // Graceful handling when consent is denied if (!checkConsent(app.pixel.consent, canTrack, analytics)) { if (debug) { console.log(`[Glood Debug] Consent not granted for ${app.name}, skipping event`); } return; // Skip event processing } ``` ### Transformation Errors ```typescript theme={null} // Safe transformation with fallbacks try { const pixelData = this.transformEventData(eventType, eventData, client); this.sendPixel(pixelData, client); } catch (error) { console.error(`[Glood] Error transforming ${eventType} event:`, error); if (client.debug) { console.error('[Glood Debug] Original event data:', eventData); } } ``` ## Custom Event Handling ### Accessing Raw Events ```typescript theme={null} import { useGloodAnalytics } from '@glood/hydrogen'; function CustomAnalytics() { const glood = useGloodAnalytics(); useEffect(() => { if (!glood) return; const recommendationsApp = glood.getApp('recommendations'); if (!recommendationsApp) return; // Custom event handling const originalHandler = recommendationsApp.handleEvent.bind(recommendationsApp); recommendationsApp.handleEvent = (eventType, eventData, client) => { // Custom processing console.log('Custom event processing:', { eventType, eventData }); // Call original handler originalHandler(eventType, eventData, client); }; }, [glood]); return null; } ``` ### Custom Data Enrichment ```typescript theme={null} // Extend event data before transformation function enrichEventData(eventData: any): any { return { ...eventData, customField: 'custom value', timestamp: new Date().toISOString(), sessionData: getSessionData(), }; } ``` ## Best Practices ### 1. Debug Mode in Development ```typescript theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: process.env.SHOPIFY_DOMAIN!, debug: process.env.NODE_ENV === 'development', }); ``` ### 2. Monitor Network Errors ```typescript theme={null} // Add global error handler for pixel transmission issues window.addEventListener('unhandledrejection', (event) => { if (event.reason?.message?.includes('Glood')) { console.error('Glood pixel transmission error:', event.reason); // Report to error tracking service } }); ``` ### 3. Validate Consent Configuration ```typescript theme={null} // Ensure appropriate consent for recommendations const glood = createGlood({ apps: { recommendations: { pixel: { consent: ['analytics', 'marketing'], // Appropriate for personalization }, }, }, }); ``` ### 4. Test Event Flow ```typescript theme={null} // Verify events are flowing correctly const glood = createGlood({ debug: true, // Enable to see event flow }); // Check browser console for: // - Event subscriptions setup // - Event reception and distribution // - Consent checking results // - Pixel transmission success/failure ``` ## See Also * [App Modules](/for-developers/glood-hydrogen-sdk/api-reference/app-modules) - App configuration and event subscriptions * [Components](/for-developers/glood-hydrogen-sdk/api-reference/components) - GloodProvider setup * [Utilities](/for-developers/glood-hydrogen-sdk/api-reference/utilities) - Consent, session bootstrap, and pixel queue utilities * [Content Security Policy](/for-developers/glood-hydrogen-sdk/content-security-policy) - CSP configuration for pixel transmission # Recommendations API Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/api-reference/recommendations-api Complete reference for useRecommendations, the standalone headless functions, and the RecommendationsApp methods # Recommendations API Reference for fetching recommendation sections and sending attribution events. For a guided walkthrough, see [Loading Recommendations](/for-developers/glood-hydrogen-sdk/recommendations). ## useRecommendations() React hook that fetches recommendation sections for the current page. Must be used within a `` whose client has the recommendations app registered. ### Signature ```typescript theme={null} function useRecommendations( params: GetSectionsParams, options?: UseRecommendationsOptions ): UseRecommendationsResult ``` ### Parameters `params` is a [`GetSectionsParams`](/for-developers/glood-hydrogen-sdk/api-reference/signatures#getsectionsparams) β€” `pageType` is required; `pageUrl`, `locale`, and `clientId` default to browser values in the browser. `options` accepts a single `skip?: boolean` (default `false`) to hold fetching until required params are ready. ### Returns β€” UseRecommendationsResult | Attribute | Type | Description | | - | - | - | | `sections` | `RecommendationSection[]` | Sections with full product data. Empty array while loading or when none configured | | `data` | `SectionsResponse \| null` | Full API response (`request_id`, `experience`, `visit_id`, `config`, ...) | | `loading` | `boolean` | `true` while the request is in flight | | `error` | `Error \| null` | `GloodApiError` on API failures, `Error` on setup problems | | `refetch` | `() => void` | Re-run the request with the same params | | `trackRender` | `(track: SectionTrack) => void` | Send a `glood:section:render` attribution event | | `trackView` | `(track: SectionTrack) => void` | Send a `glood:section:view` attribution event | | `trackClick` | `(track: SectionTrack) => void` | Send a `glood:section:click` attribution event | | `trackAddToCart` | `(track: SectionTrack) => void` | Send a `glood:section:add_to_cart` attribution event | ### Basic Usage ```tsx theme={null} import { useRecommendations } from '@glood/hydrogen'; const { sections, loading, error } = useRecommendations({ pageType: 'product_page', productId: '8977367564515', }); ``` ### With All Options ```tsx theme={null} const { sections, data, loading, error, refetch, trackClick } = useRecommendations( { pageType: 'cart', cartProductIds: ['8977367564515', '9311227838783'], cartValue: '199.00', currency: 'USD', customerId: '7412356789', sections: [218966], // only this section }, { skip: false }, ); ``` ## Standalone Functions Isomorphic functions for the v2/v3 headless suite. Use them in Hydrogen route loaders (SSR) or anywhere you need the API without a React component. Every function takes `options: HeadlessRequestOptions` as its first argument. ### Endpoints Each function POSTs to a path under the client's main endpoint (default `https://storefront.glood.ai`), versioned by `options.version` (default `3`): | Function | Method + Path | Version | | - | - | - | | `fetchHeadlessInit` | `POST /api/storefront/v3/headless/init` | v3 only | | `fetchRecommendationSections` | `POST /api/storefront/v3/headless/sections` | v3 only | | `sendHeadlessEvent` | `POST /api/storefront/v3/headless/events` | v3 only | | `fetchRecommendations` | `POST /api/storefront/v{version}/headless/recommendations` | v2 or v3 (dispatch) | | `fetchV3Recommendations` | `POST /api/storefront/v3/headless/recommendations` | v3 | | `fetchV2Recommendations` | `POST /api/storefront/v2/headless/recommendations` | v2 | | `fetchAutomaticRecommendations` | `POST /api/storefront/v3/headless/recommendations/automatic` | v3 only | | `fetchTopRecommendations` | `POST /api/storefront/v3/headless/recommendations/top` | v3 only | > [!NOTE] > > v3-only functions throw if `options.version` is explicitly `2` (they will not silently upgrade). v3 requests send `Authorization: Bearer ` + `x-shop`; v2 authenticates by the `x-shop` header alone (no bearer token). ### HeadlessRequestOptions The first argument to every standalone function β€” `apiKey` (required for v3) and `myShopifyDomain` are required; `endpoint`, `version` (default `3`), and `debug` are optional. See the full field table in [Signatures β†’ HeadlessRequestOptions](/for-developers/glood-hydrogen-sdk/api-reference/signatures#headlessrequestoptions). ### fetchRecommendationSections() Fetch recommendation sections with full product data (v3). Works server-side and in the browser; the `useRecommendations` hook uses this internally. ```typescript theme={null} async function fetchRecommendationSections( options: HeadlessRequestOptions, params: GetSectionsParams ): Promise ``` The second argument is the same [`GetSectionsParams`](#parameters--getsectionsparams) as the hook, except `pageUrl` and `locale` are **required outside the browser** (there are no defaults on the server). ```typescript theme={null} import { fetchRecommendationSections } from '@glood/hydrogen'; export async function loader({ request, params, context }) { const recommendations = await fetchRecommendationSections( { apiKey: context.env.GLOOD_API_KEY, myShopifyDomain: 'your-store.myshopify.com', }, { pageType: 'product_page', pageUrl: request.url, locale: 'en-US', productId: params.productId, }, ).catch(() => null); return { recommendations }; } ``` ### fetchHeadlessInit() Bootstrap a headless session (v3 only): server-issued `visit_id`/`user_id`, visitor history, shop `config` and storefront `token`. In the browser, `clientId` and `pageUrl` default from the cookie/`window`. `GloodProvider` calls this automatically on mount β€” use it directly only for custom bootstrapping. ```typescript theme={null} async function fetchHeadlessInit( options: HeadlessRequestOptions, params?: InitParams ): Promise ``` `InitParams`: `userId?`, `clientId?`, `customerId?`, `pageType?`, `pageUrl?` β€” all optional. ### sendHeadlessEvent() Send a single interaction event to the events ingestion endpoint (v3 only). In the browser, `channel` (`'hydrogen'`), `sessionId` and `clientId` are filled in when omitted; the server requires `session_id` and one of `client_id`/`user_id`. ```typescript theme={null} async function sendHeadlessEvent( options: HeadlessRequestOptions, params: HeadlessEventParams ): Promise ``` `HeadlessEventParams` centers on the `event` object (`{ id, name, type: 'standard' | 'custom', timestamp, data? | customData? }`) plus optional `channel`, `sessionId`, `clientId`, `userId`, `customerId`, `experience`, `pageType`, `pageUrl`. Any extra fields (`cart`, `customer`, `customer_privacy`, ...) pass through in the API's snake\_case wire format. Returns `{ ok: boolean, ... }`. > [!WARNING] > > `event.timestamp` must be an ISO 8601 string within Β±2 days of now (server rule). ### fetchRecommendations() Version-aware dispatch: routes to v2 or v3 by `options.version` (default `3`). Prefer `fetchV2Recommendations` / `fetchV3Recommendations` when you want the concrete return type without narrowing. ```typescript theme={null} async function fetchRecommendations( options: HeadlessRequestOptions, params: RecommendationsParams ): Promise ``` ### fetchV3Recommendations() Multi-query, anchor-based recommendations (v3). Each query in `params.queries` is a `RecommendationQuery` (`{ id, recommendationType, productIds, view, maxRecommendations?, creationType? }`, up to 10 anchor product ids per query). Results are keyed by each query's `id`. ```typescript theme={null} async function fetchV3Recommendations( options: HeadlessRequestOptions, params: RecommendationsParams ): Promise ``` `RecommendationsParams`: `queries: RecommendationQuery[]`, plus optional `clientId`, `userId`, `customerId`. ### fetchV2Recommendations() Multi-query similar-products recommendations (v2 β€” shop-header auth only, no bearer token). ```typescript theme={null} async function fetchV2Recommendations( options: HeadlessRequestOptions, params: V2RecommendationsParams ): Promise ``` `V2RecommendationsParams`: `{ queries: RecommendationQuery[] }`. Response data is keyed by query id: `{ serve_id, products }`. ### fetchAutomaticRecommendations() Single-anchor, cursor-paginated similar-products recommendations (v3 only). ```typescript theme={null} async function fetchAutomaticRecommendations( options: HeadlessRequestOptions, params: AutomaticRecommendationsParams ): Promise ``` `AutomaticRecommendationsParams`: `productIds: number[]`, `view: RecommendationView`, optional `recommendationType` (only `'similar_products'`), `maxRecommendations`, `filter`, `pagination: { cursor?, limit? }`. Returns `{ status, serve_id, pagination: { cursor, hasMore? }, products }`. ### fetchTopRecommendations() Anchorless, strategy-ranked, faceted catalog recommendations (v3 only). ```typescript theme={null} async function fetchTopRecommendations( options: HeadlessRequestOptions, params: TopRecommendationsParams ): Promise ``` `TopRecommendationsParams`: `strategy: 'BESTSELLERS' | 'NEW_ARRIVALS'` (uppercase), `view: RecommendationView`, optional `strategyOptions: { salesTimePeriod?: 7 | 15 | 30, bestsellerMetric? }`, `query` (full-text catalog search), `filter`, `facets: TopFacet[]` (`'vendor' | 'product_type' | 'tag' | 'price'`), `pagination`. Returns `{ status, serve_id, strategy, pagination, products, facets? }`. ### runHeadlessInit() Session-bootstrap helper used internally by `GloodProvider`: runs `fetchHeadlessInit` from a `GloodClient`, persisting/replaying the visitor id cookies. No-op (resolves `null`) for v2 clients. ```typescript theme={null} async function runHeadlessInit( client: GloodClient ): Promise ``` ### headlessRequest() Low-level POST primitive. Builds `${endpoint}/api/storefront/v{version}/headless/{resource}`, applies the per-version auth headers, and throws `GloodApiError` on a non-2xx response. The higher-level functions above are built on it. ```typescript theme={null} async function headlessRequest( resource: string, body: Record, options: HeadlessRequestOptions ): Promise ``` ### Errors β€” GloodApiError Thrown by every standalone function on any non-2xx response: ```typescript theme={null} class GloodApiError extends Error { /** HTTP status code, e.g. 401 */ readonly status: number; /** Parsed JSON error body, e.g. { error: 'Invalid authentication' } */ readonly body: unknown; } ``` ```typescript theme={null} import { GloodApiError } from '@glood/hydrogen'; try { await fetchRecommendationSections(options, params); } catch (error) { if (error instanceof GloodApiError && error.status === 401) { // Invalid or mismatched API key } } ``` ## RecommendationsApp The app instance registered via `client.use(recommendations())`. Retrieve it from the client for advanced usage: ```typescript theme={null} import { RecommendationsApp } from '@glood/hydrogen'; const app = client.getApp('recommendations') as RecommendationsApp; ``` ### Methods Alongside `getSections`, the app exposes `getInit`, `getRecommendations`, `getAutomaticRecommendations`, `getTopRecommendations`, `sendEvent`, and the `trackRender` / `trackView` / `trackClick` / `trackAddToCart` attribution helpers. See the full method list with signatures in [App Modules β†’ RecommendationsApp Methods](/for-developers/glood-hydrogen-sdk/api-reference/app-modules#recommendationsapp-methods). ```typescript theme={null} const data = await app.getSections({ pageType: 'home' }); app.trackClick({ section: '218966', sectionServeId: data.sections[0].section_serve_id, products: [{ productId: '9311227838783' }], }); ``` > [!NOTE] > > Attribution events respect the app's pixel configuration: if `pixel.enabled` is `false`, they are not sent. ## SectionTrack Object Links an attribution event to the exact section render it came from. Pass `sectionServeId` (the `section_serve_id` from the sections response) to tie the event to a specific render. See the full field table in [Signatures β†’ SectionTrack](/for-developers/glood-hydrogen-sdk/api-reference/signatures#sectiontrack). ```typescript theme={null} const track: SectionTrack = { section: '218966', sectionServeId: '56a98d2d-a014-4dd7-ab2d-1a5191b84262', requestId: '671778ec-8382-4d9e-9671-fb91daccf049', page: 'product_page', parent: { productId: '8977367564515' }, products: [ { productId: '9311227838783', variantId: '48792371233087', quantity: 1 }, ], }; ``` ## Response Shape β€” SectionsResponse ```typescript theme={null} interface SectionsResponse { /** Unique id for this request β€” pass to attribution events */ request_id: string; /** Sections with full product data */ sections: RecommendationSection[]; /** Current product details (product pages), or null */ product: Record | null; /** Shopify storefront access token from the shop config */ token: string | null; /** Shop configuration (currency, money format, integrations, ...) */ config: Record; /** Assigned A/B experience id β€” persisted to localStorage automatically */ experience: string | null; /** Unique id for this visit */ visit_id: string | null; } ``` See [TypeScript Types](/for-developers/glood-hydrogen-sdk/api-reference/types#recommendations-api-types) for the full `RecommendationSection` and `SectionProduct` definitions. ### Example Response ```json theme={null} { "request_id": "671778ec-8382-4d9e-9671-fb91daccf049", "sections": [ { "id": 218966, "section_serve_id": "56a98d2d-a014-4dd7-ab2d-1a5191b84262", "page_type": "home", "experience_id": 27647, "layout": "horizontal_grid", "location": "MainContent", "type": "bestsellers", "position": 3, "title": "Bestsellers", "extra": {}, "discount_config": { "enabled": false }, "show_discount_label": false, "translations": {}, "products": [ { "product_id": 9311227838783, "title": "The Collection Snowboard: Oxygen", "handle": "the-collection-snowboard-oxygen", "vendor": "Hydrogen Vendor", "product_type": "snowboard", "tags": "Premium, Snow", "price": 1025, "compare_at_price": null, "image": { "url": "https://cdn.shopify.com/..." }, "options": [ { "id": 1, "name": "Title", "values": ["Default Title"], "position": 1 } ], "variants": [ { "variant_id": 48792371233087, "title": "Default Title", "price": 1025, "compare_at_price": null, "sku": "", "selected_options": [{ "name": "Title", "value": "Default Title" }] } ], "metafields": [], "trending_rank": 3, "sales_rank": 7 } ], "cursor": null, "hasMore": false } ], "product": null, "token": "shpat_...", "config": { "shop": { "currency": "USD", "money_format": "${{amount}}" } }, "experience": "27647", "visit_id": "fc300769-ea40-43d9-8bf3-6b721913fea8" } ``` ## See Also * [Loading Recommendations Guide](/for-developers/glood-hydrogen-sdk/recommendations) - Walkthrough with rendering patterns * [Recommendations Example](/for-developers/glood-hydrogen-sdk/examples/recommendations) - Complete working page * [TypeScript Types](/for-developers/glood-hydrogen-sdk/api-reference/types) - All type definitions * [Event System](/for-developers/glood-hydrogen-sdk/api-reference/event-system) - How attribution events are transmitted # Search API Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/api-reference/search-api Complete reference for useSearch / useInstantSearch / useSearchConfig, the standalone search fetchers, the SearchApp methods, and search attribution events # Search API Reference for the Glood Hydrogen **Search v1** surface. For a guided walkthrough, see [Search & Discovery](/for-developers/glood-hydrogen-sdk/search). > [!NOTE] > > All search calls are **v1** on the search host (`https://search.glood.ai`) and authenticate with > `Authorization: Bearer ` + `x-shop`. Params are camelCase (mapped to snake\_case on the > wire); responses are snake\_case exactly as returned by the backend. ## Hooks React hooks, each usable within a `` whose client has the search app registered (`.use(search())`). ### useSearch() Runs a full product search for the current params and exposes attribution helpers. ```typescript theme={null} function useSearch( params: SearchParams, options?: { skip?: boolean } ): UseSearchResult ``` **Parameters** β€” `params` is a [`SearchParams`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchparams) (all optional; `query` may be `""`). `options.skip` (default `false`) holds fetching until required params are ready. **Returns β€” `UseSearchResult`** | Attribute | Type | Description | | - | - | - | | `products` | `SearchItem[]` | Result products (or `{ product_id }` refs when `view: 'product_ids'`). Empty while loading | | `data` | `SearchResponse \| null` | Full response (`request_id`, `pagination`, `facets`, `metadata`) | | `loading` | `boolean` | `true` while in flight | | `error` | `Error \| null` | `GloodApiError` on API failures | | `refetch` | `() => void` | Re-run with the same params | | `trackSearch` | `(track: SearchTrack) => void` | Emit `glood:instant_search_triggered` | | `trackResultView` | `(track: SearchTrack) => void` | Emit `glood:search_result_rendered` | | `trackResultClick` | `(track: SearchTrack) => void` | Emit `glood:search_result_clicked` | | `trackAddToCart` | `(track: SearchTrack) => void` | Emit `glood:search:add_to_cart` | | `trackFilter` | `(track: SearchTrack) => void` | Emit `glood:search_filter_updated` | ```tsx theme={null} const { products, data, trackResultClick } = useSearch({ query: 'running shoe', sort: 'price_asc', facets: [{ key: 'color', operator: 'or', value: ['red'] }], pagination: { page: 1, limit: 24 }, options: { includeFacets: true, personalize: true }, }); ``` ### useInstantSearch() Type-ahead search. On an empty / too-short query the response carries `trending`. ```typescript theme={null} function useInstantSearch( params: InstantSearchParams, options?: { skip?: boolean } ): UseInstantSearchResult ``` **Parameters** β€” `params` is an [`InstantSearchParams`](/for-developers/glood-hydrogen-sdk/api-reference/types#instantsearchparams) (`query` required, may be `""`). Use `options.skip` to gate on the minimum query length. **Returns β€” `UseInstantSearchResult`** | Attribute | Type | Description | | - | - | - | | `data` | `InstantSearchResponse \| null` | Full response (products, suggestions, autocorrect, trending) | | `products` | `SearchItem[]` | Convenience: `data.products.results` | | `suggestions` | `SearchSuggestion[]` | Convenience: keyword suggestions | | `collections` | `InstantSearchCollection[]` | Convenience: collection results | | `pages` | `InstantSearchPage[]` | Convenience: page results | | `loading` | `boolean` | `true` while in flight | | `error` | `Error \| null` | Error, if any | | `refetch` | `() => void` | Re-run with the same params | ```tsx theme={null} const { products, suggestions, data } = useInstantSearch( { query: term, objects: ['product', 'query_suggestion', 'autocorrect'] }, { skip: term.length < 2 }, ); ``` ### useSearchConfig() Fetches the headless search config (feature flags, filter definitions, shop, analytics, translations, storefront token). ```typescript theme={null} function useSearchConfig( params?: SearchConfigParams, options?: { skip?: boolean } ): UseSearchConfigResult ``` **Returns β€” `UseSearchConfigResult`**: `{ config: SearchConfigResponse | null, loading, error, refetch }`. ```tsx theme={null} const { config } = useSearchConfig({ locale: 'en-US' }); ``` ### useSearchInit() / useSearchInitReady() `GloodProvider` runs the search session bootstrap **once on mount** (when `search()` is registered), mirroring recs init. You don't call it yourself β€” these hooks read its result: ```typescript theme={null} function useSearchInit(): SearchInitResponse | null function useSearchInitReady(): boolean ``` * `useSearchInit()` returns the [`SearchInitResponse`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchinitparams--searchinitresponse) (visitor identity, history, lean `config`, `token`, `visit_id`), or `null` until it resolves. * `useSearchInitReady()` returns `true` once init has settled (success or failure). `useSearch` and `useInstantSearch` gate their fetches on this, so they don't fire before the session is bootstrapped. ```tsx theme={null} const init = useSearchInit(); const ready = useSearchInitReady(); // init?.visitor.browsed_products, init?.token, init?.visit_id … ``` ## Standalone functions Isomorphic functions for the v1 search suite. Use them in Hydrogen route loaders (SSR) or anywhere you need the API without a React component. Every function takes `options: FetchSearchOptions` as its first argument. ### Endpoints Each function POSTs to a path under the search endpoint (default `https://search.glood.ai`), all **v1**: | Function | Method + Path | | - | - | | `fetchSearchInit(options, params?)` | `POST /api/storefront/v1/headless/init` | | `fetchSearchConfig(options, params?)` | `POST /api/storefront/v1/headless/config` | | `fetchInstantSearch(options, params)` | `POST /api/storefront/v1/headless/instant-search` | | `fetchFilters(options, params?)` | `POST /api/storefront/v1/headless/filters` | | `fetchFilterAggregations(options, params?)` | `POST /api/storefront/v1/headless/filter-aggregations` | | `fetchSearchResults(options, params?)` | `POST /api/storefront/v1/headless/search` | | `fetchImageSearch(options, params)` | `POST /api/storefront/v1/headless/image-search` | | `sendSearchEvent(options, params)` | `POST /api/storefront/v1/headless/events` | > [!NOTE] > > `FetchSearchOptions` is the shared `HeadlessRequestOptions` β€” `apiKey` and `myShopifyDomain` > are required; `endpoint` (default `https://search.glood.ai`) and `debug` are optional. The > version is pinned to `1` internally. In the browser, `visitor_id` / `client_id` / `session_id` > default from the Glood cookies when omitted. > [!NOTE] > > The standalone functions above POST to whatever `endpoint` you pass in `options`. When you call > through the **`SearchApp`** (`app.imageSearch(...)`, the `track*` helpers, auto-subscribed events), > routing is split automatically: `imageSearch` and all events go to the app's **`controlEndpoint`** > (non-edge), while every other call uses `endpoint`. See > [Configuration β†’ Edge vs. non-edge routing](/for-developers/glood-hydrogen-sdk/configuration#edge-vs-non-edge-routing-controlendpoint). ### fetchSearchInit() Session bootstrap β€” resolves the visitor, returns their history (browsed / cart / purchased product ids), a lean feature-flag config (no filter definitions, no filter tree), the storefront token and a fresh `visit_id`. `GloodProvider` runs this automatically on mount; call it directly only for SSR or non-React use. ```typescript theme={null} async function fetchSearchInit( options: FetchSearchOptions, params?: SearchInitParams ): Promise ``` ### fetchSearchConfig() ```typescript theme={null} async function fetchSearchConfig( options: FetchSearchOptions, params?: SearchConfigParams ): Promise ``` ### fetchInstantSearch() `query` is required (may be `""`); throws locally if `query` is `undefined`/`null`. ```typescript theme={null} async function fetchInstantSearch( options: FetchSearchOptions, params: InstantSearchParams ): Promise ``` ### fetchFilters() ```typescript theme={null} async function fetchFilters( options: FetchSearchOptions, params?: FiltersParams ): Promise ``` ### fetchFilterAggregations() ```typescript theme={null} async function fetchFilterAggregations( options: FetchSearchOptions, params?: FilterAggregationsParams ): Promise ``` ### fetchSearchResults() ```typescript theme={null} async function fetchSearchResults( options: FetchSearchOptions, params?: SearchParams ): Promise ``` ```tsx theme={null} export async function loader({ request, context }) { const q = new URL(request.url).searchParams.get('q') ?? ''; const results = await fetchSearchResults( { apiKey: context.env.GLOOD_API_KEY, myShopifyDomain: 'your-store.myshopify.com' }, { query: q, pagination: { page: 1, limit: 24 } }, ).catch(() => null); return { results }; } ``` ### fetchImageSearch() Exactly one of `image` / `imageUrl` is required (throws locally otherwise). ```typescript theme={null} async function fetchImageSearch( options: FetchSearchOptions, params: ImageSearchParams ): Promise ``` ### sendSearchEvent() The v1 analogue of `sendHeadlessEvent`. In the browser, `channel` (`'hydrogen'`), `session_id`, `client_id` and `visitor_id` are filled from cookies when omitted. Extra snake\_case fields (`cart`, `customer`, `customer_privacy`, …) pass through. For SSR / non-React use; inside React prefer the `SearchApp` track helpers wired up by `GloodProvider`. ```typescript theme={null} async function sendSearchEvent( options: FetchSearchOptions, params: HeadlessEventParams ): Promise ``` ```tsx theme={null} await sendSearchEvent( { apiKey, myShopifyDomain }, { event: { id: crypto.randomUUID(), name: 'glood:search_result_clicked', type: 'custom', timestamp: new Date().toISOString(), // Search events are fully snake_case. Only navigator.user_agent is required, but // send document.location too β€” analytics scope funnels by its pathname. context: { document: { title: document.title, referrer: document.referrer, location: { href: location.href, pathname: location.pathname, search: location.search, }, }, navigator: { user_agent: navigator.userAgent, language: navigator.language, cookie_enabled: navigator.cookieEnabled, }, window: { screen: { width: window.screen.width, height: window.screen.height } }, }, custom_data: { track: { request_id, search_term: 'shoe', products: [{ product_id: '123' }] } }, }, channel: 'HYDROGEN', }, ); ``` > [!WARNING] > > `event.timestamp` must be an ISO 8601 string within Β±2 days of now (server rule). The events > API requires at least one of `visitor_id` / `client_id` (defaulted from cookies in the browser). ### Errors β€” GloodApiError Thrown by every standalone function on a non-2xx response (re-exported from the search module): ```typescript theme={null} import { GloodApiError } from '@glood/hydrogen'; try { await fetchSearchResults(options, params); } catch (error) { if (error instanceof GloodApiError && error.status === 401) { // Invalid or mismatched API key } } ``` ## SearchApp The app instance registered via `client.use(search())`. Retrieve it from the client for advanced / SSR usage: ```typescript theme={null} import { SearchApp } from '@glood/hydrogen'; const app = client.getApp('search') as SearchApp; ``` ### Methods | Method | Signature | Description | | - | - | - | | `init` | `(params?: SearchInitParams) => Promise` | Session bootstrap (visitor + history + lean config + token). `GloodProvider` runs it once on mount | | `config` | `(params?: SearchConfigParams) => Promise` | Fetch the search config | | `instantSearch` | `(params: InstantSearchParams) => Promise` | Instant search | | `filters` | `(params?: FiltersParams) => Promise` | Facet definitions | | `search` | `(params?: SearchParams) => Promise` | Full product search | | `imageSearch` | `(params: ImageSearchParams) => Promise` | Visual search | ```typescript theme={null} const res = await app.search({ query: 'shoe', pagination: { limit: 24 } }); ``` ### Event helpers Each emits a `glood:search:*` custom event via the pixel pipeline and returns `void`: ```typescript theme={null} trackSearch(track: SearchTrack): void // glood:instant_search_triggered trackResultView(track: SearchTrack): void // glood:search_result_rendered trackResultClick(track: SearchTrack): void // glood:search_result_clicked trackAddToCart(track: SearchTrack): void // glood:search:add_to_cart trackFilter(track: SearchTrack): void // glood:search_filter_updated ``` ```typescript theme={null} app.trackResultClick({ request_id: res.request_id, search_term: 'shoe', search_type: 'text', products: [{ product_id: '9311227838783', variant_id: '48792371233087', quantity: 1 }], filters: [{ key: 'color', value: ['red'] }], source: 'search_page', }); ``` > [!NOTE] > > Track events respect the app's pixel config: if `pixel.enabled` is `false`, they are not sent. ## search() module Factory that creates and configures the search app. Pass `{ events }` to narrow the standard Shopify events forwarded to the search backend (default: all events). ```typescript theme={null} function search(options?: { events?: EventType[] }): GloodAppModule ``` ```typescript theme={null} import { createGlood, search } from '@glood/hydrogen'; const glood = createGlood({ apiKey, myShopifyDomain }) .use(search({ events: ['search_submitted', 'product_added_to_cart'] })); ``` ## SearchTrack object Attribution payload for `glood:search:*` events (snake\_case wire shape): ```typescript theme={null} interface SearchTrack { request_id?: string; // request_id from the search response search_term?: string; search_type?: string; // 'text' | 'image' products?: Array<{ product_id: string | number; variant_id?: string | number; quantity?: number }>; filters?: Array<{ key: string; value: string | string[] }>; source?: string; page_type?: string; } ``` ## Response shapes The key response types (`SearchResponse`, `InstantSearchResponse`, `SearchConfigResponse`, `FiltersResponse`, `FilterAggregationsResponse`, `ImageSearchResponse`) and the shared `SearchProduct` object are documented in full in [TypeScript Types β†’ Search API Types](/for-developers/glood-hydrogen-sdk/api-reference/types#search-api-types). ### Example β€” SearchResponse ```json theme={null} { "status": "ok", "request_id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", "products": [ { "product_id": 9311227838783, "title": "Running Shoe", "handle": "running-shoe", "price": 49.99, "compare_at_price": 69.99, "display_price": 49.99, "display_currency": "USD", "available_for_sale": true, "is_in_stock": true, "image": { "url": "https://cdn.shopify.com/...", "alt_text": "Running Shoe" }, "options": [{ "id": 111, "name": "Size", "position": 1, "values": ["S", "M", "L"] }], "variants": [ { "variant_id": 456, "title": "M", "price": 49.99, "selected_options": [{ "name": "Size", "value": "M" }] } ], "metafields": [{ "namespace": "custom", "key": "material", "value": "leather" }] } ], "pagination": { "total": 240, "page": 1, "limit": 24, "total_pages": 10, "has_next_page": true, "has_prev_page": false, "next_page": 2, "prev_page": null }, "facets": [ { "key": "color", "type": "terms", "aggregation": { "buckets": [{ "value": "red", "count": 42, "selected": true }] } } ], "metadata": { "query_time": 40, "total_time": 55, "region": "toronto", "search_type": "hybrid" } } ``` ## See Also * [Search & Discovery Guide](/for-developers/glood-hydrogen-sdk/search) β€” walkthrough with rendering patterns * [Search Example](/for-developers/glood-hydrogen-sdk/examples/search) β€” complete working route * [TypeScript Types](/for-developers/glood-hydrogen-sdk/api-reference/types#search-api-types) β€” all search type definitions * [Event System](/for-developers/glood-hydrogen-sdk/api-reference/event-system) β€” how search events are transmitted # Signatures & Parameters Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/api-reference/signatures Argument structure for every hook, component, and function exported by @glood/hydrogen, in table form. A quick, table-first reference for the argument structure of everything exported from `@glood/hydrogen`. Object-typed arguments (e.g. `GloodConfig`, `GetSectionsParams`) are expanded under [Parameter object shapes](#parameter-object-shapes); full response types live in [Types](/for-developers/glood-hydrogen-sdk/api-reference/types). > [!NOTE] > > All headless calls run against API `version` (`2 | 3`, default `3`). Functions marked **v3-only** throw when called on a v2 client. ## Client ### createGlood(config) ```typescript theme={null} function createGlood(config: GloodConfig): GloodClient ``` | Argument | Type | Required | Description | | - | - | - | - | | `config` | [`GloodConfig`](#gloodconfig) | Yes | Client configuration. Throws if `apiKey`/`myShopifyDomain` are missing or `version` is not `2`/`3`. | **Returns:** `GloodClient` ### GloodClient methods | Method | Arguments | Returns | | - | - | - | | `use(appModuleOrFactory)` | `appModuleOrFactory: GloodAppModule` | `GloodClient` (chainable) | | `getEnabledApps()` | β€” | `GloodApp[]` | | `getApp(name)` | `name: AppName` (`'recommendations'`) | `GloodApp \| undefined` | | `getInitData()` | β€” | `InitResponse \| null` (saved `/v3/headless/init` response; read-only) | | `setInitData(data)` | `data: InitResponse \| null` | `void` (used internally by `runHeadlessInit`) | ## App module ### recommendations() ```typescript theme={null} function recommendations(): GloodAppModule ``` Takes no arguments. Pass to `client.use(recommendations())`. ### RecommendationsApp methods Obtain the app with `client.getApp('recommendations')`. | Method | Arguments | Returns | Notes | | - | - | - | - | | `getSections(params)` | `params:` [`GetSectionsParams`](#getsectionsparams) | `Promise` | v3 | | `getInit(params?)` | `params?:` [`InitParams`](#initparams) | `Promise` | **v3-only** | | `getRecommendations(params)` | `params:` [`RecommendationsParams`](#recommendationsparams) | `Promise` | version-aware | | `getAutomaticRecommendations(params)` | `params:` [`AutomaticRecommendationsParams`](#automaticrecommendationsparams) | `Promise` | **v3-only** | | `getTopRecommendations(params)` | `params:` [`TopRecommendationsParams`](#toprecommendationsparams) | `Promise` | **v3-only** | | `sendEvent(params)` | `params:` [`HeadlessEventParams`](#headlesseventparams) | `Promise` | **v3-only** | | `trackRender(track)` | `track:` [`SectionTrack`](#sectiontrack) | `void` | glood:section:render | | `trackView(track)` | `track:` [`SectionTrack`](#sectiontrack) | `void` | glood:section:view | | `trackClick(track)` | `track:` [`SectionTrack`](#sectiontrack) | `void` | glood:section:click | | `trackAddToCart(track)` | `track:` [`SectionTrack`](#sectiontrack) | `void` | glood:section:add\_to\_cart | ### search() ```typescript theme={null} function search(options?: { events?: EventType[] }): GloodAppModule ``` `options.events` narrows the forwarded standard events (default: all). Pass to `client.use(search())`. Search is pinned to **v1** regardless of the client version. ### SearchApp methods Obtain the app with `client.getApp('search')`. | Method | Arguments | Returns | Notes | | - | - | - | - | | `init(params?)` | `params?:` [`SearchInitParams`](#searchinitparams) | `Promise` | v1; auto-run once by `GloodProvider` | | `config(params?)` | `params?:` [`SearchConfigParams`](#searchconfigparams) | `Promise` | v1 | | `instantSearch(params)` | `params:` [`InstantSearchParams`](#instantsearchparams) | `Promise` | v1 | | `filters(params?)` | `params?:` [`FiltersParams`](#filtersparams) | `Promise` | v1 | | `search(params?)` | `params?:` [`SearchParams`](#searchparams) | `Promise` | v1 | | `imageSearch(params)` | `params:` [`ImageSearchParams`](#imagesearchparams) | `Promise` | v1 | | `trackSearch(track)` | `track:` [`SearchTrack`](#searchtrack) | `void` | glood:instant\_search\_triggered | | `trackResultView(track)` | `track:` [`SearchTrack`](#searchtrack) | `void` | glood:search\_result\_rendered | | `trackResultClick(track)` | `track:` [`SearchTrack`](#searchtrack) | `void` | glood:search\_result\_clicked | | `trackAddToCart(track)` | `track:` [`SearchTrack`](#searchtrack) | `void` | glood:search:add\_to\_cart | | `trackFilter(track)` | `track:` [`SearchTrack`](#searchtrack) | `void` | glood:search\_filter\_updated | ## Components & hooks ### GloodProvider(props) ```typescript theme={null} function GloodProvider(props: GloodProviderProps): React.ReactElement ``` | Prop | Type | Required | Description | | - | - | - | - | | `client` | `GloodClient` | Yes | The client from `createGlood()`. | | `loaderData` | `any` | Yes | Root loader data (shop/consent context). | | `children` | `ReactNode` | Yes | App tree. | Subscribes to Shopify analytics and fires `/v3/headless/init` on mount (v3). ### Hooks | Hook | Arguments | Returns | | - | - | - | | `useGloodAnalytics()` | β€” | `GloodClient \| null` | | `useGloodInit()` | β€” | `InitResponse \| null` (v3 init response; `null` until resolved / for v2) | | `useGloodInitReady()` | β€” | `boolean` (true once page-load init has settled) | | `useRecommendations(params, options?)` | `params:` [`GetSectionsParams`](#getsectionsparams), `options?: { skip?: boolean }` | `UseRecommendationsResult` | | `useSearch(params, options?)` | `params:` [`SearchParams`](#searchparams), `options?: { skip?: boolean }` | `UseSearchResult` | | `useInstantSearch(params, options?)` | `params:` [`InstantSearchParams`](#instantsearchparams), `options?: { skip?: boolean }` | `UseInstantSearchResult` | | `useSearchConfig(params?, options?)` | `params?:` [`SearchConfigParams`](#searchconfigparams), `options?: { skip?: boolean }` | `UseSearchConfigResult` | | `useSearchInit()` | β€” | `SearchInitResponse \| null` (search session bootstrap; `null` until resolved) | | `useSearchInitReady()` | β€” | `boolean` (true once search init has settled; `useSearch`/`useInstantSearch` gate on it) | `UseRecommendationsResult` = `{ sections, data, loading, error, refetch, trackRender, trackView, trackClick, trackAddToCart }`. `UseSearchResult` = `{ products, data, loading, error, refetch, trackSearch, trackResultView, trackResultClick, trackAddToCart, trackFilter }`. `UseInstantSearchResult` = `{ data, products, suggestions, collections, pages, loading, error, refetch }`. `UseSearchConfigResult` = `{ config, loading, error, refetch }`. ## Standalone functions All take `options:` [`HeadlessRequestOptions`](#headlessrequestoptions) as the first argument. | Function | Arguments | Returns | Notes | | - | - | - | - | | `fetchRecommendationSections(options, params)` | `params:` [`GetSectionsParams`](#getsectionsparams) | `Promise` | v3 | | `fetchHeadlessInit(options, params?)` | `params?:` [`InitParams`](#initparams) | `Promise` | **v3-only** | | `sendHeadlessEvent(options, params)` | `params:` [`HeadlessEventParams`](#headlesseventparams) | `Promise` | **v3-only** | | `fetchRecommendations(options, params)` | `params:` [`RecommendationsParams`](#recommendationsparams) | `Promise` | version-aware | | `fetchV3Recommendations(options, params)` | `params:` [`RecommendationsParams`](#recommendationsparams) | `Promise` | v3 | | `fetchV2Recommendations(options, params)` | `params:` [`V2RecommendationsParams`](#v2recommendationsparams) | `Promise` | v2 | | `fetchAutomaticRecommendations(options, params)` | `params:` [`AutomaticRecommendationsParams`](#automaticrecommendationsparams) | `Promise` | **v3-only** | | `fetchTopRecommendations(options, params)` | `params:` [`TopRecommendationsParams`](#toprecommendationsparams) | `Promise` | **v3-only** | | `headlessRequest(resource, body, options)` | `resource: string`, `body: Record` | `Promise` | low-level POST | | `runHeadlessInit(client)` | `client: GloodClient` | `Promise` | no-op/`null` for v2 | | `fetchSearchInit(options, params?)` | `params?:` [`SearchInitParams`](#searchinitparams) | `Promise` | search v1 | | `fetchSearchConfig(options, params?)` | `params?:` [`SearchConfigParams`](#searchconfigparams) | `Promise` | search v1 | | `fetchInstantSearch(options, params)` | `params:` [`InstantSearchParams`](#instantsearchparams) | `Promise` | search v1 | | `fetchFilters(options, params?)` | `params?:` [`FiltersParams`](#filtersparams) | `Promise` | search v1 | | `fetchFilterAggregations(options, params?)` | `params?:` [`FilterAggregationsParams`](#filteraggregationsparams) | `Promise` | search v1 | | `fetchSearchResults(options, params?)` | `params?:` [`SearchParams`](#searchparams) | `Promise` | search v1 | | `fetchImageSearch(options, params)` | `params:` [`ImageSearchParams`](#imagesearchparams) | `Promise` | search v1 | | `sendSearchEvent(options, params)` | `params:` [`HeadlessEventParams`](#headlesseventparams) | `Promise` | search v1 | > [!NOTE] > > Search fetchers take `options: FetchSearchOptions` (the same `HeadlessRequestOptions`) and are > pinned to v1 internally, defaulting `endpoint` to `https://search.glood.ai`. ## Utilities & errors | Export | Arguments | Returns | | - | - | - | | `checkConsent(requiredConsents, canTrack, analytics)` | `requiredConsents: readonly ConsentType[]`, `canTrack: () => boolean`, `analytics: any` | `boolean` | | `getPixelQueue(debug?)` | `debug?: boolean` (default `false`) | `PixelQueue` | | `resetPixelQueue()` | β€” | `void` | | `new GloodApiError(message, status, body)` | `message: string`, `status: number`, `body: unknown` | `GloodApiError` (`.status`, `.body`) | ## Parameter object shapes ### GloodConfig | Field | Type | Required | Default | Description | | - | - | - | - | - | | `apiKey` | `string` | Yes | β€” | Glood storefront token (`gl_sf_*`). | | `myShopifyDomain` | `string` | Yes | β€” | `store-name.myshopify.com`. | | `version` | `2 \| 3` | No | `3` | Headless API version. | | `apps` | `{ recommendations?: RecommendationsAppConfig }` | No | defaults | Per-app config. | | `debug` | `boolean` | No | `false` | Debug logging. | | `settings` | `Record` | No | β€” | Passthrough settings. | ### HeadlessRequestOptions | Field | Type | Required | Default | Description | | - | - | - | - | - | | `apiKey` | `string` | Yes (v3) | β€” | Storefront token; bearer for v3. | | `myShopifyDomain` | `string` | Yes | β€” | Sent as `x-shop`. | | `endpoint` | `string` | No | `https://storefront.glood.ai` | Endpoint override. | | `version` | `2 \| 3` | No | `3` | API version. | | `debug` | `boolean` | No | `false` | Log request/response. | ### GetSectionsParams | Field | Type | Required | Description | | - | - | - | - | | `pageType` | `PageType` | Yes | Page the visitor is on. | | `pageUrl` | `string` | No | Defaults to `window.location.href` in the browser. | | `locale` | `string` | No | Defaults to `navigator.language` in the browser. | | `productId` | `string \| number` | No | Numeric Shopify product id (product pages). | | `cartProductIds` | `Array` | No | Numeric ids in cart. | | `sections` | `number[]` | No | Specific section ids (empty = all). | | `clientId` | `string` | No | Defaults to the `_glood_client_id` cookie. | | `userId` | `string` | No | Defaults to the init `_glood_user_id` cookie. | | `customerId` | `string` | No | Shopify customer id. | | `market` | `string` | No | Market id. | | `currency` | `string` | No | Currency code. | | `cartValue` | `string` | No | Cart total. | | `collection` | `number` | No | Numeric collection id. | | `qs` | `string` | No | Query string for experience assignment. | | `preview` | `boolean` | No | Include disabled sections. | ### InitParams | Field | Type | Required | Description | | - | - | - | - | | `userId` | `string` | No | Replays a persisted visitor id (returning visitor). | | `clientId` | `string` | No | Defaults to the `_glood_client_id` cookie. | | `customerId` | `string` | No | Shopify customer id. | | `pageType` | `PageType` | No | Current page type. | | `pageUrl` | `string` | No | Defaults to `window.location.href`. | ### RecommendationQuery | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | Result key in the response. | | `recommendationType` | `string` | Yes | One of [`RecommendationType`](#recommendationtype-recommendationtype) β€” commonly `'similar_products'` / `'bought_together'`. | | `productIds` | `Array` | Yes | Anchor product ids (v3: up to 10). | | `maxRecommendations` | `number` | No | Max results. | | `creationType` | `string` | No | One of [`CreationType`](#creationtype-creationtype): `'manual'` \| `'automatic'`. | | `view` | `RecommendationView` | Yes | `'product_details'` or `'product_ids'`. | ### RecommendationsParams | Field | Type | Required | Description | | - | - | - | - | | `queries` | [`RecommendationQuery[]`](#recommendationquery) | Yes | Up to 5 (v3). | | `clientId` | `string` | No | Visitor client id. | | `userId` | `string` | No | Visitor user id. | | `customerId` | `string` | No | Shopify customer id. | ### V2RecommendationsParams | Field | Type | Required | Description | | - | - | - | - | | `queries` | [`RecommendationQuery[]`](#recommendationquery) | Yes | `similar_products` only on v2. | ### AutomaticRecommendationsParams | Field | Type | Required | Description | | - | - | - | - | | `productIds` | `number[]` | Yes | Anchor product ids. | | `view` | `RecommendationView` | Yes | `'product_details'` or `'product_ids'`. | | `recommendationType` | `'similar_products'` | No | Only value supported. | | `maxRecommendations` | `number` | No | Max results. | | `filter` | `Record` | No | Vendor/tag/variant filters. | | `pagination` | `{ cursor?: string \| null; limit?: number }` | No | Cursor pagination (limit default 12). | ### TopRecommendationsParams | Field | Type | Required | Description | | - | - | - | - | | `strategy` | `TopStrategy` | Yes | `'BESTSELLERS'` \| `'NEW_ARRIVALS'` β€” **uppercase**. | | `view` | `RecommendationView` | Yes | `'product_details'` or `'product_ids'`. | | `strategyOptions` | `{ salesTimePeriod?: 7 \| 15 \| 30; bestsellerMetric?: BestsellerMetric }` | No | `bestsellerMetric`: `'revenue'` \| `'quantity'` \| `'orders'`. | | `query` | `string` | No | Full-text catalog search. | | `filter` | `Record` | No | Vendor/tag/price/etc. filters. | | `facets` | `TopFacet[]` | No | `'vendor' \| 'product_type' \| 'tag' \| 'price'`. | | `pagination` | `{ cursor?: string \| null; limit?: number }` | No | Cursor pagination (limit default 24, max 100). | ### HeadlessEventParams | Field | Type | Required | Description | | - | - | - | - | | `event` | `{ id, name, type, timestamp, data?, customData? }` | Yes | `type` is `'standard' \| 'custom'`; `timestamp` ISO, within Β±2 days. | | `channel` | `HeadlessEventChannel` | No | `'mobile' \| 'headless' \| 'hydrogen'` (default `'hydrogen'`). | | `sessionId` | `string` | No | Defaults to the session cookie (server requires it). | | `clientId` | `string` | No | At least one of `clientId`/`userId` required. | | `userId` | `string` | No | See above. | | `customerId` | `string` | No | Shopify customer id. | | `experience` | `string \| null` | No | Assigned experience id. | | `pageType` | `string` | No | Page type. | | `pageUrl` | `string` | No | Page URL. | Additional fields (e.g. `cart`, `customer`, `customer_privacy`, `device`) are passed through in the API's snake\_case wire format. ### SectionTrack | Field | Type | Required | Description | | - | - | - | - | | `section` | `string` | No | Glood section id. | | `sectionServeId` | `string` | No | `section_serve_id` from the sections response. | | `requestId` | `string` | No | `request_id` from the sections response. | | `page` | `string` | No | Page type of the interaction. | | `parent` | `{ productId?: string; variantId?: string }` | No | Context product (e.g. the PDP product). | | `products` | `SectionTrackProduct[]` | No | Products involved (`{ productId, variantId?, quantity? }`). | ### SearchInitParams All optional. In the browser `visitorId` / `clientId` default from the Glood cookies. | Field | Type | Required | Description | | - | - | - | - | | `pageType` | `string` | No | Page the session starts on (context only). | | `pageUrl` | `string` | No | Full URL of that page. | | `locale` | `string` | No | BCP-47 locale (default `en-US`). | | `market` | `number` | No | Shopify market id. | | `visitorId` | `string` | No | Anonymous visitor UID; defaults from cookie in the browser. | | `clientId` | `string` | No | Per-session/device id; defaults from cookie in the browser. | | `customerId` | `string` | No | Shopify customer id (logged-in shoppers). | ### SearchConfigParams | Field | Type | Required | Description | | - | - | - | - | | `locale` | `string` | No | BCP-47 locale (default `en-US`). | | `market` | `number` | No | Shopify market id. | | `theme` | `number` | No | Theme id (parity only; no templates rendered). | | `targetPage` | `string` | No | `search` \| `collection`. | | `targetId` | `number` | No | Target object id (e.g. collection id). | | `visitorId` | `string` | No | Defaults from the visitor cookie in the browser. | | `skipCache` | `boolean` | No | Bypass the cached config. | ### InstantSearchParams | Field | Type | Required | Description | | - | - | - | - | | `query` | `string` | Yes | Search term (may be `""`). | | `locale` | `string` | No | BCP-47 locale. | | `market` | `number` | No | Shopify market id. | | `limit` | `number` | No | Per-type result limit (1–100). | | `objects` | [`InstantSearchObject[]`](#instantsearchobject-objects) | No | Result blocks to return. | | `view` | [`SearchView`](#searchview-view) | No | `product_details` (default) \| `product_ids`. | | `visitorId` / `clientId` / `customerId` | `string` | No | Identity triple (defaults from cookies in the browser). | | `trending` | `{ type?, period?, category?, limit? }` | No | Empty-state trending options (`type`: `searches` \| `products` \| `all`; `period`: `1h` \| `24h` \| `7d` \| `30d`). | ### FiltersParams | Field | Type | Required | Description | | - | - | - | - | | `collection` | `string \| number` | No | Collection id to scope the tree. | | `tree` | `number` | No | Explicit filter tree id. | | `targetPage` | `string` | No | `search` \| `collection`. | | `targetId` | `number` | No | Target object id. | | `locale` | `string` | No | BCP-47 locale. | | `market` | `number` | No | Shopify market id. | | `includeValues` | `boolean` | No | Include facet values (default `true`). | | `includeDisabled` | `boolean` | No | Include disabled filters (default `false`). | ### FilterAggregationsParams | Field | Type | Required | Description | | - | - | - | - | | `collection` | `string \| number` | No | Collection id to scope aggregation. | | `tree` | `number` | No | Explicit filter tree id. | | `query` | `string` | No | Search term (may be `""`). | | `appliedFilters` | `Array<{ key, value }>` | No | Applied filter selections. | | `facets` | `Array<{ key }>` | No | Which facets to aggregate. | | `locale` / `market` | `string` / `number` | No | Locale / market. | | `options` | `{ includeZeroCounts?, includeDisabled?, sortBy?, limit? }` | No | Aggregation options (`sortBy`: `count` \| `alpha` \| `position`). | | `visitorId` | `string` | No | Visitor id. | ### SearchParams | Field | Type | Required | Description | | - | - | - | - | | `query` | `string` | No | Search term (may be `""`). | | `targetPage` | `string` | No | `search` \| `collection`. | | `targetId` | `number` | No | Target object id (e.g. collection id). | | `locale` / `market` | `string` / `number` | No | Locale / market. | | `facets` | `Array<{ key, operator?, value }>` | No | Applied facets (`operator`: `or` \| `and` \| …). | | `sort` | [`SearchSort`](#searchsort-sort) | No | Result ordering (default `relevance`). | | `view` | [`SearchView`](#searchview-view) | No | `product_details` (default) \| `product_ids`. | | `pagination` | `{ page?, limit? }` | No | Page-based pagination (limit ≀ 100). | | `options` | `{ includeAggregations?, includeHighlights?, includeFacets?, boostInStock?, personalize? }` | No | Search options. | | `visitorId` / `clientId` / `customerId` | `string` | No | Identity triple. | ### ImageSearchParams | Field | Type | Required | Description | | - | - | - | - | | `image` | `string` | Cond. | Base64 or `data:` URL. Exactly one of `image` / `imageUrl`. | | `imageUrl` | `string` | Cond. | http(s) URL or `data:` base64 URL. Exactly one of `image` / `imageUrl`. | | `facets` | `Record \| Array` | No | Applied filters. | | `locale` / `market` | `string` / `number` | No | Locale (default `en`) / market. | | `view` | [`SearchView`](#searchview-view) | No | `product_details` (default) \| `product_ids`. | | `pagination` | `{ page?, limit? }` | No | Page-based pagination. | | `visitorId` / `clientId` / `customerId` | `string` | No | Identity triple. | ### SearchTrack | Field | Type | Required | Description | | - | - | - | - | | `request_id` | `string` | No | `request_id` from the search response. | | `search_term` | `string` | No | The search term. | | `search_type` | `string` | No | `text` \| `image`. | | `products` | `Array<{ product_id, variant_id?, quantity? }>` | No | Products involved. | | `filters` | `Array<{ key, value }>` | No | Applied filters. | | `source` | `string` | No | Interaction source. | | `page_type` | `string` | No | Page type. | ## Enums & value sets Several fields accept a fixed set of values. `recommendationType` / `creationType` are typed as `string` in the SDK (for forward-compat), but only the values below are meaningful. ### RecommendationType (`recommendationType`) | Value | Notes | | - | - | | `similar_products` | Supported on every recommendation endpoint (v2, v3, automatic). | | `bought_together` | v3 `/recommendations` only. | | `recently_viewed` | | | `cross_sell` | | | `bestsellers` | | | `trending` | | | `personalized` | | | `recent_launch` | | | `collections` | | | `purchases` | | | `promoted` | | | `custom` | | | `email_recommendations` | | > [!NOTE] > > `fetchV3Recommendations` / `getRecommendations` accept any of the above, but the backend currently returns results only for `similar_products` and `bought_together`. `fetchV2Recommendations` and `fetchAutomaticRecommendations` support `similar_products` only. ### CreationType (`creationType`) | Value | | - | | `manual` | | `automatic` | ### RecommendationView (`view`) | Value | Result item shape | | - | - | | `product_details` | Full product objects (`RecommendedProduct`). | | `product_ids` | `{ product_id: number }`. | ### TopStrategy (`strategy`) **Uppercase** β€” maps directly to the backend enum. | Value | | - | | `BESTSELLERS` | | `NEW_ARRIVALS` | ### BestsellerMetric (`strategyOptions.bestsellerMetric`) | Value | | - | | `revenue` | | `quantity` | | `orders` | `strategyOptions.salesTimePeriod` accepts `7`, `15`, or `30` (days). ### TopFacet (`facets[]`) | Value | | - | | `vendor` | | `product_type` | | `tag` | | `price` | ### HeadlessEventChannel (`channel`) | Value | Notes | | - | - | | `hydrogen` | Default for this SDK. | | `headless` | | | `mobile` | | ### Event type (`event.type`) | Value | | - | | `standard` | | `custom` | ### PageType (`pageType`) `product_page`, `collection`, `home`, `cart`, `order_confirm`, `other`, `blog`, `ajax_cart`, `404`, `checkout`, `returns` ### ConsentType (`pixel.consent[]`) `analytics`, `marketing`, `preferences`, `sale_of_data` ### Event names (`event.name`) Standard Shopify analytics events the SDK forwards: `page_viewed`, `product_viewed`, `collection_viewed`, `cart_viewed`, `search_submitted`, `product_added_to_cart`, `product_removed_from_cart`. Custom attribution events: `glood:section:render`, `glood:section:view`, `glood:section:click`, `glood:section:add_to_cart`, and for search: `glood:instant_search_triggered`, `glood:search_result_rendered`, `glood:search_result_clicked`, `glood:search:add_to_cart`, `glood:search_filter_updated`. ### SearchView (`view`) Product render mode for search endpoints: | Value | Result shape | | - | - | | `product_details` | Full [`SearchProduct`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchproduct) objects (default). | | `product_ids` | `{ product_id: number }` only. | ### SearchSort (`sort`) `relevance` (default), `title_asc`, `title_desc`, `price_asc`, `price_desc`, `best_selling`, `oldest`, `newest`. ### InstantSearchObject (`objects[]`) `product`, `collection`, `page`, `article`, `query_suggestion`, `autocorrect`. ### Search event channel (`channel`) The search events API (`sendSearchEvent`) uses **uppercase** channels: `HYDROGEN`, `HEADLESS`, `MOBILE`. `sendSearchEvent` defaults to `HYDROGEN`. ## See Also > [card] [Types](/for-developers/glood-hydrogen-sdk/api-reference/types) > > Full request/response type definitions. > [card] [Recommendations API](/for-developers/glood-hydrogen-sdk/api-reference/recommendations-api) > > Standalone function usage and endpoints. # TypeScript Types Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/api-reference/types Complete TypeScript interface definitions for the Glood Hydrogen SDK # TypeScript Types The Glood Hydrogen SDK is built with TypeScript-first design, providing comprehensive type definitions for all interfaces, configurations, and data structures. ## Core Configuration Types ### GloodConfig Main configuration interface for creating a Glood client. ```typescript theme={null} interface GloodConfig { /** Glood API key for authentication */ apiKey: string; /** Your Shopify domain (e.g., 'store-name.myshopify.com') */ myShopifyDomain: string; /** * Headless API version to use (2 or 3). Defaults to 3. Version 3 is the full * suite (init, sections, events, recommendations variants); version 2 only * has recommendations and authenticates by shop header alone (no bearer token). */ version?: ApiVersion; /** App-specific configurations (optional - uses defaults if not provided) */ apps?: { recommendations?: RecommendationsAppConfig; }; /** Enable debug logging in development */ debug?: boolean; /** Additional settings object */ settings?: Record; } ``` **Usage:** ```typescript theme={null} const config: GloodConfig = { apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // 2 | 3, default 3 debug: true, }; ``` ### PixelConfig Configuration for pixel tracking per app. ```typescript theme={null} interface PixelConfig { /** Enable/disable pixel tracking for this app */ enabled: boolean; /** Retained for config compatibility; no longer used to route events (see note) */ endpoint: string; /** Required consent types for pixel tracking */ consent: readonly ConsentType[]; } ``` > [!NOTE] > > `pixel.endpoint` is retained for backward compatibility but **no longer > determines where events are sent**. Events are routed by the client's > `version` off the app's main endpoint (v3 β†’ `/api/storefront/v3/headless/events`, > v2 β†’ `/api/storefront/event`). `pixel.enabled` and `pixel.consent` still apply. **Usage:** ```typescript theme={null} const pixelConfig: PixelConfig = { enabled: true, endpoint: 'https://events.glood.ai', consent: ['analytics', 'marketing'], }; ``` ## App Configuration Types ### RecommendationsAppConfig Configuration specific to the recommendations app. ```typescript theme={null} interface RecommendationsAppConfig { /** Main app endpoint for features and API calls */ endpoint: string; /** Pixel tracking configuration */ pixel: PixelConfig; /** Events this app should subscribe to (defaults to all events if not specified) */ subscribedEvents?: EventType[]; } ``` ### SearchAppConfig Configuration specific to the search app. ```typescript theme={null} interface SearchAppConfig { /** * Main app endpoint β€” used for init, config, instant-search, filters, * filter-aggregations and search. Point this at a regional edge to serve * those from the edge. Defaults to https://search.glood.ai. */ endpoint: string; /** * Non-edge (control-plane) endpoint for calls the edge cannot serve: * image search (needs the vision/embedding pipeline) and event ingestion. * Defaults to the built-in non-edge host, so overriding only `endpoint` * with an edge URL keeps image search + events on the control plane. */ controlEndpoint?: string; /** Pixel tracking configuration */ pixel: PixelConfig; /** Events this app should subscribe to (defaults to all events if not specified) */ subscribedEvents?: EventType[]; } ``` > [!NOTE] > > `imageSearch()` and all event ingestion route to `controlEndpoint`; every other search call > routes to `endpoint`. See [Configuration β†’ Edge vs. non-edge routing](/for-developers/glood-hydrogen-sdk/configuration#edge-vs-non-edge-routing-controlendpoint). ## Client & App Types ### GloodClient The main client interface returned by `createGlood()`. ```typescript theme={null} interface GloodClient { /** Configuration used to create this client */ config: GloodConfig; /** Debug mode enabled */ debug: boolean; /** Registered apps */ apps: Map; /** Get all enabled apps */ getEnabledApps(): GloodApp[]; /** Get specific app by name */ getApp(name: AppName): GloodApp | undefined; /** Add an app module to the client */ use(appModuleOrFactory: GloodAppModule | ((config?: any) => GloodAppModule)): GloodClient; /** Read the /v3/headless/init response saved on page load (null until it runs / for v2) */ getInitData(): InitResponse | null; /** Save the init response β€” called by runHeadlessInit; not intended for app code */ setInitData(data: InitResponse | null): void; } ``` ### GloodApp Interface representing an individual app instance. ```typescript theme={null} interface GloodApp { /** App name */ name: AppName; /** Main app endpoint for features */ endpoint: string; /** Pixel configuration */ pixel: PixelConfig; /** Events this app subscribes to */ subscribedEvents: EventType[]; /** Analytics instance from Hydrogen useAnalytics hook */ analytics?: any; /** Loader data from the Hydrogen route loader */ loaderData?: any; /** Handle an analytics event */ handleEvent(eventType: EventType, eventData: any, client: GloodClient): void; /** Set analytics instance on the app */ setAnalytics(analytics: any): void; /** Set loader data on the app */ setLoaderData?: (loaderData: any) => void; /** Set the owning client (injected by client.use()) so the app can make API calls */ setClient?: (client: GloodClient) => void; /** Update subscribed events for this app */ setSubscribedEvents(events: EventType[]): void; } ``` ### GloodAppModule Function type for app module factories. ```typescript theme={null} interface GloodAppModule { /** Create app instance with optional custom configuration */ (): GloodApp; } ``` **Usage:** ```typescript theme={null} // App module functions return GloodAppModule const recommendationsModule: GloodAppModule = recommendations(); ``` ## React Component Types ### GloodProviderProps Props for the GloodProvider React component. ```typescript theme={null} interface GloodProviderProps { /** Glood client instance */ client: GloodClient; /** Child components to wrap */ children: React.ReactNode; /** Route loader data β€” used to seed the session/init on first render */ loaderData: any; } ``` **Usage:** ```typescript theme={null} function App() { return ( ); } ``` ## Analytics Event Data Types ### PageViewData Data structure for page view events. ```typescript theme={null} interface PageViewData { url: string; title?: string; referrer?: string; timestamp: number; } ``` ### ProductViewData Data structure for product view events. ```typescript theme={null} interface ProductViewData { productId: string; productHandle: string; productTitle: string; productPrice: number; productVendor?: string; productType?: string; currency: string; timestamp: number; } ``` ### SearchData Data structure for search events. ```typescript theme={null} interface SearchData { query: string; resultsCount: number; timestamp: number; } ``` ### CollectionViewData Data structure for collection view events. ```typescript theme={null} interface CollectionViewData { collectionId: string; collectionHandle: string; collectionTitle: string; timestamp: number; } ``` ### CartViewData Data structure for cart view events. ```typescript theme={null} interface CartViewData { cartId: string; totalPrice: number; itemCount: number; timestamp: number; } ``` ## Recommendations API Types ### GetSectionsParams Parameters for fetching recommendation sections β€” used by both `useRecommendations()` and `fetchRecommendationSections()`. ```typescript theme={null} interface GetSectionsParams { /** Page type the visitor is on */ pageType: PageType; /** Full URL of the current page (defaults to window.location.href in the browser) */ pageUrl?: string; /** Locale code, e.g. 'en-US' (defaults to navigator.language in the browser) */ locale?: string; /** Numeric Shopify product id (not GID) β€” required for product page recommendations */ productId?: string | number; /** Numeric product ids currently in the cart */ cartProductIds?: Array; /** Specific Glood section ids to fetch (empty = all enabled sections for the page) */ sections?: number[]; /** Glood client id (defaults to the _glood_client_id cookie in the browser) */ clientId?: string; /** Logged-in user id */ userId?: string; /** Shopify customer id */ customerId?: string; /** Market id for multi-market shops */ market?: string; /** Currency code */ currency?: string; /** Cart total value */ cartValue?: string; /** Numeric collection id (for collection pages) */ collection?: number; /** Query string used for experience assignment */ qs?: string; /** Include disabled sections (preview mode) */ preview?: boolean; } ``` **Usage:** ```typescript theme={null} const params: GetSectionsParams = { pageType: 'product_page', productId: '8977367564515', }; ``` ### SectionsResponse Full response from the sections API. ```typescript theme={null} interface SectionsResponse { /** Unique id for this request β€” pass to attribution events */ request_id: string; /** Sections with full product data */ sections: RecommendationSection[]; /** Current product details (product pages), or null */ product: Record | null; /** Shopify storefront access token from the shop config */ token: string | null; /** Shop configuration (currency, money format, integrations, ...) */ config: Record; /** Assigned A/B experience id β€” persisted to localStorage automatically */ experience: string | null; /** Unique id for this visit */ visit_id: string | null; } ``` ### RecommendationSection A recommendation section configured in the Glood dashboard, served with its products. ```typescript theme={null} interface RecommendationSection { /** Glood section id */ id: number; /** Serve id used to attribute glood:section:* events to this render */ section_serve_id: string; /** Page type this section was served for */ page_type: string; /** A/B experience this section belongs to */ experience_id: string | null; /** Layout, e.g. 'horizontal_grid', 'carousel' */ layout: string; /** Placement location configured in the dashboard */ location: string; /** Recommendation type, e.g. 'bestsellers', 'similar_products', 'bought_together' */ type: string; /** Position among sections on the page */ position: number; /** Translated section title */ title: string; /** Extra section settings */ extra: Record; /** Discount configuration for this section */ discount_config: Record | null; /** Whether to show discount labels */ show_discount_label: boolean; /** Title translations */ translations: Record | null; /** Recommended products with full data */ products: SectionProduct[]; /** Pagination cursor (null when not paginated) */ cursor: string | null; /** Whether more products are available */ hasMore: boolean; } ``` ### SectionProduct A recommended product with complete display data. ```typescript theme={null} interface SectionProduct { /** Numeric Shopify product id */ product_id: number; title: string; handle: string; vendor?: string; product_type?: string; /** Comma-separated tag list */ tags?: string; /** Minimum price across variants */ price: number | null; /** Compare-at price (null when not on sale) */ compare_at_price: number | null; /** Featured image */ image?: { url?: string } | null; /** Product options (Size, Color, ...) */ options: SectionProductOption[]; /** All variants */ variants: SectionProductVariant[]; metafields?: Array<{ namespace: string; key: string; value: string }>; } ``` ### SectionProductVariant ```typescript theme={null} interface SectionProductVariant { /** Numeric Shopify variant id */ variant_id: number; title: string; display_name?: string; position?: number; sku?: string; /** Selected option values, e.g. [{ name: 'Size', value: 'S' }] */ selected_options: Array<{ name: string; value: string }>; price: number | string | null; compare_at_price: number | string | null; image?: { url?: string } | null; } ``` ### SectionProductOption ```typescript theme={null} interface SectionProductOption { id: number; name: string; values: string[]; position: number; } ``` ### SectionTrack Attribution payload linking a `glood:section:*` event to a specific section render. ```typescript theme={null} interface SectionTrack { /** Glood section id (as a string) */ section?: string; /** section_serve_id from the sections response */ sectionServeId?: string; /** request_id from the sections response */ requestId?: string; /** Page type where the interaction happened */ page?: string; /** Context product (e.g. the PDP product the section rendered on) */ parent?: { productId?: string; variantId?: string }; /** Products involved in the interaction */ products?: SectionTrackProduct[]; } interface SectionTrackProduct { productId: string; variantId?: string; quantity?: number; } ``` ### FetchSectionsOptions Options for `fetchRecommendationSections()`. ```typescript theme={null} interface FetchSectionsOptions { /** Glood storefront token (same value as GloodConfig.apiKey) */ apiKey: string; /** Shop domain, e.g. 'store-name.myshopify.com' */ myShopifyDomain: string; /** Recommendations endpoint override (defaults to https://storefront.glood.ai) */ endpoint?: string; /** Log request/response details */ debug?: boolean; } ``` ### GloodApiError Error thrown when the sections API responds with a non-2xx status. ```typescript theme={null} class GloodApiError extends Error { /** HTTP status code */ readonly status: number; /** Parsed JSON error body */ readonly body: unknown; } ``` **Usage:** ```typescript theme={null} import { GloodApiError } from '@glood/hydrogen'; if (error instanceof GloodApiError) { console.error(error.status, error.body); } ``` ## Headless API Types The headless API is version-aware. A v3 client uses the full suite (`/init`, `/sections`, `/events`, and the recommendations variants); a v2 client is legacy and only supports recommendations, authenticating by shop header alone (no bearer token). ### ApiVersion Headless API version selector. Defaults to `3`. ```typescript theme={null} type ApiVersion = 2 | 3; ``` ### HeadlessRequestOptions Options passed as the first argument to every standalone headless function (server loaders / advanced usage). ```typescript theme={null} interface HeadlessRequestOptions { /** Glood API key for authentication */ apiKey: string; /** Shop domain, e.g. 'store-name.myshopify.com' */ myShopifyDomain: string; /** Endpoint override (defaults to https://storefront.glood.ai) */ endpoint?: string; /** Headless API version to use (2 or 3). Defaults to 3. */ version?: ApiVersion; /** Log request/response details */ debug?: boolean; } ``` ### InitParams Parameters for the v3 session init call. ```typescript theme={null} interface InitParams { userId?: string; clientId?: string; customerId?: string; pageType?: PageType; pageUrl?: string; } ``` ### InitResponse Response from `POST /api/storefront/v3/headless/init`. Exposed via the `useGloodInit()` hook. Always `null` for v2 clients (init is a v3-only endpoint). ```typescript theme={null} interface InitResponse { /** Per-visit id (persisted to the _glood_visit_id session cookie) */ visit_id: string; /** Visitor id (persisted to the _glood_user_id cookie, replayed on return) */ user_id: string; client_id: string | null; customer_id: string | null; /** Visitor history */ visitor: { browsed_products: any[]; cart_products: any[]; purchased_products: any[]; }; /** Shop configuration (currency, money_format, storefront_graphql_version, integrations, analytics_enabled, ...) */ config: Record; /** Shopify storefront access token */ token: string | null; } ``` ### HeadlessEventChannel Channel a headless event originates from. Defaults to `'hydrogen'`. ```typescript theme={null} type HeadlessEventChannel = 'mobile' | 'headless' | 'hydrogen'; ``` ### HeadlessEventParams Parameters for sending an analytics/attribution event to the versioned events API. On a v3 client this posts to `POST /api/storefront/v3/headless/events`. ```typescript theme={null} interface HeadlessEventParams { event: { id: string; name: string; type: 'standard' | 'custom'; /** ISO 8601 timestamp; must be within Β±2 days of now (server rule) */ timestamp: string; data?: Record; customData?: { track: SectionTrack }; }; /** Defaults to 'hydrogen' */ channel?: HeadlessEventChannel; /** Defaults to the session cookie in the browser (server requires it) */ sessionId?: string; /** At least one of clientId / userId is required by the server */ clientId?: string; userId?: string; customerId?: string; experience?: string | null; pageType?: string; pageUrl?: string; [key: string]: any; } ``` ### HeadlessEventResponse Response from the events API. ```typescript theme={null} interface HeadlessEventResponse { ok: boolean; [key: string]: any; } ``` ### RecommendationView Shape of items returned by a recommendation query. ```typescript theme={null} type RecommendationView = 'product_details' | 'product_ids'; ``` ### RecommendedProduct A product returned in the `product_details` view β€” same shape as [`SectionProduct`](#sectionproduct). ```typescript theme={null} type RecommendedProduct = SectionProduct; ``` ### RecommendedProductRef A product returned in the `product_ids` view. ```typescript theme={null} interface RecommendedProductRef { product_id: number; } ``` ### RecommendedItem A recommended item β€” either a full product or a product id reference, depending on the query's `view`. ```typescript theme={null} type RecommendedItem = RecommendedProduct | RecommendedProductRef; ``` ### RecommendationQuery A single query in a multi-query v3 recommendations request. ```typescript theme={null} interface RecommendationQuery { /** Caller-chosen id; results are keyed by it in the response */ id: string; /** * One of the RecommendationType values: 'similar_products' | 'bought_together' | * 'recently_viewed' | 'cross_sell' | 'bestsellers' | 'trending' | 'personalized' | * 'recent_launch' | 'collections' | 'purchases' | 'promoted' | 'custom' | * 'email_recommendations'. See the Signatures page β†’ Enums for support notes. */ recommendationType: string; /** Anchor product ids (v3 accepts up to 10 per query) */ productIds: Array; maxRecommendations?: number; creationType?: string; view: RecommendationView; } ``` ### RecommendationsParams Parameters for the v3 recommendations endpoint (`POST /api/storefront/v3/headless/recommendations`). ```typescript theme={null} interface RecommendationsParams { queries: RecommendationQuery[]; clientId?: string; userId?: string; customerId?: string; } ``` ### RecommendationsResponse Response from the v3 recommendations endpoint. Results are keyed by each query's `id`. ```typescript theme={null} interface RecommendationsResponse { status: string; serve_id: string; data: Record< string, { recommendation_serve_id: string; recommendation_type: string; max_recommendations?: number; creation_type?: string; product_ids: number[]; view: RecommendationView; recommendations: RecommendedItem[]; } >; } ``` ### V2RecommendationsParams Parameters for the legacy v2 recommendations endpoint (`POST /api/storefront/v2/headless/recommendations`, `similar_products` only). ```typescript theme={null} interface V2RecommendationsParams { queries: RecommendationQuery[]; } ``` ### V2RecommendationsResponse Response from the v2 recommendations endpoint. Results are keyed by each query's `id`. ```typescript theme={null} interface V2RecommendationsResponse { status: string; data: Record; } ``` ### AutomaticRecommendationsParams Parameters for the v3 automatic recommendations endpoint (`POST /api/storefront/v3/headless/recommendations/automatic`) β€” single anchor, paginated. ```typescript theme={null} interface AutomaticRecommendationsParams { productIds: number[]; view: RecommendationView; /** Only 'similar_products' is supported by this endpoint */ recommendationType?: 'similar_products'; maxRecommendations?: number; filter?: Record; pagination?: { cursor?: string | null; limit?: number }; } ``` ### AutomaticRecommendationsResponse ```typescript theme={null} interface AutomaticRecommendationsResponse { status: string; serve_id: string; pagination: { cursor: string | null; hasMore?: boolean }; products: RecommendedItem[]; } ``` ### TopStrategy Strategy for the anchorless top recommendations endpoint. **Values are uppercase** (they map directly to the backend enum). ```typescript theme={null} type TopStrategy = 'BESTSELLERS' | 'NEW_ARRIVALS'; ``` ### TopFacet Facet dimensions returned by the top recommendations endpoint. ```typescript theme={null} type TopFacet = 'vendor' | 'product_type' | 'tag' | 'price'; ``` ### TopRecommendationsParams Parameters for the v3 top recommendations endpoint (`POST /api/storefront/v3/headless/recommendations/top`) β€” anchorless, faceted. ```typescript theme={null} interface TopRecommendationsParams { strategy: TopStrategy; view: RecommendationView; strategyOptions?: { salesTimePeriod?: 7 | 15 | 30; bestsellerMetric?: string; }; /** Full-text search over the catalog */ query?: string; filter?: Record; facets?: TopFacet[]; pagination?: { cursor?: string | null; limit?: number }; } ``` ### TopRecommendationsResponse ```typescript theme={null} interface TopRecommendationsResponse { status: string; serve_id: string; strategy: string; pagination: { cursor: string | null; hasMore: boolean; total: number; totalRelation: string; limit: number; }; products: RecommendedItem[]; facets?: Record; } ``` ## Search API Types Types for the **Search v1** suite. Params are camelCase (mapped to snake\_case on the wire); responses are snake\_case exactly as returned by the backend. ### SearchView / SearchSort ```typescript theme={null} type SearchView = 'product_details' | 'product_ids'; type SearchSort = | 'relevance' | 'title_asc' | 'title_desc' | 'price_asc' | 'price_desc' | 'best_selling' | 'oldest' | 'newest'; ``` ### SearchProduct Self-contained product object (from `getHeadlessProductResponse`). ```typescript theme={null} interface SearchMedia { id?: string; url?: string; width?: number | null; height?: number | null; alt_text?: string | null; [key: string]: any; } interface SearchProductOption { id: number; name: string; position: number; values: string[]; } interface SearchProductVariant { variant_id: number; title: string; display_name?: string; sku?: string | null; position?: number; price: number | null; compare_at_price: number | null; available_for_sale: boolean; is_in_stock: boolean; sellable_online_quantity?: number | null; selected_options: Array<{ name: string; value: string }>; image?: SearchMedia | null; } interface SearchProduct { product_id: number; title: string; handle: string; product_type?: string; vendor?: string; tags?: string[]; price: number | null; compare_at_price: number | null; display_price?: number | null; display_compare_at_price?: number | null; display_currency?: string; original_currency?: string; currency_rate?: number; available_for_sale?: boolean; is_in_stock?: boolean; total_inventory?: number | null; image?: SearchMedia | null; featured_media?: SearchMedia | null; media?: SearchMedia[]; options?: SearchProductOption[]; variants?: SearchProductVariant[]; metafields?: Array<{ namespace: string; key: string; value: string }>; } /** Returned when view: 'product_ids' */ interface SearchProductRef { product_id: number; } type SearchItem = SearchProduct | SearchProductRef; ``` ### SearchPagination ```typescript theme={null} interface SearchPagination { total: number; page: number; limit: number; total_pages: number; has_next_page: boolean; has_prev_page: boolean; next_page?: number | null; prev_page?: number | null; } ``` ### SearchInitParams / SearchInitResponse Session bootstrap. `GloodProvider` runs `init` once on mount; `useSearchInit()` exposes the response and `useSearchInitReady()` the settled flag that `useSearch`/`useInstantSearch` gate on. ```typescript theme={null} interface SearchInitParams { pageType?: string; pageUrl?: string; locale?: string; market?: number; visitorId?: string; // defaults from cookie in the browser clientId?: string; // defaults from cookie in the browser customerId?: string; } interface SearchInitResponse { visit_id: string; // fresh session id; echo as session_id on events visitor_id: string | null; client_id: string | null; customer_id: string | null; visitor: { browsed_products: number[]; cart_products: number[]; purchased_products: number[]; }; config: Record; // lean feature flags (no filters/tree; see REST reference) token: string | null; // Shopify storefront access token metadata: { region?: string; locale?: string; market?: number | null; [k: string]: any }; } ``` ### SearchConfigParams / SearchConfigResponse ```typescript theme={null} interface SearchConfigParams { locale?: string; market?: number; theme?: number; // parity only; no templates rendered targetPage?: string; targetId?: number; visitorId?: string; skipCache?: boolean; } interface SearchConfigResponse { config: Record; // feature flags (see REST reference) filters: SearchFacet[]; filter_tree: { id: number; target_page: string; target_ids: number[]; is_default: boolean; title: string; settings: Record; data: any[]; translations: Record; } | null; shop: { currency_format?: string; primary_locale?: string; currency?: string; [k: string]: any }; analytics: { enabled: boolean; tracking_id?: string | null; [k: string]: any }; translations: Record; token: string | null; metadata: { region?: string; locale?: string; market?: number | null; [k: string]: any }; } ``` ### InstantSearchParams / InstantSearchResponse ```typescript theme={null} type InstantSearchObject = | 'product' | 'collection' | 'page' | 'article' | 'query_suggestion' | 'autocorrect'; interface InstantSearchParams { query: string; // required (may be "") locale?: string; market?: number; limit?: number; objects?: InstantSearchObject[]; view?: SearchView; visitorId?: string; clientId?: string; customerId?: string; trending?: { type?: 'searches' | 'products' | 'all'; period?: '1h' | '24h' | '7d' | '30d'; category?: string; limit?: number; }; } interface SearchSuggestion { text: string; type: string; object_count?: number; search_count?: number; } interface SearchAutocorrect { original_query: string; corrected_query: string; confidence?: number; corrections?: any[]; alternatives?: any[]; } interface InstantSearchCollection { collection_id: number; title: string; handle: string; image?: SearchMedia | null; } interface InstantSearchPage { page_id: number; title: string; handle: string; } interface InstantSearchArticle { article_id: number; title: string; handle: string; blog_handle?: string; author?: string; summary?: string; image?: SearchMedia | null; published_at?: string; tags?: string[]; } interface InstantSearchResponse { query: string; corrected_query: string | null; autocorrect: SearchAutocorrect | null; suggestions: SearchSuggestion[]; products: { results: SearchItem[]; total: number }; collections: { results: InstantSearchCollection[]; total: number }; pages: { results: InstantSearchPage[]; total: number }; articles: { results: InstantSearchArticle[]; total: number }; trending: { searches: Array<{ term: string; translated_term?: string; search_count: number }>; products: SearchItem[]; } | null; metadata: { query_time?: number; locale?: string; market?: number | null; min_query_length?: number; [k: string]: any }; } ``` ### FiltersParams / FiltersResponse ```typescript theme={null} interface SearchFacetValue { value: string; label: string; count: number | null; position?: number; hex?: string | null; image?: SearchMedia | null; order?: number | null; } interface SearchFacet { id: number; key: string; title: string; type: string; attribute_type: string; position?: number; expanded?: boolean; visible?: boolean; operator?: string; settings?: Record; min?: number | null; max?: number | null; step?: number | null; unit?: string | null; suffix?: string | null; values?: SearchFacetValue[]; } interface FiltersParams { collection?: string | number; tree?: number; targetPage?: string; targetId?: number; locale?: string; market?: number; includeValues?: boolean; // default true includeDisabled?: boolean; // default false } interface FiltersResponse { facets: SearchFacet[]; tree: { id: number; target_page: string; target_ids: number[]; is_default: boolean; title: string; settings: Record; } | null; metadata: { locale?: string; market?: number | null; region?: string; total_facets?: number; [k: string]: any }; } ``` ### FilterAggregationsParams / FilterAggregationsResponse ```typescript theme={null} interface AppliedFilter { key: string; value: string[] | string; } interface FilterAggregationsParams { collection?: string | number; tree?: number; query?: string; appliedFilters?: AppliedFilter[]; facets?: Array<{ key: string }>; locale?: string; market?: number; options?: { includeZeroCounts?: boolean; includeDisabled?: boolean; sortBy?: string; limit?: number }; visitorId?: string; } interface FilterAggregationBucket { value: string; label?: string; count: number; enabled?: boolean; is_others?: boolean; selected?: boolean; } interface FilterAggregation { type: string; data_type: string; buckets: FilterAggregationBucket[]; has_more?: boolean; other_count?: number; stats?: { min: number; max: number; avg: number; sum: number; count: number }; } interface FilterAggregationsResponse { aggregations: Record; facets: Array<{ id: number; key: string; title: string; data_type: string; attribute_type: string }>; tree: { id: number; target_page: string; target_id?: number | null; is_default: boolean } | null; metadata: { total_products?: number; query_time?: number; region?: string; [k: string]: any }; } ``` ### SearchParams / SearchResponse ```typescript theme={null} interface SearchAppliedFacet { key: string; operator?: 'or' | 'and'; value: string[] | string; } interface SearchParams { query?: string; targetPage?: string; targetId?: number; locale?: string; market?: number; facets?: SearchAppliedFacet[]; sort?: SearchSort; view?: SearchView; pagination?: { page?: number; limit?: number }; options?: { includeAggregations?: boolean; includeHighlights?: boolean; includeFacets?: boolean; boostInStock?: boolean; personalize?: boolean; }; visitorId?: string; clientId?: string; customerId?: string; } interface SearchResponseFacet { key: string; type: string; aggregation: { buckets: FilterAggregationBucket[] }; } interface SearchResponse { status: string; request_id: string; products: SearchItem[]; pagination: SearchPagination; facets?: SearchResponseFacet[]; metadata: { query_time?: number; total_time?: number; region?: string; search_type?: string; [k: string]: any }; } ``` ### ImageSearchParams / ImageSearchResponse ```typescript theme={null} interface ImageSearchParams { image?: string; // base64 or data: URL ┐ exactly one imageUrl?: string; // http(s) or data: URL β”˜ required facets?: Record | SearchAppliedFacet[]; locale?: string; market?: number; view?: SearchView; pagination?: { page?: number; limit?: number }; visitorId?: string; clientId?: string; customerId?: string; } interface ImageSearchResponse { status: string; products: SearchItem[]; pagination: SearchPagination; search_metadata: { processing_time?: number; search_type?: string; image_analysis?: Record; image_caption?: string; search_text?: string; has_embedding?: boolean; errors?: any[]; dominant_colors?: string[]; [key: string]: any; }; } ``` ### SearchTrack Attribution payload for `glood:search:*` custom events (snake\_case wire shape). ```typescript theme={null} interface SearchTrackProduct { product_id: string | number; variant_id?: string | number; quantity?: number; } interface SearchTrackFilter { key: string; value: string | string[]; } interface SearchTrack { request_id?: string; search_term?: string; search_type?: string; // 'text' | 'image' products?: SearchTrackProduct[]; filters?: SearchTrackFilter[]; source?: string; page_type?: string; } /** SEARCH_EVENT_NAMES member */ type GloodSearchEventName = | 'glood:instant_search_triggered' | 'glood:search_result_rendered' | 'glood:search_result_clicked' | 'glood:search:add_to_cart' | 'glood:search_filter_updated'; ``` ## Pixel System Types ### PixelEvent Structure for pixel events in the transmission queue. ```typescript theme={null} interface PixelEvent { endpoint: string; data: Record; /** * Request headers. When omitted, the queue falls back to * { 'Content-Type': 'application/json', 'x-shop-myshopify-domain': shopDomain }. */ headers?: Record; /** Legacy shortcut used to build the x-shop-myshopify-domain header when `headers` is not given */ shopDomain?: string; } ``` ### PixelPayload Complete pixel payload sent to Glood endpoints. ```typescript theme={null} interface PixelPayload { events: Record[]; apiKey: string; shopDomain: string; timestamp: number; } ``` ## Constant Types ### AppName Union type for available app names. ```typescript theme={null} type AppName = 'recommendations'; ``` **Usage:** ```typescript theme={null} const appName: AppName = 'recommendations'; // βœ… Valid const invalidName: AppName = 'invalid'; // ❌ TypeScript error ``` ### EventType Union type for all supported analytics events. ```typescript theme={null} type EventType = | 'page_viewed' | 'product_viewed' | 'collection_viewed' | 'cart_viewed' | 'search_viewed' | 'search_submitted' | 'custom_promotion_viewed' | 'product_added_to_cart' | 'product_removed_from_cart'; ``` **Usage:** ```typescript theme={null} const event: EventType = 'product_viewed'; // βœ… Valid const invalidEvent: EventType = 'invalid_event'; // ❌ TypeScript error ``` ### ConsentType Union type for customer privacy consent types. ```typescript theme={null} type ConsentType = | 'analytics' | 'marketing' | 'preferences' | 'sale_of_data'; ``` **Usage:** ```typescript theme={null} const consent: ConsentType[] = ['analytics', 'marketing']; // βœ… Valid const invalidConsent: ConsentType[] = ['invalid']; // ❌ TypeScript error ``` ### PageType Union type of page types accepted by the sections API. ```typescript theme={null} type PageType = | 'product_page' | 'collection' | 'home' | 'cart' | 'order_confirm' | 'other' | 'blog' | 'ajax_cart' | '404' | 'checkout' | 'returns'; ``` The `PAGE_TYPES` constant exports the same list as a runtime array. ### GloodSectionEventName Union type of the custom attribution event names. ```typescript theme={null} type GloodSectionEventName = | 'glood:section:render' | 'glood:section:view' | 'glood:section:click' | 'glood:section:add_to_cart'; ``` The `SECTION_EVENT_NAMES` constant exports the same list as a runtime array. ## Type Imports Import specific types as needed: ```typescript theme={null} // Import all types import type { GloodConfig, GloodClient, GloodApp, AppName, EventType, ConsentType, PixelConfig, } from '@glood/hydrogen'; // Import specific app config types import type { RecommendationsAppConfig, } from '@glood/hydrogen'; // Import event data types import type { PageViewData, ProductViewData, SearchData, CartViewData, } from '@glood/hydrogen'; // Import React component types import type { GloodProviderProps, } from '@glood/hydrogen'; // Import recommendations API types import type { GetSectionsParams, SectionsResponse, RecommendationSection, SectionProduct, SectionProductVariant, SectionProductOption, SectionTrack, SectionTrackProduct, FetchSectionsOptions, UseRecommendationsOptions, UseRecommendationsResult, PageType, GloodSectionEventName, } from '@glood/hydrogen'; ``` ## Best Practices ### 1. Use Type-Only Imports Import types with `import type` so they're erased at build time: ```typescript theme={null} // βœ… Good - Type-only import import type { GloodConfig } from '@glood/hydrogen'; // ❌ Avoid - Runtime import for types import { GloodConfig } from '@glood/hydrogen'; ``` ### 2. Use Const Assertions Use const assertions for consent literals: ```typescript theme={null} // βœ… Good - Const assertion preserves literal types const consent = ['analytics', 'marketing'] as const; ``` ## See Also * [Client API](/for-developers/glood-hydrogen-sdk/api-reference/client) - Using types with createGlood() * [Components](/for-developers/glood-hydrogen-sdk/api-reference/components) - React component types * [App Modules](/for-developers/glood-hydrogen-sdk/api-reference/app-modules) - App configuration types * [Configuration Guide](/for-developers/glood-hydrogen-sdk/configuration) - Type-safe configuration patterns # Utilities Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/api-reference/utilities Utility functions for consent management, session bootstrap, the pixel queue, and constants # Utilities The SDK exports a small set of utilities for advanced usage: consent management, session bootstrap, the pixel queue, and shared constants. ## Consent Management ### checkConsent() Checks if all required consent types have been granted by the customer. ```typescript theme={null} function checkConsent( requiredConsents: ConsentType[], canTrack: any, analytics: any ): boolean ``` **Parameters:** * `requiredConsents` - Array of consent types that must be granted * `canTrack` - Hydrogen's canTrack function from analytics * `analytics` - Hydrogen's analytics instance **Returns:** `true` if all required consents are granted, `false` otherwise **Usage:** ```typescript theme={null} import { checkConsent, CONSENT_TYPES } from '@glood/hydrogen'; // Check if analytics consent is granted const canSendAnalytics = checkConsent( [CONSENT_TYPES.ANALYTICS], canTrack, analytics ); // Check multiple consent types const canSendMarketing = checkConsent( [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING], canTrack, analytics ); if (canSendAnalytics) { // Send analytics pixel } ``` **Implementation Details:** ```typescript theme={null} export function checkConsent( requiredConsents: ConsentType[], canTrack: any, analytics: any ): boolean { if (!requiredConsents || requiredConsents.length === 0) { return true; // No consent required } return requiredConsents.every(consentType => { switch (consentType) { case 'analytics': return analytics.customerPrivacy?.analyticsProcessingAllowed(); case 'marketing': return analytics.customerPrivacy?.marketingAllowed(); case 'preferences': return analytics.customerPrivacy?.preferencesProcessingAllowed(); case 'sale_of_data': return analytics.customerPrivacy?.saleOfDataAllowed(); default: return false; } }); } ``` ## Session Bootstrap ### runHeadlessInit() Bootstraps a session for a Glood client. Called automatically by `GloodProvider` on mount, but exposed for advanced use (e.g. running init yourself in a route loader). ```typescript theme={null} function runHeadlessInit(client: GloodClient): Promise ``` **Parameters:** * `client` - The `GloodClient` created by `createGlood(...).use(recommendations())` **Returns:** The `/v3/headless/init` response (`InitResponse`), or `null` for **v2** clients (init is a v3-only endpoint, so it is a no-op there). For a **v3** client it calls `POST /api/storefront/v3/headless/init`, which: * replays the persisted visitor id and returns/echoes `user_id` (persisted to the `_glood_user_id` cookie so returning visitors are recognized), * creates a per-visit `visit_id` (`_glood_visit_id`, a session cookie), * returns `visitor` history (browsed / cart / purchased), shop `config`, and the storefront `token`. **Usage:** ```typescript theme={null} import { runHeadlessInit } from '@glood/hydrogen'; const init = await runHeadlessInit(glood); if (init) { console.log('Visit id:', init.visit_id); console.log('User id:', init.user_id); console.log('Browsed products:', init.visitor.browsed_products); } // init is null for a version: 2 client ``` It also saves the response on the client, so after it runs you can read it back synchronously with `client.getInitData()` (and reactively with `useGloodInit()`) β€” no need to hold the return value yourself. > [!NOTE] > > Inside components, prefer the `useGloodInit()` hook, which returns the same `InitResponse` (or `null` until it resolves / for v2 clients) without re-running init. `GloodProvider` already calls `runHeadlessInit` for you on mount β€” call it directly only for manual/SSR bootstrap. ## Constants ### DEFAULT\_ENDPOINTS Default API and pixel endpoints for the recommendations app. ```typescript theme={null} const DEFAULT_ENDPOINTS = { recommendations: { main: 'https://storefront.glood.ai', pixel: 'https://events.glood.ai/api/storefront/event', }, } as const; ``` > [!NOTE] > > `recommendations.pixel` is **legacy** and no longer used to route events. > Events are sent off the `main` endpoint by the client's `version` > (v3 β†’ `/api/storefront/v3/headless/events`). **Usage:** ```typescript theme={null} import { DEFAULT_ENDPOINTS } from '@glood/hydrogen'; // Get recommendations endpoints const recEndpoint = DEFAULT_ENDPOINTS.recommendations.main; const recPixel = DEFAULT_ENDPOINTS.recommendations.pixel; // Use in custom configuration const customConfig = { endpoint: DEFAULT_ENDPOINTS.recommendations.main, pixel: { enabled: true, endpoint: DEFAULT_ENDPOINTS.recommendations.pixel, consent: ['analytics', 'marketing'], }, }; ``` ### DEFAULT\_PIXEL\_CONFIG Default pixel configuration settings. ```typescript theme={null} const DEFAULT_PIXEL_CONFIG = { enabled: true, } as const; ``` ### CONSENT\_TYPES Constants for all consent types. ```typescript theme={null} const CONSENT_TYPES = { ANALYTICS: 'analytics', MARKETING: 'marketing', PREFERENCES: 'preferences', SALE_OF_DATA: 'sale_of_data', } as const; ``` **Usage:** ```typescript theme={null} import { CONSENT_TYPES } from '@glood/hydrogen'; // Use in configuration const pixelConfig = { enabled: true, endpoint: 'https://storefront.glood.ai', consent: [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING], }; // Type-safe consent checking const requiredConsents = [ CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.PREFERENCES, ]; ``` ### DEFAULT\_PIXEL\_CONSENT Default consent requirements for the recommendations app. ```typescript theme={null} const DEFAULT_PIXEL_CONSENT = { recommendations: [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING], } as const; ``` **Usage:** ```typescript theme={null} import { DEFAULT_PIXEL_CONSENT } from '@glood/hydrogen'; // Get default consent for the recommendations app const recConsent = DEFAULT_PIXEL_CONSENT.recommendations; // ['analytics', 'marketing'] // Use in custom configuration const customConfig = { endpoint: 'https://custom-storefront.glood.ai', pixel: { enabled: true, endpoint: 'https://custom-storefront.glood.ai', consent: DEFAULT_PIXEL_CONSENT.recommendations, // ['analytics', 'marketing'] }, }; ``` ### API\_VERSIONS / DEFAULT\_API\_VERSION Supported headless API versions and the default used when `version` is omitted from `createGlood`. ```typescript theme={null} const API_VERSIONS = [2, 3] as const; const DEFAULT_API_VERSION = 3 as const; ``` **Usage:** ```typescript theme={null} import { API_VERSIONS, DEFAULT_API_VERSION } from '@glood/hydrogen'; // Validate a version before passing it to createGlood function isValidVersion(v: number): boolean { return API_VERSIONS.includes(v as any); } console.log('Default version:', DEFAULT_API_VERSION); // 3 ``` ### PAGE\_TYPES Page types accepted by the sections API (`getSections` / `useRecommendations`). ```typescript theme={null} const PAGE_TYPES = [ 'product_page', 'collection', 'home', 'cart', 'order_confirm', 'other', 'blog', 'ajax_cart', '404', 'checkout', 'returns', ] as const; ``` ## Pixel Queue ### getPixelQueue() Gets the global pixel queue instance for sending events. ```typescript theme={null} function getPixelQueue(debug?: boolean): PixelQueue ``` **Parameters:** * `debug` - Enable debug logging for pixel transmission **Returns:** PixelQueue instance **Usage:** ```typescript theme={null} import { getPixelQueue } from '@glood/hydrogen'; const pixelQueue = getPixelQueue(true); // Enable debug mode // Send a pixel event pixelQueue.add({ endpoint: 'https://storefront.glood.ai/api/storefront/v3/headless/events', data: { event: { id: 'evt_123', name: 'product_viewed', // ... event data } } }); ``` ### resetPixelQueue() Resets the pixel queue (mainly for testing). ```typescript theme={null} function resetPixelQueue(): void ``` **Usage:** ```typescript theme={null} import { resetPixelQueue } from '@glood/hydrogen'; // Reset queue (typically used in tests) resetPixelQueue(); ``` ## Advanced Usage Examples ### Consent Validation Report exactly which required consents are missing, built on the exported `checkConsent`: ```typescript theme={null} import { checkConsent, CONSENT_TYPES } from '@glood/hydrogen'; function validateConsent( requiredConsents: ConsentType[], canTrack: any, analytics: any ): { valid: boolean; missing: ConsentType[] } { const missing: ConsentType[] = []; for (const consentType of requiredConsents) { if (!checkConsent([consentType], canTrack, analytics)) { missing.push(consentType); } } return { valid: missing.length === 0, missing, }; } // Usage const validation = validateConsent( [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING], canTrack, analytics ); if (!validation.valid) { console.log('Missing consents:', validation.missing); } ``` ## See Also * [Event System](/for-developers/glood-hydrogen-sdk/api-reference/event-system) - How utilities are used in event processing * [Types Reference](/for-developers/glood-hydrogen-sdk/api-reference/types) - TypeScript types for utilities * [App Modules](/for-developers/glood-hydrogen-sdk/api-reference/app-modules) - How apps use these utilities * [Components](/for-developers/glood-hydrogen-sdk/api-reference/components) - React components using utilities # Configuration Guide Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/configuration Comprehensive guide to configuring the Glood Hydrogen SDK for different use cases and environments # Configuration Guide The Glood Hydrogen SDK supports both basic and advanced configuration patterns to fit different use cases and environments. ## Configuration Overview The SDK follows a **zero-configuration** principle with sensible defaults, while providing **full customization** options for advanced use cases. ### Configuration Hierarchy 1. **Basic Configuration** - Only API key and domain required 2. **Client-Level App Config** - Override recommendations settings in the `apps.recommendations` block of `createGlood(...)` 3. **Environment Variables** - External configuration management ## API Version `createGlood` accepts an optional numeric `version` that selects the headless API version. It defaults to `3`. * **`3` (default)** - The full headless suite: session init, sections, events, and all recommendation variants. Authenticates with an `Authorization: Bearer ` header plus the shop header. * **`2` (legacy)** - Recommendations only. Authenticates by shop header alone (no bearer token) and does not support session init or the events suite. ```typescript theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // 2 | 3 β€” 3 is the default }); ``` > [!NOTE] > > `createGlood` throws if `version` is anything other than `2` or `3`. Leave it unset (or `3`) unless you specifically need the legacy v2 behavior. ## Basic Configuration ### Minimal Setup The simplest configuration requires only your API key and Shopify domain: ```typescript theme={null} import { createGlood, recommendations } from '@glood/hydrogen'; const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // 2 | 3 β€” 3 is the default }) .use(recommendations()); ``` **What this provides:** * βœ… Recommendations enabled with default endpoint * βœ… Pixel tracking enabled * βœ… Default consent requirements * βœ… Automatic event subscriptions * βœ… Production-ready configuration ### Basic with Debug Mode Enable debug logging for development: ```typescript theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // 2 | 3 β€” 3 is the default debug: process.env.NODE_ENV === 'development', }) .use(recommendations()); ``` ## Advanced Configuration ### Client-Level App Configuration Override the recommendations app settings in the main client configuration: ```typescript theme={null} import { createGlood, CONSENT_TYPES } from '@glood/hydrogen'; const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // 2 | 3 β€” 3 is the default apps: { recommendations: { endpoint: 'https://custom-storefront.glood.ai', pixel: { enabled: true, consent: [CONSENT_TYPES.ANALYTICS], // Only analytics }, subscribedEvents: ['product_viewed', 'cart_viewed'], // Limited events }, }, debug: true, settings: { customKey: 'customValue', trackingVersion: '2.0', }, }) .use(recommendations()); ``` > [!NOTE] > > The `recommendations()` module factory takes no arguments. Configure the app entirely through the `apps.recommendations` block of `createGlood(...)`, then register it with `.use(recommendations())`. ## Search App Configuration The search app is a **v1** headless API on its own host (`https://search.glood.ai`), independent of the client's global `version`. Register it with `.use(search())` and configure it through the `apps.search` block: ```typescript theme={null} import { createGlood, search, CONSENT_TYPES } from '@glood/hydrogen'; const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', apps: { search: { endpoint: 'https://search.glood.ai', // search API host (default) controlEndpoint: 'https://search.glood.ai', // non-edge host for image search + events (default) pixel: { enabled: true, endpoint: 'https://search.glood.ai/api/storefront/event', // search pixel (default) consent: [CONSENT_TYPES.ANALYTICS], // search default: analytics only }, }, }, }) .use(search()); ``` **Defaults for the search app:** | Setting | Default | | - | - | | `apiVersion` | `1` (pinned β€” always v1, even on a v2/v3 client) | | `endpoint` | `https://search.glood.ai` | | `controlEndpoint` | `https://search.glood.ai` (falls back to the non-edge host) | | `pixel.endpoint` | `https://search.glood.ai/api/storefront/event` | | `pixel.consent` | `['analytics']` | | Subscribed events | all standard Shopify events | > [!NOTE] > > Search's default consent is **analytics only** (unlike recommendations, which also requires > marketing). Search's `apiVersion` is fixed at `1` and is not affected by the client's > `version` β€” so you can run recommendations (v3) and search (v1) on the same client. ### Edge vs. non-edge routing (`controlEndpoint`) The search app talks to two hosts. `endpoint` is the **main** host β€” used for `init`, `config`, `instantSearch`, `filters`, filter aggregations, and `search`. `controlEndpoint` is the **non-edge (control-plane)** host β€” used only for **image search** and **event ingestion**, which cannot be served by a regional edge (image search needs the vision/embedding pipeline; events are ingested centrally). `controlEndpoint` defaults to the non-edge host, so if you point `endpoint` at a regional edge, image search and events automatically stay on the control plane β€” you only override one field: ```typescript theme={null} const glood = createGlood({ apiKey, myShopifyDomain }) .use(search()); // Serve the fast path from an edge, keep image search + events on the control plane: createGlood({ apiKey, myShopifyDomain, apps: { search: { endpoint: 'https://edge-eu.glood.ai', // init/config/instant/filters/search β†’ edge // controlEndpoint omitted β†’ image search + events stay on the default non-edge host }, }, }).use(search()); ``` | Call | Routed to | | - | - | | `init`, `config`, `instantSearch`, `filters`, filter aggregations, `search` | `endpoint` | | `imageSearch` | `controlEndpoint` | | events (standard + `glood:*` attribution) | `controlEndpoint` | > [!NOTE] > > Set `controlEndpoint` explicitly only when your control plane isn't the default host (e.g. a local > or self-hosted deployment). In production, leave it unset and it resolves to the non-edge host. ### Narrowing search events The `search()` factory optionally narrows which Shopify standard events are forwarded to the search backend (default: all events): ```typescript theme={null} const glood = createGlood({ apiKey, myShopifyDomain }) .use(search({ events: ['search_submitted', 'product_added_to_cart'] })); ``` ## Where Events Are Sent Analytics and attribution events are routed by the app's API version off the app's events endpoint β€” there is no separate events host. * **v3** (recommendations) β†’ `POST {endpoint}/api/storefront/v3/headless/events`, with headers `Authorization: Bearer ` and `x-shop`. * **v1** (search) β†’ `POST {controlEndpoint}/api/storefront/v1/headless/events`, with headers `Authorization: Bearer ` and `x-shop`. * **v2** (legacy recommendations) β†’ `POST {endpoint}/api/storefront/event`, with header `x-shop-myshopify-domain` (legacy payload). > [!NOTE] > > You do not configure an events endpoint directly. For recommendations it is derived from the app's > `endpoint`; for **search** it is derived from `controlEndpoint` (the non-edge host), so events keep > flowing to the control plane even when `endpoint` points at a regional edge. ## Environment-Specific Configuration ### Multi-Environment Setup Configure different settings for different environments: ```typescript theme={null} const getGloodConfig = () => { const env = process.env.NODE_ENV; const isDev = env === 'development'; const isStaging = env === 'staging'; const isProd = env === 'production'; return { apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: process.env.PUBLIC_STORE_DOMAIN!, version: 3, // 2 | 3 β€” 3 is the default debug: isDev || isStaging, apps: { recommendations: { endpoint: isDev ? 'https://dev-storefront.glood.ai' : isStaging ? 'https://staging-storefront.glood.ai' : 'https://storefront.glood.ai', pixel: { enabled: isProd || isStaging, // No pixels in dev consent: [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING], }, }, }, }; }; const glood = createGlood(getGloodConfig()) .use(recommendations()); ``` ### Environment Variables Use environment variables for external configuration: ```bash theme={null} # .env.development GLOOD_API_KEY=dev_api_key GLOOD_DEBUG=true GLOOD_PIXEL_ENABLED=false GLOOD_RECOMMENDATIONS_ENDPOINT=https://dev-storefront.glood.ai # .env.staging GLOOD_API_KEY=staging_api_key GLOOD_DEBUG=true GLOOD_PIXEL_ENABLED=true GLOOD_RECOMMENDATIONS_ENDPOINT=https://staging-storefront.glood.ai # .env.production GLOOD_API_KEY=production_api_key GLOOD_DEBUG=false GLOOD_PIXEL_ENABLED=true GLOOD_RECOMMENDATIONS_ENDPOINT=https://storefront.glood.ai ``` ```typescript theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: process.env.PUBLIC_STORE_DOMAIN!, version: 3, // 2 | 3 β€” 3 is the default debug: process.env.GLOOD_DEBUG === 'true', apps: { recommendations: { endpoint: process.env.GLOOD_RECOMMENDATIONS_ENDPOINT!, pixel: { enabled: process.env.GLOOD_PIXEL_ENABLED === 'true', consent: [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING], }, }, }, }); ``` ## Privacy & Consent Configuration ### Default Consent Requirements The recommendations app requires both analytics and marketing consent by default, since personalization relies on marketing signals: ```typescript theme={null} // Default consent for recommendations const defaultConsent = ['analytics', 'marketing']; ``` ### Custom Consent Configuration Customize consent requirements for compliance: ```typescript theme={null} import { CONSENT_TYPES } from '@glood/hydrogen'; // GDPR-compliant minimal consent const minimalConsent = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // 2 | 3 β€” 3 is the default apps: { recommendations: { endpoint: 'https://storefront.glood.ai', pixel: { enabled: true, consent: [CONSENT_TYPES.ANALYTICS], // Only analytics }, }, }, }); // Strict privacy requirements const strictConsent = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // 2 | 3 β€” 3 is the default apps: { recommendations: { endpoint: 'https://storefront.glood.ai', pixel: { enabled: true, consent: [ CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING, CONSENT_TYPES.PREFERENCES, CONSENT_TYPES.SALE_OF_DATA, // All consents required ], }, }, }, }); ``` ### Consent Scenarios Different configurations for different privacy requirements: ```typescript theme={null} const getConsentConfig = (privacyLevel: 'minimal' | 'standard' | 'full') => { const consentMap = { minimal: [CONSENT_TYPES.ANALYTICS], standard: [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.PREFERENCES], full: [ CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING, CONSENT_TYPES.PREFERENCES, CONSENT_TYPES.SALE_OF_DATA, ], }; return { apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // 2 | 3 β€” 3 is the default apps: { recommendations: { endpoint: 'https://storefront.glood.ai', pixel: { enabled: true, consent: consentMap[privacyLevel], }, }, }, }; }; // Usage based on user preference or region const privacyLevel = getPrivacyLevel(); // 'minimal' | 'standard' | 'full' const glood = createGlood(getConsentConfig(privacyLevel)); ``` ## Event Subscription Configuration ### Default Event Subscriptions By default, the recommendations app subscribes to all relevant events: ```typescript theme={null} const defaultSubscriptions = { recommendations: [ 'page_viewed', 'product_viewed', 'collection_viewed', 'cart_viewed', 'product_added_to_cart', 'product_removed_from_cart', 'search_submitted', 'custom_promotion_viewed' ], }; ``` ### Custom Event Subscriptions Limit events by setting `subscribedEvents` in the `apps.recommendations` block: ```typescript theme={null} // Product-focused recommendations const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // 2 | 3 β€” 3 is the default apps: { recommendations: { subscribedEvents: ['product_viewed', 'cart_viewed'], }, }, }) .use(recommendations()); // Minimal event tracking const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // 2 | 3 β€” 3 is the default apps: { recommendations: { subscribedEvents: ['product_viewed'], // Only product views }, }, }) .use(recommendations()); ``` ## Performance Configuration ### Development Optimization Optimize for development experience: ```typescript theme={null} const developmentConfig = { apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // 2 | 3 β€” 3 is the default debug: true, // Detailed logging apps: { recommendations: { endpoint: 'https://dev-storefront.glood.ai', pixel: { enabled: false, // No network requests consent: [], }, subscribedEvents: ['product_viewed'], // Minimal events }, }, }; const glood = createGlood(developmentConfig) .use(recommendations()); ``` ### Production Optimization Optimize for production performance: ```typescript theme={null} const productionConfig = { apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: process.env.PUBLIC_STORE_DOMAIN!, version: 3, // 2 | 3 β€” 3 is the default debug: false, // No debug logging apps: { recommendations: { endpoint: 'https://storefront.glood.ai', pixel: { enabled: true, consent: [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING], }, // Use default event subscriptions (all events) }, }, }; ``` ## Testing Configuration In tests, point the recommendations `endpoint` at a mock server and set `pixel.enabled: false` so no external requests are made: ```typescript theme={null} const glood = createGlood({ apiKey: 'test_api_key', myShopifyDomain: 'test-store.myshopify.com', apps: { recommendations: { endpoint: 'http://localhost:3001/mock-api', pixel: { enabled: false, consent: [] }, }, }, }) .use(recommendations()); ``` ## Configuration Validation `createGlood` validates `apiKey`, `myShopifyDomain` and `version` (must be `2` or `3`) and throws on invalid input, so no separate validation step is needed. ## Best Practices ### 1. Environment-Based Configuration Use different configurations for different environments: ```typescript theme={null} // βœ… Good - Environment-specific config const config = getConfigForEnvironment(process.env.NODE_ENV); // ❌ Avoid - Hardcoded production config everywhere const config = { /* production settings */ }; ``` ### 2. Gradual Rollout Start with minimal configuration and gradually add custom settings: ```typescript theme={null} // Phase 1: Basic setup const glood = createGlood({ apiKey, myShopifyDomain }) .use(recommendations()); // Phase 2: Custom endpoint and events const glood = createGlood({ apiKey, myShopifyDomain, apps: { recommendations: { endpoint: 'https://storefront.glood.ai', subscribedEvents: ['product_viewed', 'cart_viewed'], }, }, }) .use(recommendations()); ``` ### 3. Privacy-First Configuration Design configurations with privacy in mind: ```typescript theme={null} // βœ… Good - Minimal consent by default const baseConsent = [CONSENT_TYPES.ANALYTICS]; // βœ… Good - Explicit consent requirements const marketingConsent = [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING]; // ❌ Avoid - Requiring all consents by default const consent = Object.values(CONSENT_TYPES); ``` ### 4. Configuration Documentation Document your configuration choices: ```typescript theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: process.env.PUBLIC_STORE_DOMAIN!, // Headless API version (3 is the default full suite) version: 3, // Enable debug logging in non-production environments debug: process.env.NODE_ENV !== 'production', apps: { recommendations: { endpoint: 'https://storefront.glood.ai', pixel: { // Enable pixel tracking for personalization enabled: true, // Require both analytics and marketing consent for personalization consent: [CONSENT_TYPES.ANALYTICS, CONSENT_TYPES.MARKETING], }, // Track key e-commerce events for recommendations subscribedEvents: [ 'product_viewed', 'cart_viewed', 'product_added_to_cart' ], }, }, }) .use(recommendations()); ``` ## Configuration Examples See the Examples section for complete configuration examples: * [Basic Setup](/for-developers/glood-hydrogen-sdk/examples/basic-setup) - Simple configuration * [Recommendations](/for-developers/glood-hydrogen-sdk/examples/recommendations) - Fetching and displaying recommendation sections ## See Also * [Installation Guide](/for-developers/glood-hydrogen-sdk/installation) - Getting started * [API Reference](/for-developers/glood-hydrogen-sdk/api-reference/client) - Complete API documentation * [Content Security Policy](/for-developers/glood-hydrogen-sdk/content-security-policy) - CSP configuration * [Types Reference](/for-developers/glood-hydrogen-sdk/api-reference/types) - TypeScript interfaces # Content Security Policy Setup Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/content-security-policy Configure CSP to enable Glood pixel tracking and event transmission # Content Security Policy Setup Hydrogen ships with a strict Content Security Policy. Without whitelisting Glood's domains, the browser blocks both recommendation fetches and pixel events with CSP violations. This page shows the required configuration. ## Required CSP Configuration Add the Glood domains to the `connectSrc` directive in your `app/entry.server` file. Hydrogen **merges** your entries with its defaults, so localhost/HMR entries are preserved in development: ```javascript theme={null} // app/entry.server.tsx (or .jsx) const {nonce, header, NonceProvider} = createContentSecurityPolicy({ shop: { checkoutDomain: context.env.PUBLIC_CHECKOUT_DOMAIN, storeDomain: context.env.PUBLIC_STORE_DOMAIN, }, connectSrc: [ "'self'", 'https://storefront.glood.ai', // v3 headless suite (init, sections, events, recommendations) 'https://search.glood.ai', // search v1 API β€” config, instant-search, filters, search, image-search, and events ], }); ``` > [!NOTE] > > Only add the origins for the apps you register. Recommendations needs `storefront.glood.ai`; > search needs `search.glsvces.com` (it serves both the API and events). Registering `.use(search())` > without the search origin blocks every search fetch and event with a CSP violation. ## Glood Domains Explained ### Required Endpoints | Domain | Purpose | Used By | | - | - | - | | `https://storefront.glood.ai` | v3 headless suite β€” session init, recommendation sections (`useRecommendations`, `fetchRecommendationSections`), recommendations, and event transmission | Recommendations app | | `https://search.glood.ai` | Search v1 API β€” config, instant search, filters, filter aggregations, search results, image search, and all search events (standard + `glood:search:*` attribution) (`useSearch`, `useInstantSearch`, `useSearchConfig`, `fetchSearchResults`, …) | Search app | > [!NOTE] > > `https://events.glood.ai` is **no longer used**. As of v3, events go to the versioned events API on the main host (`POST https://storefront.glood.ai/api/storefront/v3/headless/events`). For a `version: 2` client, events go to `POST https://storefront.glood.ai/api/storefront/event` β€” still on the main host. The single `storefront.glood.ai` entry covers all cases. ### Why This Domain Is Needed * **Session Init**: On load, v3 clients bootstrap a session via `POST /api/storefront/v3/headless/init` * **Recommendation Fetches**: Sections and recommendations are fetched via `fetch()` API calls * **Event Transmission**: The SDK sends analytics and attribution events via `fetch()` to the versioned events API * **Privacy Compliance**: Events are only sent when customer consent is granted * **Personalization**: Allows Glood to provide personalized recommendations ## Implementation in Hydrogen Add the CSP configuration to your root layout file: ```typescript theme={null} // app/root.tsx import { json, type LoaderFunctionArgs, } from '@shopify/remix-oxygen'; import { Links, Meta, Outlet, Scripts, ScrollRestoration, useLoaderData, } from '@remix-run/react'; import { Analytics, getShopAnalytics, useNonce, } from '@shopify/hydrogen'; import { createContentSecurityPolicy } from '@shopify/hydrogen'; export async function loader({context}: LoaderFunctionArgs) { const {nonce, header, NonceProvider} = createContentSecurityPolicy({ shop: { checkoutDomain: context.env.PUBLIC_CHECKOUT_DOMAIN, storeDomain: context.env.PUBLIC_STORE_DOMAIN, }, connectSrc: [ "'self'", 'https://storefront.glood.ai', // v3 headless suite (init, sections, events, recommendations) 'https://search.glood.ai', // search v1 API + events ], }); return json({ nonce, header, // ... other loader data }); } export default function App() { const nonce = useNonce(); const data = useLoaderData(); return ( ); } export function headers({loaderHeaders}: {loaderHeaders: Headers}) { return { 'Content-Security-Policy': loaderHeaders.get('Content-Security-Policy'), }; } ``` If you use a non-default recommendations `endpoint`, add that host to `connectSrc` instead of (or alongside) `storefront.glood.ai`. ## Troubleshooting CSP violations show up in the browser console: ``` Content Security Policy: The page's settings blocked the loading of a resource at https://storefront.glood.ai/ ``` If you see this, the Glood host is missing from `connectSrc` β€” add `'https://storefront.glood.ai'` for recommendations, or `'https://search.glood.ai'` for search (or your custom endpoints). With `debug: true` on the client, successful transmission logs the target URL, so you can confirm the request reaches the network rather than being blocked. ## See Also * [Event System](/for-developers/glood-hydrogen-sdk/api-reference/event-system) - How events are transmitted * [Configuration](/for-developers/glood-hydrogen-sdk/configuration) - Endpoint and pixel settings * [Installation Guide](/for-developers/glood-hydrogen-sdk/installation) - Complete setup instructions * [Hydrogen CSP Documentation](https://shopify.dev/docs/custom-storefronts/hydrogen/deployment/content-security-policy) - Official Shopify CSP guide # Basic Setup Example Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/examples/basic-setup Complete example of basic Glood Hydrogen SDK setup with minimal configuration # Basic Setup Example This example shows how to set up the Glood Hydrogen SDK with minimal configuration for a typical e-commerce store. ## Complete Implementation ### 1. Environment Variables ```bash theme={null} # .env GLOOD_API_KEY=your_glood_api_key_here PUBLIC_STORE_DOMAIN=your-store.myshopify.com PUBLIC_CHECKOUT_DOMAIN=your-store.myshopify.com PUBLIC_STOREFRONT_ID=your_storefront_id_here ``` ### 2. Create the Glood Client (app/lib/glood.ts) Create the client once and register the recommendations app. The `apiKey` is a public storefront token (`gl_sf_*`), so it is safe to ship to the browser. ```typescript theme={null} // app/lib/glood.ts import { createGlood, recommendations } from '@glood/hydrogen'; export const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: process.env.PUBLIC_STORE_DOMAIN!, // Headless API version (2 | 3). 3 is the default and the full suite // (init, sections, events, recommendations variants); set explicitly here // for clarity. v2 is legacy and only supports recommendations. version: 3, debug: process.env.NODE_ENV === 'development', }).use(recommendations()); ``` ### 3. Root Layout (app/root.tsx) Wrap your app with `GloodProvider` inside Shopify's `Analytics.Provider` and pass the root loader data. `GloodProvider` subscribes to Shopify's analytics events and, on a **v3** client, automatically fires `POST /v3/headless/init` on mount to bootstrap the session (see below). ```typescript theme={null} import { Outlet, Links, Meta, Scripts, ScrollRestoration, useRouteLoaderData, } from 'react-router'; import { Analytics, getShopAnalytics, useNonce, } from '@shopify/hydrogen'; import { GloodProvider } from '@glood/hydrogen'; import { glood } from '~/lib/glood'; export async function loader({ context }) { const { storefront, env, cart } = context; return { cart: cart.get(), shop: getShopAnalytics({ storefront, publicStorefrontId: env.PUBLIC_STOREFRONT_ID, }), consent: { checkoutDomain: env.PUBLIC_CHECKOUT_DOMAIN, storefrontAccessToken: env.PUBLIC_STOREFRONT_API_TOKEN, withPrivacyBanner: true, }, }; } export function Layout({ children }) { const nonce = useNonce(); return ( {children} ); } export default function App() { const data = useRouteLoaderData('root'); if (!data) { return ; } return ( ); } ``` > [!NOTE] > > `GloodProvider` must render inside Shopify's `Analytics.Provider` so it can > subscribe to the storefront's analytics events. ## What This Setup Provides ### βœ… Automatic Session Init (v3) On page load, a **v3** client automatically calls `POST /api/storefront/v3/headless/init` via `GloodProvider`. This bootstrap: * replays a persisted visitor id and returns/echoes `user_id` (stored in the `_glood_user_id` cookie so returning visitors are recognized), * creates a per-visit `visit_id` (`_glood_visit_id`, a session cookie), * returns the visitor's `browsed` / `cart` / `purchased` history, shop `config` (currency, money format, GraphQL version, integrations, analytics flag) and a storefront `token`. The init response is available anywhere via the `useGloodInit()` hook. For a **v2** client, init is a no-op (the endpoint is v3-only) and `useGloodInit()` returns `null`. ### βœ… Automatic Event Tracking Once wrapped, `GloodProvider` automatically tracks Shopify analytics events (page views, product views, collection views, cart views, add/remove from cart) and forwards them to the recommendations app. ### βœ… Default Endpoint * **Recommendations**: `https://storefront.glood.ai` β€” the v3 headless suite (init, sections, events, recommendations) lives under this endpoint. ### βœ… Debug Logging In development mode (`debug: true`), you'll see console logs like: ``` [Glood Debug] Registered recommendations app [Glood Debug] Running headless init: https://storefront.glood.ai/api/storefront/v3/headless/init [Glood Debug] Setting up centralized subscription for page_viewed [Glood Debug] Received product_viewed event, distributing to interested apps [Glood Debug] Consent granted for recommendations, processing event ``` ## Testing the Setup ### 1. Verify Installation Check that the SDK is working by looking for debug logs in the browser console. ### 2. Verify Session Init On first load, confirm a `POST /api/storefront/v3/headless/init` request succeeds, and that the `_glood_user_id` and `_glood_visit_id` cookies are set. ### 3. Test Event Tracking 1. **Navigate to a product page** – should see `product_viewed` events 2. **Add item to cart** – should see `product_added_to_cart` events 3. **View cart** – should see `cart_viewed` events ## Customizing the Basic Setup ### Add Custom Settings ```typescript theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: process.env.PUBLIC_STORE_DOMAIN!, version: 3, debug: process.env.NODE_ENV === 'development', settings: { storeVersion: '2.0', customTrackingId: 'custom-123', }, }).use(recommendations()); ``` ### Environment-Specific Debug ```typescript theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: process.env.PUBLIC_STORE_DOMAIN!, debug: process.env.NODE_ENV !== 'production', // Debug in dev and staging }).use(recommendations()); ``` ## Using the Glood Client ### Access the Init Response ```typescript theme={null} import { useGloodInit } from '@glood/hydrogen'; function VisitorHistory() { const init = useGloodInit(); if (!init) return null; // null until init resolves (always null for v2) return (

User id: {init.user_id}

Visit id: {init.visit_id}

Recently browsed: {init.visitor.browsed_products.length} products

); } ``` ### Access the Client in Components ```typescript theme={null} import { useGloodAnalytics } from '@glood/hydrogen'; function MyComponent() { const glood = useGloodAnalytics(); if (!glood) { return
Glood not available
; } const recommendationsApp = glood.getApp('recommendations'); return (

Debug mode: {glood.debug ? 'On' : 'Off'}

Recommendations endpoint: {recommendationsApp?.endpoint}

); } ``` ## Common Issues and Solutions ### Issue: No Debug Logs **Check:** 1. Debug mode is enabled: `debug: true` 2. Browser console is open 3. Events are being triggered (navigate to product pages) ### Issue: CSP Violations **Check:** 1. `https://storefront.glood.ai` is in `connectSrc` (see [Content Security Policy](/for-developers/glood-hydrogen-sdk/content-security-policy)) 2. CSP headers are being applied correctly 3. No typos in domain names ### Issue: No Network Requests **Check:** 1. Customer consent is granted (try allowing all cookies) 2. The recommendations app is registered with `.use(recommendations())` 3. `GloodProvider` renders inside `Analytics.Provider` ### Issue: TypeScript Errors **Solution:** ```bash theme={null} npm install --save-dev @types/react @types/node ``` ## Next Steps * [Recommendations Example](/for-developers/glood-hydrogen-sdk/examples/recommendations) - Render sections client-side and via SSR * [Configuration](/for-developers/glood-hydrogen-sdk/configuration) - Version selection, consent, and endpoints * [Signatures & Parameters](/for-developers/glood-hydrogen-sdk/api-reference/signatures) - Every hook and function at a glance * [API Reference](/for-developers/glood-hydrogen-sdk/api-reference/client) - Complete documentation ## Support If you need help with the basic setup: * πŸ“– [Configuration Guide](/for-developers/glood-hydrogen-sdk/configuration) * πŸ”§ [API Reference](/for-developers/glood-hydrogen-sdk/api-reference/client) * πŸ’¬ [GitHub Discussions](https://github.com/LoopClub/glood-hydrogen/discussions) * πŸ› [Report Issues](https://github.com/LoopClub/glood-hydrogen/issues) # Recommendations Example Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/examples/recommendations Complete working example: client-side recommendation sections with attribution tracking # Recommendations Example A complete, tested integration showing recommendations on a product page and the homepage, with full attribution tracking. The primary path renders **client-side** with the `useRecommendations` hook. Copy the pieces you need. ## 1. Client Setup Create the client once and register the recommendations app: ```tsx theme={null} // app/lib/glood.ts import { createGlood, recommendations } from '@glood/hydrogen'; export const glood = createGlood({ apiKey: 'gl_sf_your_storefront_token', myShopifyDomain: 'your-store.myshopify.com', version: 3, // headless API version (2 | 3); 3 is the default debug: import.meta.env.DEV, // verbose [Glood Debug] console logs in dev }).use(recommendations()); ``` Wrap your app in `root.tsx` (inside Shopify's `Analytics.Provider`). A **v3** client fires `POST /v3/headless/init` automatically on mount: ```tsx theme={null} // app/root.tsx import { Analytics } from '@shopify/hydrogen'; import { GloodProvider } from '@glood/hydrogen'; import { glood } from '~/lib/glood'; export default function App() { const data = useRouteLoaderData('root'); return ( ); } ``` ## 2. Reusable Recommendations Component (client-side) `useRecommendations(params, options?)` fetches sections in the browser via the recommendations app from `GloodProvider`. Because the fetch runs client-side, `pageUrl` / `locale` / `clientId` / `userId` default from the browser and the assigned experience is persisted automatically. The hook also returns four attribution helpers. Fire them against a section's `section_serve_id`: * `trackRender` β†’ when the section mounts in the DOM * `trackView` β†’ when the section scrolls into the viewport * `trackClick` β†’ when a recommended product link is clicked * `trackAddToCart` β†’ when the product is added to cart ```tsx theme={null} // app/components/GloodRecommendations.tsx import { useEffect, useRef } from 'react'; import { useRecommendations } from '@glood/hydrogen'; export function GloodRecommendations({ pageType, productId, cartProductIds, }: { pageType: string; productId?: string; cartProductIds?: string[]; }) { const { sections, data, loading, error, trackRender, trackView, trackClick, trackAddToCart, } = useRecommendations({ pageType, productId, cartProductIds }); // Fire render/view once per section serve β€” effects can re-run and observers // can re-intersect; these sets keep each event to exactly one send. const renderedServeIds = useRef(new Set()); const viewedServeIds = useRef(new Set()); const sectionRefs = useRef(new Map()); const buildTrack = ( section: (typeof sections)[number], products?: Array<{ productId: string; variantId?: string; quantity?: number }>, ) => ({ section: String(section.id), sectionServeId: section.section_serve_id, requestId: data?.request_id, page: pageType, parent: productId ? { productId } : undefined, ...(products ? { products } : {}), }); // 1) glood:section:render β€” once per section on mount useEffect(() => { sections.forEach((section) => { if (renderedServeIds.current.has(section.section_serve_id)) return; renderedServeIds.current.add(section.section_serve_id); trackRender(buildTrack(section)); }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [sections]); // 2) glood:section:view β€” when 50% of a section enters the viewport useEffect(() => { if (typeof IntersectionObserver === 'undefined' || sections.length === 0) { return; } const observer = new IntersectionObserver( (entries) => { entries.forEach((entry) => { if (!entry.isIntersecting) return; const serveId = (entry.target as HTMLElement).dataset.gloodServeId; if (!serveId || viewedServeIds.current.has(serveId)) return; viewedServeIds.current.add(serveId); observer.unobserve(entry.target); const section = sections.find((s) => s.section_serve_id === serveId); if (section) trackView(buildTrack(section)); }); }, { threshold: 0.5 }, ); sectionRefs.current.forEach((el) => el && observer.observe(el)); return () => observer.disconnect(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [sections]); if (loading) return

Loading recommendations…

; if (error) return

Recommendations error: {error.message}

; if (sections.length === 0) return null; return (
{sections.map((section) => (
{ if (el) sectionRefs.current.set(section.section_serve_id, el); else sectionRefs.current.delete(section.section_serve_id); }} >

{section.title}

{section.products.map((product) => { const track = buildTrack(section, [ { productId: String(product.product_id), variantId: product.variants[0] ? String(product.variants[0].variant_id) : undefined, quantity: 1, }, ]); return ( ); })}
))}
); } ``` ## 3. Use It on Any Page **Product page** β€” pass the numeric product id (strip the GID prefix): ```tsx theme={null} // app/routes/products.$handle.tsx import { GloodRecommendations } from '~/components/GloodRecommendations'; export default function Product() { const { product } = useLoaderData(); return (
{/* ...product details... */}
); } ``` **Homepage:** ```tsx theme={null} // app/routes/_index.tsx ``` **Cart page** β€” pass what's in the cart so Glood can exclude/complement it: ```tsx theme={null} line.merchandise.product.id.split('/').pop(), )} /> ``` ## 4. Server-Side Rendering Variant To include recommendations in the initial HTML, fetch in the route loader with `fetchRecommendationSections` instead of the hook: ```tsx theme={null} // app/routes/products.$handle.tsx import { fetchRecommendationSections } from '@glood/hydrogen'; export async function loader({ request, params, context }) { // Load the product first so we have its GID β€” the sections API wants the // numeric product id, not the route's `$handle` param. const product = await loadProduct(context, params); const recommendations = await fetchRecommendationSections( { apiKey: context.env.GLOOD_API_KEY, myShopifyDomain: 'your-store.myshopify.com', version: 3, // defaults to 3 }, { pageType: 'product_page', pageUrl: request.url, locale: 'en-US', // Derive the numeric id from the product GID (gid://shopify/Product/123) productId: product.id.split('/').pop(), }, ).catch(() => null); // degrade gracefully return { product, recommendations }; } export default function Product() { const { recommendations } = useLoaderData(); return ( <> {recommendations?.sections.map((section) => (

{section.title}

{/* render section.products */}
))} ); } ``` > [!NOTE] > > With SSR you still get attribution: retrieve the track helpers client-side from > `useRecommendations` (pass `{ skip: true }` to reuse the helpers without a > second fetch) and call `trackRender` / `trackView` / `trackClick` / > `trackAddToCart` with the `section_serve_id` values from your loader data. ## 5. Don't Forget the CSP Recommendation fetches and events are blocked by Hydrogen's default Content Security Policy. Add Glood's endpoint in `entry.server`: ```tsx theme={null} const { nonce, header, NonceProvider } = createContentSecurityPolicy({ shop: { checkoutDomain: context.env.PUBLIC_CHECKOUT_DOMAIN, storeDomain: context.env.PUBLIC_STORE_DOMAIN, }, connectSrc: [ "'self'", 'https://storefront.glood.ai', // headless suite: init, sections, events ], }); ``` See [Content Security Policy](/for-developers/glood-hydrogen-sdk/content-security-policy) for details. ## What You'll See in the Console (debug: true) ``` [Glood Debug] Registered recommendations app [Glood Debug] Running headless init: https://storefront.glood.ai/api/storefront/v3/headless/init [Glood Debug] Fetching sections: https://storefront.glood.ai/api/storefront/v3/headless/sections {page_type: 'home', ...} [Glood Debug] Received 5 sections [Glood Debug] Consent granted for recommendations, processing event [Glood Debug] Successfully sent event to https://storefront.glood.ai/api/storefront/v3/headless/events ``` ## See Also * [Loading Recommendations Guide](/for-developers/glood-hydrogen-sdk/recommendations) * [Recommendations API Reference](/for-developers/glood-hydrogen-sdk/api-reference/recommendations-api) * [Basic Setup Example](/for-developers/glood-hydrogen-sdk/examples/basic-setup) # Search Example Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/examples/search Complete working example: a custom search page with instant search, results, filters, image search and attribution # Search Example A complete, copy-pasteable search experience built on the Glood Hydrogen Search SDK: config β†’ instant search β†’ full results β†’ filters β†’ image search β†’ attribution events. Take the pieces you need. ## 1. Client Setup Register the search app once (alongside recommendations if you use it): ```tsx theme={null} // app/lib/glood.ts import { createGlood, search } from '@glood/hydrogen'; export const glood = createGlood({ apiKey: 'gl_sf_your_storefront_token', myShopifyDomain: 'your-store.myshopify.com', debug: import.meta.env.DEV, }).use(search()); ``` Wrap your app in `root.tsx` (inside Shopify's `Analytics.Provider`): ```tsx theme={null} // app/root.tsx import { Analytics } from '@shopify/hydrogen'; import { GloodProvider } from '@glood/hydrogen'; import { glood } from '~/lib/glood'; export default function App() { const data = useRouteLoaderData('root'); return ( ); } ``` ## 2. Don't Forget the CSP Search fetches and events are blocked by Hydrogen's default CSP. Add the search origins in `entry.server`: ```tsx theme={null} const { nonce, header, NonceProvider } = createContentSecurityPolicy({ shop: { checkoutDomain: context.env.PUBLIC_CHECKOUT_DOMAIN, storeDomain: context.env.PUBLIC_STORE_DOMAIN, }, connectSrc: [ "'self'", 'https://storefront.glood.ai', // recommendations (if used) 'https://search.glood.ai', // search v1 API + events ], }); ``` ## 3. Instant Search Box Type-ahead search with suggestions, autocorrect and a trending empty state: ```tsx theme={null} // app/components/GloodSearchBox.tsx import { useState } from 'react'; import { useInstantSearch } from '@glood/hydrogen'; export function GloodSearchBox() { const [term, setTerm] = useState(''); const { products, suggestions, data, loading } = useInstantSearch( { query: term, objects: ['product', 'collection', 'query_suggestion', 'autocorrect'] }, { skip: term.length < 2 }, ); return (
setTerm(e.target.value)} placeholder="Search products…" /> {loading && } {data?.corrected_query && ( )} {suggestions.length > 0 && (
    {suggestions.map((s) => (
  • setTerm(s.text)}> {s.text}
  • ))}
)}
{products.map((p) => ( {p.title} {p.title} {p.display_price ?? p.price} ))}
{term.length < 2 && data?.trending?.searches?.length ? (

Trending

{data.trending.searches.map((t) => ( ))}
) : null}
); } ``` ## 4. Full Search Results Page A results page with filters, sort, pagination, and click/add-to-cart attribution: ```tsx theme={null} // app/routes/search.tsx import { useState } from 'react'; import { useSearchParams } from 'react-router'; import { useSearch, useGloodAnalytics } from '@glood/hydrogen'; export default function SearchPage() { const [searchParams] = useSearchParams(); const query = searchParams.get('q') ?? ''; const [page, setPage] = useState(1); const [selectedColors, setSelectedColors] = useState([]); const facets = selectedColors.length ? [{ key: 'color', operator: 'or' as const, value: selectedColors }] : []; const { products, data, loading, error, trackSearch, trackResultClick, trackAddToCart, trackFilter, } = useSearch({ query, facets, sort: 'relevance', pagination: { page, limit: 24 }, options: { includeFacets: true }, }); if (error) return

Search failed: {error.message}

; const buildTrack = (product?: { product_id: number | string }) => ({ request_id: data?.request_id, search_term: query, search_type: 'text', source: 'search_page', ...(product ? { products: [{ product_id: product.product_id }] } : {}), ...(selectedColors.length ? { filters: [{ key: 'color', value: selectedColors }] } : {}), }); return (
trackSearch(buildTrack())}>
{loading ? (

Searching…

) : ( <>

{data?.pagination.total} results for β€œ{query}”

{products.map((product) => ( ))}
)}
); } ``` ## 5. Image (Visual) Search Search by an uploaded photo: ```tsx theme={null} // app/components/GloodImageSearch.tsx import { useState } from 'react'; import { useGloodAnalytics, type SearchItem } from '@glood/hydrogen'; const toDataUrl = (file: File) => new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result as string); reader.onerror = reject; reader.readAsDataURL(file); }); export function GloodImageSearch() { const app = useGloodAnalytics()?.getApp('search'); const [products, setProducts] = useState([]); async function onFile(e: React.ChangeEvent) { const file = e.target.files?.[0]; if (!file || !app) return; // jpeg/png/webp only, 1KB–5MB, 100Γ—100 to 4096Γ—4096 const res = await app.imageSearch({ image: await toDataUrl(file), pagination: { limit: 24 } }); setProducts(res.products); } return (
{products.map((p) => ( {p.title} {p.title} ))}
); } ``` ## 6. Server-Side Rendering Variant To ship results in the initial HTML, fetch in the loader instead of the hook: ```tsx theme={null} // app/routes/search.tsx import { fetchSearchResults } from '@glood/hydrogen'; export async function loader({ request, context }) { const query = new URL(request.url).searchParams.get('q') ?? ''; const results = await fetchSearchResults( { apiKey: context.env.GLOOD_API_KEY, myShopifyDomain: 'your-store.myshopify.com', }, { query, pagination: { page: 1, limit: 24 } }, ).catch(() => null); // degrade gracefully return { query, results }; } export default function SearchPage() { const { results } = useLoaderData(); return (
{results?.products.map((product) => ( {product.title} {product.title} ))}
); } ``` > [!NOTE] > > With SSR you still get attribution: retrieve the track helpers client-side from `useSearch` > (pass `{ skip: true }` to reuse them without a second fetch), or send events directly with > `sendSearchEvent(options, event)`. ## 7. Standard Events Are Automatic Once `search()` is registered, `GloodProvider` forwards Shopify standard events (`product_viewed`, `search_submitted`, `product_added_to_cart`, …) to the search backend with no extra code. Narrow them if you want: ```tsx theme={null} createGlood({ apiKey, myShopifyDomain }) .use(search({ events: ['search_submitted', 'product_added_to_cart'] })); ``` ## 8. Glood Search Events On top of the standard events, the Glood search app emits custom attribution events. The search page above already sends the click and filter ones via the track helpers: | Event | Fired when | How | | - | - | - | | `glood:search_result_rendered` | Results render / enter the viewport | `trackResultView(track)` | | `glood:search_result_clicked` | A result is clicked | `trackResultClick(track)` β€” see Β§4 | | `glood:search_filter_appeared` | The filter UI is rendered | `sendSearchEvent(options, event)` (no helper) | | `glood:search_filter_updated` | A facet is applied / changed | `trackFilter(track)` β€” see Β§4 | Each event carries a specific `custom_data.track` payload on the wire β€” see the [event-wise payload structure](/api-reference/search/headless/events#event-payload-structure) in the Search Events API reference for the exact shape of every standard and `glood:` event. ## What You'll See in the Console (debug: true) ``` [Glood Debug] Registered search app [Glood Debug] App search subscribes to events: ['page_viewed', 'product_viewed', 'search_submitted', ...] [Glood Debug] Fetching search: https://search.glood.ai/api/storefront/v1/headless/search {query: 'shoe', ...} [Glood Debug] Successfully sent event to https://search.glood.ai/api/storefront/event ``` ## See Also * [Search & Discovery Guide](/for-developers/glood-hydrogen-sdk/search) * [Search Events API β€” event payload structure](/api-reference/search/headless/events#event-payload-structure) * [Search API Reference](/for-developers/glood-hydrogen-sdk/api-reference/search-api) * [Content Security Policy](/for-developers/glood-hydrogen-sdk/content-security-policy) # Collection Page Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/guides/collection-page Render a Shopify collection with facets, sort and pagination using the Glood Hydrogen Search SDK A collection page is a [`useSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#usesearch) call with an **empty query** scoped to a collection via `targetPage: 'collection'` and the collection's **numeric** id. > [!NOTE] > > Prerequisite: the search app is registered (`.use(search())`), your app is wrapped in > ``, and `https://search.glood.ai` is in your CSP `connectSrc`. See > [Installation](/for-developers/glood-hydrogen-sdk/installation) β€” this guide covers only the > collection-page wiring. ## 1. Fetch the collection's products Call [`useSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#usesearch) with `targetPage: 'collection'`, `targetId` (the numeric Shopify collection id), and `includeFacets` so the response carries inline facet counts for the collection. ```tsx theme={null} import { useState } from 'react'; import { useSearch } from '@glood/hydrogen'; function CollectionGrid({ collectionId }: { collectionId: number }) { const [page, setPage] = useState(1); const { products, data, loading, error } = useSearch({ query: '', // collection browse β€” no search term targetPage: 'collection', targetId: collectionId, // numeric id, not the gid:// or handle sort: 'best_selling', pagination: { page, limit: 24 }, options: { includeFacets: true }, }); if (error) return

{error.message}

; // …render below } ``` The params above are a [`SearchParams`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchparams--searchresponse); the returned `data` is a [`SearchResponse`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchparams--searchresponse) and each `products` entry is a [`SearchProduct`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchproduct). > [!NOTE] > > `targetId` is the **numeric** collection id. In a Hydrogen collection route you have the > collection GID (`gid://shopify/Collection/123`) β€” pass the trailing number (`123`). ## 2. Render products, sort and pagination ```tsx theme={null} return (
{/* hold `sort` in state and pass it to useSearch; re-run resets to page 1 */}
{products.map((p) => ( {p.title} {p.title} {p.display_price ?? p.price} ))}
); ``` `sort` accepts the values in [`SearchSort`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchview--searchsort); `data.pagination` is a [`SearchPagination`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchpagination). ## 3. Add facet filtering With `includeFacets: true`, `data.facets` holds the collection's facets with live counts. Track the selected values in state and pass them back as the `facets` param: ```tsx theme={null} const [selected, setSelected] = useState>({}); const { data } = useSearch({ query: '', targetPage: 'collection', targetId: collectionId, facets: Object.entries(selected).map(([key, value]) => ({ key, operator: 'or', value })), pagination: { page, limit: 24 }, options: { includeFacets: true }, }); // …render facets {data?.facets?.map((facet) => (
{facet.key} {facet.aggregation.buckets.map((b) => ( ))}
))} ``` Each applied filter is a [`SearchAppliedFacet`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchparams--searchresponse). > [!NOTE] > > For stable filter **definitions** (labels, order, swatches β€” independent of the current > query), fetch them once with > [`fetchFilters`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#fetchfilters) / > `app.filters({ collection: collectionId })` and merge in the live counts from > `data.facets`. See [Filters & aggregations](/for-developers/glood-hydrogen-sdk/search#filters--aggregations). ## 4. Attribute clicks `useSearch` returns the track helpers. Fire [`trackResultClick`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#usesearch) with `page_type: 'collection'`: ```tsx theme={null} const { products, data, trackResultClick } = useSearch({ /* …as above */ }); trackResultClick({ request_id: data?.request_id, search_type: 'text', page_type: 'collection', products: [{ product_id: p.product_id }], }) } > ``` The payload is a [`SearchTrack`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchtrack). ## See also * [`useSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#usesearch) β€” full returns (including `trackFilter`, `trackAddToCart`) * [Search Page](/for-developers/glood-hydrogen-sdk/guides/search-page) β€” the same call driven by a query * [Search API Reference](/for-developers/glood-hydrogen-sdk/api-reference/search-api) # Image Search Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/guides/image-search Search by an uploaded photo or image URL using the Glood Hydrogen Search SDK Image (visual) search takes one image source and returns matching products. In the browser use the `SearchApp`'s [`imageSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#methods) method; for SSR use the standalone [`fetchImageSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#fetchimagesearch). > [!NOTE] > > Prerequisite: the search app is registered (`.use(search())`), your app is wrapped in > ``, and `https://search.glood.ai` is in your CSP `connectSrc`. See > [Installation](/for-developers/glood-hydrogen-sdk/installation). ## 1. Get the image as a `data:` URL Pass **exactly one** source: `image` (base64 or a `data:` URL) **or** `imageUrl` (an http(s) URL, fetched server-side). From a file input, convert to a `data:` URL: ```tsx theme={null} const toDataUrl = (file: File) => new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result as string); reader.onerror = reject; reader.readAsDataURL(file); }); ``` ## 2. Run the search Retrieve the `SearchApp` via `useGloodAnalytics().getApp('search')` and call [`imageSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#methods): ```tsx theme={null} import { useState } from 'react'; import { useGloodAnalytics, type SearchItem } from '@glood/hydrogen'; export function ImageSearch() { const app = useGloodAnalytics()?.getApp('search'); const [products, setProducts] = useState([]); async function onFile(e: React.ChangeEvent) { const file = e.target.files?.[0]; if (!file || !app) return; const res = await app.imageSearch({ image: await toDataUrl(file), pagination: { limit: 24 } }); setProducts(res.products); } return ( ); } ``` Params are an [`ImageSearchParams`](/for-developers/glood-hydrogen-sdk/api-reference/types#imagesearchparams--imagesearchresponse); `res` is an [`ImageSearchResponse`](/for-developers/glood-hydrogen-sdk/api-reference/types#imagesearchparams--imagesearchresponse) and each product is a [`SearchProduct`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchproduct). > [!NOTE] > > `imageSearch` always runs against the app's **`controlEndpoint`** (non-edge) β€” the vision > pipeline isn't available on regional edges. This routing is automatic; see > [Configuration β†’ Edge vs. non-edge routing](/for-developers/glood-hydrogen-sdk/configuration#edge-vs-non-edge-routing-controlendpoint). ## 3. Image constraints Images are validated server-side; anything outside these returns `400`: | Rule | Value | | - | - | | Format | `jpeg`, `png`, `webp` only | | Size | 1 KB – 5 MB | | Dimensions | 100Γ—100 to 4096Γ—4096 px | ## 4. From a URL, or on the server Pass `imageUrl` instead of `image` to search by a hosted image, and use [`fetchImageSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#fetchimagesearch) when you don't have a React component (loaders, mobile backends): ```tsx theme={null} import { fetchImageSearch } from '@glood/hydrogen'; const res = await fetchImageSearch( { apiKey: context.env.GLOOD_API_KEY, myShopifyDomain: 'your-store.myshopify.com' }, { imageUrl: 'https://example.com/photo.jpg', pagination: { limit: 24 } }, ); ``` ## 5. Attribution Attribute clicks with `search_type: 'image'` via the `SearchApp` track helpers ([`trackResultClick`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#event-helpers)), each taking a [`SearchTrack`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchtrack): ```tsx theme={null} app.trackResultClick({ search_type: 'image', source: 'image_search', products: [{ product_id: p.product_id }], }); ``` ## See also * [`fetchImageSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#fetchimagesearch) β€” standalone signature * [Search & Discovery β†’ Image search](/for-developers/glood-hydrogen-sdk/search#image-visual-search) * [Search API Reference](/for-developers/glood-hydrogen-sdk/api-reference/search-api) # Instant Search Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/guides/instant-search Add a type-ahead search box with suggestions, autocorrect and a trending empty state using the Glood Hydrogen Search SDK Instant (type-ahead) search is a single [`useInstantSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#useinstantsearch) call that returns products, collections, pages, keyword suggestions and autocorrect β€” and a `trending` block when the query is empty. > [!NOTE] > > Prerequisite: the search app is registered (`.use(search())`), your app is wrapped in > ``, and `https://search.glood.ai` is in your CSP `connectSrc`. See > [Installation](/for-developers/glood-hydrogen-sdk/installation). ## 1. Wire the input to `useInstantSearch` Keep the query in state and gate fetching with `options.skip` until it clears the minimum length. The minimum comes from the config (`minimum_type_ahead_input_count`), read via [`useSearchConfig`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#usesearchconfig). ```tsx theme={null} import { useState } from 'react'; import { useInstantSearch, useSearchConfig } from '@glood/hydrogen'; export function SearchBox() { const { config } = useSearchConfig(); const minChars = config?.config.minimum_type_ahead_input_count ?? 2; const [term, setTerm] = useState(''); const { products, suggestions, collections, data, loading } = useInstantSearch( { query: term, objects: ['product', 'collection', 'query_suggestion', 'autocorrect'] }, { skip: term.length < minChars }, ); // …render below } ``` Params are an [`InstantSearchParams`](/for-developers/glood-hydrogen-sdk/api-reference/types#instantsearchparams--instantsearchresponse) (`objects` selects which result blocks to return); `data` is an [`InstantSearchResponse`](/for-developers/glood-hydrogen-sdk/api-reference/types#instantsearchparams--instantsearchresponse). `config` is a [`SearchConfigResponse`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchconfigparams--searchconfigresponse). ## 2. Render suggestions, autocorrect and products `products`, `suggestions` and `collections` are convenience accessors; the full response (`articles`, `autocorrect`, `trending`, `metadata`) is on `data`. ```tsx theme={null} return (
setTerm(e.target.value)} placeholder="Search…" /> {loading && } {data?.corrected_query && ( )}
    {suggestions.map((s) => (
  • setTerm(s.text)}>{s.text}
  • ))}
{products.map((p) => ( {p.title} {p.title} {p.display_price ?? p.price} ))}
); ``` Each suggestion is a [`SearchSuggestion`](/for-developers/glood-hydrogen-sdk/api-reference/types#instantsearchparams--instantsearchresponse), each product a [`SearchProduct`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchproduct). ## 3. Trending empty state The same response carries a `trending` block whenever the query is empty or below the minimum length β€” no extra call. Drop the `skip` gate so it fetches on an empty query, tune it with the `trending` param ([`InstantSearchTrendingParams`](/for-developers/glood-hydrogen-sdk/api-reference/types#instantsearchparams--instantsearchresponse)), and read `data.trending`: ```tsx theme={null} const { data } = useInstantSearch({ query: term, trending: { type: 'all', period: '7d', limit: 8 }, }); {term.length < minChars && data?.trending?.searches?.map((t) => ( ))} ``` ## 4. Submit to the results page On Enter or click, navigate to your [Search Page](/for-developers/glood-hydrogen-sdk/guides/search-page) (`/search?q=`). Standard `search_submitted` events are forwarded automatically once `search()` is registered; for explicit attribution call [`trackSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#event-helpers) from `useGloodAnalytics().getApp('search')` (see [Events & attribution](/for-developers/glood-hydrogen-sdk/search#events--attribution)). ## See also * [`useInstantSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#useinstantsearch) β€” full returns * [`fetchInstantSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#fetchinstantsearch) β€” SSR / non-React * [Search Page](/for-developers/glood-hydrogen-sdk/guides/search-page) # Search Page Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/guides/search-page Build a full search results page β€” query, facets, sort, pagination and attribution β€” with the Glood Hydrogen Search SDK A search results page is a [`useSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#usesearch) call driven by the shopper's query, with facets, sort, pagination and attribution. > [!NOTE] > > Prerequisite: the search app is registered (`.use(search())`), your app is wrapped in > ``, and `https://search.glood.ai` is in your CSP `connectSrc`. See > [Installation](/for-developers/glood-hydrogen-sdk/installation). ## 1. Run the search Read the query from the URL and pass it to [`useSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#usesearch). Set `includeFacets` to get inline facet counts for the current query. ```tsx theme={null} // app/routes/search.tsx import { useState } from 'react'; import { useSearchParams } from 'react-router'; import { useSearch } from '@glood/hydrogen'; export default function SearchPage() { const [params] = useSearchParams(); const query = params.get('q') ?? ''; const [page, setPage] = useState(1); const [sort, setSort] = useState('relevance'); const { products, data, loading, error, trackResultClick, trackFilter } = useSearch({ query, sort, pagination: { page, limit: 24 }, options: { includeFacets: true }, }); if (error) return

Search failed: {error.message}

; // …render below } ``` Params are a [`SearchParams`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchparams--searchresponse); `data` is a [`SearchResponse`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchparams--searchresponse) and `products` are [`SearchProduct`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchproduct) objects. ## 2. Render results, sort and pagination ```tsx theme={null} return ( <>

{data?.pagination.total} results for β€œ{query}”

); ``` `sort` values are listed in [`SearchSort`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchview--searchsort); `data.pagination` is a [`SearchPagination`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchpagination). ## 3. Add facet filtering Track selected facet values in state and pass them as the `facets` param (an array of [`SearchAppliedFacet`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchparams--searchresponse)). Render the buckets from `data.facets`: ```tsx theme={null} const [selected, setSelected] = useState>({}); const { data } = useSearch({ query, facets: Object.entries(selected).map(([key, value]) => ({ key, operator: 'or', value })), pagination: { page, limit: 24 }, options: { includeFacets: true }, }); {data?.facets?.map((facet) => (
{facet.key} {facet.aggregation.buckets.map((b) => ( ))}
))} ``` > [!NOTE] > > For stable filter definitions independent of the query, fetch them with > [`fetchFilters`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#fetchfilters), and > for standalone live counts use > [`fetchFilterAggregations`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#fetchfilteraggregations). ## 4. Attribution [`useSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#usesearch) returns [`trackSearch`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#usesearch), `trackResultView`, `trackResultClick`, `trackAddToCart` and `trackFilter`. Call `trackSearch` when the results render, `trackResultClick` on click (step 2), and `trackAddToCart` on add. Each takes a [`SearchTrack`](/for-developers/glood-hydrogen-sdk/api-reference/types#searchtrack). Standard Shopify events (`search_submitted`, `product_viewed`, …) are forwarded automatically β€” see [Events & attribution](/for-developers/glood-hydrogen-sdk/search#events--attribution). ## 5. (Optional) Server-render the first page To ship results in the initial HTML, call [`fetchSearchResults`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#fetchsearchresults) in the route loader instead of the hook: ```tsx theme={null} import { fetchSearchResults } from '@glood/hydrogen'; export async function loader({ request, context }) { const query = new URL(request.url).searchParams.get('q') ?? ''; const results = await fetchSearchResults( { apiKey: context.env.GLOOD_API_KEY, myShopifyDomain: 'your-store.myshopify.com' }, { query, pagination: { page: 1, limit: 24 } }, ).catch(() => null); // never let search break the page return { query, results }; } ``` ## See also * [Instant Search](/for-developers/glood-hydrogen-sdk/guides/instant-search) β€” the type-ahead box that feeds this page * [Search API Reference](/for-developers/glood-hydrogen-sdk/api-reference/search-api) * [Full example route](/for-developers/glood-hydrogen-sdk/examples/search) # Glood Hydrogen SDK Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/index Complete guide to integrating Glood with Shopify Hydrogen for e-commerce analytics and personalization # Glood Hydrogen SDK The **Glood Hydrogen SDK** is a TypeScript-first library designed specifically for integrating Glood's product recommendations into Shopify Hydrogen storefronts. It provides React components, hooks, and utilities optimized for the Hydrogen framework. The SDK is **recommendations-focused**: it loads recommendation sections, powers the headless recommendation endpoints, and streams analytics and attribution events back to Glood. ## Key Features πŸš€ **Hydrogen-Optimized** - Built specifically for Shopify Hydrogen with SSR support πŸ›οΈ **Recommendations** - Load recommendation sections with full product data via a React hook or SSR loader πŸ“‘ **Zero-Config Analytics** - Standard events (page views, add to cart, ...) sent out of the box 🎯 **TypeScript First** - Complete type safety with excellent developer experience ⚑ **Performance Focused** - Tree-shakeable exports and optimized pixel tracking πŸ”§ **Zero Configuration** - Works out of the box with sensible defaults πŸ›‘οΈ **Privacy Compliant** - GDPR/CCPA compliant with automatic consent handling πŸ“¦ **Lightweight** - Minimal bundle impact with selective imports ## Quick Start ### 1. Installation ```bash theme={null} npm install @glood/hydrogen ``` ### 2. Basic Setup Add your Glood API key to environment variables: ```bash theme={null} # .env GLOOD_API_KEY=your_glood_api_key_here ``` Configure the SDK in your root layout: ```tsx theme={null} // app/root.tsx import { Analytics } from '@shopify/hydrogen'; import { GloodProvider, createGlood } from '@glood/hydrogen'; import { recommendations } from '@glood/hydrogen'; import { useLoaderData } from 'react-router'; const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // Headless API version (2 | 3), 3 is the default }) .use(recommendations()); export default function App() { const loaderData = useLoaderData(); return ( ); } ``` ### 3. That's It! πŸŽ‰ No additional setup required. The SDK automatically: * βœ… Bootstraps a session on load (v3 clients call `POST /api/storefront/v3/headless/init`) * βœ… Tracks user interactions via Shopify Analytics * βœ… Sends analytics and attribution events to the versioned events API * βœ… Respects customer privacy settings * βœ… Provides debug logging in development ### 4. Load Recommendations Display the recommendation sections configured in your Glood dashboard: ```tsx theme={null} import { useRecommendations } from '@glood/hydrogen'; function ProductRecommendations({ productId }) { const { sections, loading } = useRecommendations({ pageType: 'product_page', productId, }); if (loading) return null; return sections.map((section) => (

{section.title}

{section.products.map((product) => ( {product.title} β€” {product.price} ))}
)); } ``` See [Loading Recommendations](/for-developers/glood-hydrogen-sdk/recommendations) for SSR loaders and attribution tracking. ### Why loaderData is Required The `loaderData` prop is **mandatory** and enables the Glood recommendations app to: * **Access route-specific data** from Hydrogen loaders for enhanced context * **Enhance analytics events** with additional page-specific information * **Provide personalized recommendations** based on current page data Always pass the result of `useLoaderData()` to the `GloodProvider` component. ## Architecture Overview ### React Context Integration The SDK uses React Context to provide the Glood client throughout your application: ```tsx theme={null} // GloodProvider creates a context with the client function App() { const loaderData = useLoaderData(); return ( ); } // Access the client anywhere in your component tree function MyComponent() { const client = useGloodAnalytics(); // Use client for custom integrations } ``` ### Session Init On mount, `GloodProvider` bootstraps a session for **v3** clients by calling `POST /api/storefront/v3/headless/init`. It replays the persisted visitor id (`_glood_user_id` cookie), creates a per-visit id (`_glood_visit_id`), and returns the visitor's history, shop config, and storefront token. For **v2** clients init is a no-op. The response is exposed via the `useGloodInit()` hook. ### Event Flow 1. **Shopify Analytics** β†’ Automatically tracks user interactions 2. **GloodProvider** β†’ Subscribes to analytics events via `useAnalytics()` 3. **Event Transformation** β†’ Converts Shopify events to the Glood event format 4. **Consent Checking** β†’ Verifies customer privacy permissions 5. **Event Transmission** β†’ Sends events to the versioned events API (v3 β†’ `POST {endpoint}/api/storefront/v3/headless/events`; v2 β†’ `POST {endpoint}/api/storefront/event`) ### App Module The SDK exposes a single app module: * **Recommendations** (`recommendations()`) - Product recommendations, personalization, sections, and event tracking Register it via `.use(recommendations())`. It can be configured with a custom endpoint and pixel settings. ## Configuration Options ### Basic Configuration (Recommended) ```tsx theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // Headless API version (2 | 3), 3 is the default debug: process.env.NODE_ENV === 'development', // Optional debug mode }); ``` **Benefits:** * Zero configuration beyond API key and domain * Automatic default endpoint for recommendations * Pixel tracking enabled by default with appropriate consent requirements * Perfect for getting started quickly ### Advanced Configuration ```tsx theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', version: 3, // 2 | 3, default 3 apps: { recommendations: { endpoint: 'https://storefront.glood.ai', pixel: { enabled: true, consent: ['analytics', 'marketing'], }, }, }, debug: true, }); ``` > [!NOTE] > > Events route off the app's main `endpoint` and the client `version` (v3 β†’ `POST {endpoint}/api/storefront/v3/headless/events`), not off `pixel.endpoint`. There is no separate events host to configure. **Benefits:** * Custom endpoint URL for different environments * Granular pixel tracking control * Custom consent requirements for privacy compliance * Environment-specific configurations ## Privacy & Compliance The SDK provides automatic privacy compliance through Shopify's Customer Privacy API: ### Default Consent Requirements * **Recommendations**: `['analytics', 'marketing']` - Analytics and marketing consent ### How Consent Works 1. User visits site and sees Shopify privacy banner 2. User grants specific consent types through the privacy interface 3. Events are tracked by Shopify Analytics as usual 4. For each event, Glood checks if user has granted **all required consents** for that app 5. Only if all consents are granted, pixel data is sent to Glood This ensures full GDPR/CCPA compliance without any manual implementation. ## Default Endpoints When using basic configuration, the recommendations endpoint is used automatically: ### Recommendations * **Main**: `https://storefront.glood.ai` - Product recommendations API and the full v3 headless suite (init, sections, events, recommendations variants) The versioned events API lives under this same host: v3 events go to `POST {endpoint}/api/storefront/v3/headless/events` and v2 events go to `POST {endpoint}/api/storefront/event`. ## Content Security Policy Setup To enable recommendation fetches and event transmission, add the Glood domain to your Content Security Policy: ```javascript theme={null} const {nonce, header, NonceProvider} = createContentSecurityPolicy({ shop: { checkoutDomain: context.env.PUBLIC_CHECKOUT_DOMAIN, storeDomain: context.env.PUBLIC_STORE_DOMAIN, }, connectSrc: [ "'self'", 'https://storefront.glood.ai', // v3 headless suite (init, sections, events, recommendations) ], }); ``` This whitelists Glood's endpoint so init, sections, recommendations, and event calls can go through. See the [CSP guide](/for-developers/glood-hydrogen-sdk/content-security-policy) for details. ## Debug Mode Enable debug mode to see detailed logging during development: ```tsx theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', debug: process.env.NODE_ENV === 'development', }); ``` Debug logs show: * Event subscriptions setup * Received analytics events * Consent checking results * Pixel transmission status * Error details ## Next Steps * [Installation Guide](/for-developers/glood-hydrogen-sdk/installation) - Detailed setup instructions * [Configuration](/for-developers/glood-hydrogen-sdk/configuration) - Basic and advanced configuration options * [Loading Recommendations](/for-developers/glood-hydrogen-sdk/recommendations) - Fetch and display recommendation sections * [API Reference](/for-developers/glood-hydrogen-sdk/api-reference/client) - Complete API documentation * [Examples](/for-developers/glood-hydrogen-sdk/examples/basic-setup) - Implementation examples and patterns * [Content Security Policy](/for-developers/glood-hydrogen-sdk/content-security-policy) - CSP configuration guide ## Requirements * Node.js 18+ * React 18+ * Shopify Hydrogen 2024.10.1+ * TypeScript 5.4+ (recommended) ## Support * πŸ“– [API Reference](/for-developers/glood-hydrogen-sdk/api-reference/client) * πŸ’¬ [GitHub Discussions](https://github.com/LoopClub/glood-hydrogen/discussions) * πŸ› [Issues](https://github.com/LoopClub/glood-hydrogen/issues) # Installation Guide Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/installation Step-by-step guide to install and set up the Glood Hydrogen SDK # Installation Guide Complete guide to installing and setting up the Glood Hydrogen SDK in your Shopify Hydrogen project. ## Prerequisites Before installing the Glood SDK, ensure you have: * **Node.js 18+** - Required for Hydrogen projects * **React 18+** - Hydrogen uses React 18 features * **Shopify Hydrogen 2024.10.1+** - Compatible Hydrogen version * **TypeScript 5.4+** - Recommended for full type safety * **Glood API Key** - Contact Glood team to obtain your API key ## Step 1: Install the Package Install the Glood Hydrogen SDK using your preferred package manager: ### npm ```bash theme={null} npm install @glood/hydrogen ``` ### yarn ```bash theme={null} yarn add @glood/hydrogen ``` ### pnpm ```bash theme={null} pnpm add @glood/hydrogen ``` ## Step 2: Environment Configuration Add your Glood API key to your environment variables: ### .env file ```bash theme={null} # .env GLOOD_API_KEY=your_glood_api_key_here ``` ### Environment Variables Set up environment variables for different environments: ```bash theme={null} # .env.development GLOOD_API_KEY=dev_api_key_here NODE_ENV=development # .env.staging GLOOD_API_KEY=staging_api_key_here NODE_ENV=staging # .env.production GLOOD_API_KEY=production_api_key_here NODE_ENV=production ``` ### TypeScript Environment Types Add environment types for TypeScript projects: ```typescript theme={null} // types/env.d.ts declare global { namespace NodeJS { interface ProcessEnv { GLOOD_API_KEY: string; PUBLIC_STORE_DOMAIN: string; PUBLIC_CHECKOUT_DOMAIN: string; NODE_ENV: 'development' | 'production' | 'staging'; } } } export {}; ``` ## Step 3: Configure Content Security Policy Add the Glood domain to your CSP configuration to enable recommendation fetches and event transmission: ```typescript theme={null} // app/root.tsx import { createContentSecurityPolicy } from '@shopify/hydrogen'; export async function loader({context}: LoaderFunctionArgs) { const {nonce, header} = createContentSecurityPolicy({ shop: { checkoutDomain: context.env.PUBLIC_CHECKOUT_DOMAIN, storeDomain: context.env.PUBLIC_STORE_DOMAIN, }, connectSrc: [ 'https://cdn.shopify.com', 'https://*.shopifycloud.com', // Glood v3 headless suite (init, sections, events, recommendations) 'https://storefront.glood.ai', // Glood search v1 API β€” serves the API and events (only needed if you register search()) 'https://search.glood.ai', ], }); return json({ nonce, header }); } export function headers({loaderHeaders}: {loaderHeaders: Headers}) { return { 'Content-Security-Policy': loaderHeaders.get('Content-Security-Policy'), }; } ``` ## Step 4: Initialize Glood Client Create and configure the Glood client in your root layout: ### Basic Setup ```typescript theme={null} // app/root.tsx import { Analytics } from '@shopify/hydrogen'; import { GloodProvider, createGlood } from '@glood/hydrogen'; import { recommendations, search } from '@glood/hydrogen'; import { useLoaderData } from 'react-router'; // Create Glood client outside component to prevent recreation const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', // Replace with your actual domain version: 3, // Headless API version (2 | 3), 3 is the default }) .use(recommendations()) .use(search()); // Search v1 β€” pinned to v1 automatically, independent of the client version export default function App() { const loaderData = useLoaderData(); return ( ); } ``` ### Environment-Specific Setup ```typescript theme={null} // app/root.tsx import { createGlood } from '@glood/hydrogen'; import { recommendations } from '@glood/hydrogen'; // Environment-aware configuration const isDevelopment = process.env.NODE_ENV === 'development'; const isStaging = process.env.NODE_ENV === 'staging'; const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: process.env.PUBLIC_STORE_DOMAIN!, version: 3, // Headless API version (2 | 3), 3 is the default debug: isDevelopment, // Enable debug logging in development apps: isDevelopment ? { // Disable pixels in development recommendations: { endpoint: 'https://storefront.glood.ai', pixel: { enabled: false, endpoint: '', consent: [] }, }, } : undefined, // Use defaults in production }) .use(recommendations()); ``` ## Step 5: Verify Installation ### Check Debug Logs Enable debug mode and check browser console: ```typescript theme={null} const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: 'your-store.myshopify.com', debug: true, // Enable debug logging }); ``` Expected console output: ``` [Glood Debug] Setting up event subscriptions for apps: ['recommendations'] [Glood Debug] Set analytics instance on recommendations app [Glood Debug] App recommendations subscribes to events: ['page_viewed', 'product_viewed', ...] [Glood Debug] All unique event types: ['page_viewed', 'product_viewed', 'cart_viewed', ...] ``` ### Test Event Tracking Navigate through your store and verify events are being tracked: 1. **Visit product page** - Should see `product_viewed` events 2. **View a collection** - Should see `collection_viewed` events 3. **View cart** - Should see `cart_viewed` events 4. **Navigate pages** - Should see `page_viewed` events ### Verify Network Requests In browser DevTools Network tab, look for requests to `https://storefront.glood.ai`: * `POST /api/storefront/v3/headless/init` (session bootstrap on load) * `POST /api/storefront/v3/headless/sections` (recommendation sections) * `POST /api/storefront/v3/headless/events` (analytics and attribution events) (For a `version: 2` client, events go to `POST /api/storefront/event` instead.) ## Complete Implementation Example Here's a complete working example: ```typescript theme={null} // app/root.tsx import { json, type LoaderFunctionArgs, type LinksFunction, type MetaFunction, } from '@shopify/remix-oxygen'; import { Links, Meta, Outlet, Scripts, ScrollRestoration, useLoaderData, } from '@remix-run/react'; import { Analytics, getShopAnalytics, useNonce, createContentSecurityPolicy, } from '@shopify/hydrogen'; import { GloodProvider, createGlood } from '@glood/hydrogen'; import { recommendations } from '@glood/hydrogen'; import favicon from '../public/favicon.ico'; import resetStyles from './styles/reset.css'; import appStyles from './styles/app.css'; // Create Glood client const glood = createGlood({ apiKey: process.env.GLOOD_API_KEY!, myShopifyDomain: process.env.PUBLIC_STORE_DOMAIN!, version: 3, // Headless API version (2 | 3), 3 is the default debug: process.env.NODE_ENV === 'development', }) .use(recommendations()); export const links: LinksFunction = () => { return [ {rel: 'stylesheet', href: resetStyles}, {rel: 'stylesheet', href: appStyles}, { rel: 'preconnect', href: 'https://cdn.shopify.com', }, { rel: 'preconnect', href: 'https://shop.app', }, {rel: 'icon', type: 'image/svg+xml', href: favicon}, ]; }; export const meta: MetaFunction = () => { return [{title: 'Hydrogen | Glood Integration'}]; }; export async function loader({context}: LoaderFunctionArgs) { const {storefront, session, cart, env} = context; // Configure CSP with Glood domains const {nonce, header} = createContentSecurityPolicy({ shop: { checkoutDomain: env.PUBLIC_CHECKOUT_DOMAIN, storeDomain: env.PUBLIC_STORE_DOMAIN, }, connectSrc: [ 'https://cdn.shopify.com', 'https://*.shopifycloud.com', 'https://storefront.glood.ai', 'https://search.glood.ai', // search v1 API + events (if search() is registered) ], }); const analytics = getShopAnalytics({ storefront, publicStorefrontId: env.PUBLIC_STOREFRONT_ID, }); return json( { analytics, nonce, }, { headers: { 'Content-Security-Policy': header, }, } ); } export default function App() { const nonce = useNonce(); const data = useLoaderData(); return ( ); } export function ErrorBoundary() { const error = useRouteError(); if (isRouteErrorResponse(error)) { return (

{error.status} {error.statusText}

{error.data}

); } else if (error instanceof Error) { return (

Error

{error.message}

The stack trace is:

{error.stack}
); } else { return

Unknown Error

; } } ``` ## Common Setup Issues ### Issue: CSP Violations **Symptoms**: Console errors about blocked requests to the Glood domain **Solution**: Ensure the Glood domain is added to `connectSrc`: ```typescript theme={null} connectSrc: [ 'https://cdn.shopify.com', 'https://*.shopifycloud.com', 'https://storefront.glood.ai', // Required (v3 headless suite) ], ``` ### Issue: Missing API Key **Symptoms**: Console error "Glood: apiKey is required" **Solution**: Verify environment variable is set: ```bash theme={null} # Check environment variable echo $GLOOD_API_KEY # Or in your app console.log('API Key:', process.env.GLOOD_API_KEY); ``` ### Issue: Invalid Shopify Domain **Symptoms**: Warning about non-standard domain format **Solution**: Use your actual Shopify domain: ```typescript theme={null} // βœ… Correct format myShopifyDomain: 'your-store.myshopify.com' // ❌ Incorrect formats myShopifyDomain: 'your-store' myShopifyDomain: 'https://your-store.myshopify.com' ``` ### Issue: Analytics Not Working **Symptoms**: No debug logs, no events tracked **Solution**: Verify Analytics wrapper and loaderData: ```typescript theme={null} // βœ… Correct - GloodProvider inside Analytics with loaderData function Root() { const loaderData = useLoaderData(); return ( ); } // ❌ Incorrect - Missing Analytics wrapper and loaderData ``` ### Issue: TypeScript Errors **Symptoms**: TypeScript compilation errors **Solution**: Install type dependencies: ```bash theme={null} npm install --save-dev @types/react @types/node ``` ## Next Steps After successful installation: 1. **[Configure Apps](/for-developers/glood-hydrogen-sdk/configuration)** - Customize app settings 2. **[Set Up CSP](/for-developers/glood-hydrogen-sdk/content-security-policy)** - Detailed CSP configuration 3. **[Review Examples](/for-developers/glood-hydrogen-sdk/examples/basic-setup)** - Implementation patterns 4. **[Load Recommendations](/for-developers/glood-hydrogen-sdk/examples/recommendations)** - Fetch and display sections ## Getting Help If you encounter issues during installation: * πŸ“– [Configuration Guide](/for-developers/glood-hydrogen-sdk/configuration) - Detailed configuration options * πŸ”§ [API Reference](/for-developers/glood-hydrogen-sdk/api-reference/client) - Complete API documentation * πŸ’¬ [GitHub Discussions](https://github.com/LoopClub/glood-hydrogen/discussions) - Community support * πŸ› [Report Issues](https://github.com/LoopClub/glood-hydrogen/issues) - Bug reports and feature requests ## Package Information * **Package Name**: `@glood/hydrogen` * **License**: MIT * **Repository**: [github.com/LoopClub/glood-hydrogen](https://github.com/LoopClub/glood-hydrogen) * **Documentation**: [docs.glood.ai](https://docs.glood.ai) * **Support**: [support@glood.ai](mailto:support@glood.ai) # Loading Recommendations Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/recommendations Fetch and display Glood recommendation sections with full product data in your Hydrogen storefront # Loading Recommendations The SDK fetches the recommendation sections you configure in the Glood dashboard β€” complete with full product data (title, handle, prices, images, options, and variants) β€” so you can render them with your own React components. There are two ways to load recommendations: | Method | Where it runs | Best for | | - | - | - | | `useRecommendations()` hook | Browser (client-side) | Most storefronts β€” simplest integration | | `fetchRecommendationSections()` | Server (Hydrogen route loaders) | SEO-critical pages that need recommendations in the initial HTML | ## Client-Side: useRecommendations Hook Use the hook inside any component rendered under ``. The page URL, locale, and Glood client id are filled in automatically from the browser. > [!NOTE] > > For a v3 client the hook waits for the page-load `/v3/headless/init` call to > settle before fetching sections (staying in `loading` until then), so init runs > first and the sections request carries the init-issued visitor id. No extra > wiring needed β€” this ordering is automatic. ```tsx theme={null} import { useRecommendations } from '@glood/hydrogen'; function ProductRecommendations({ productId }: { productId: string }) { const { sections, loading, error } = useRecommendations({ pageType: 'product_page', productId, // numeric Shopify product id, e.g. '8977367564515' }); if (loading || error) return null; return ( <> {sections.map((section) => (

{section.title}

{section.products.map((product) => ( {product.title} {product.title} {product.price} ))}
))} ); } ``` > [!NOTE] > > Shopify product ids in Hydrogen are GIDs like `gid://shopify/Product/8977367564515`. Pass only the numeric part: `product.id.split('/').pop()`. ### Page Types Every request declares which page the visitor is on. Glood returns the sections configured for that page type in the dashboard: | Page Type | Use On | | - | - | | `home` | Homepage | | `product_page` | Product detail pages (pass `productId`) | | `collection` | Collection pages (pass `collection` id) | | `cart` | Cart page (pass `cartProductIds`) | | `blog` | Blog and article pages | | `order_confirm` | Order confirmation / thank-you page | | `checkout`, `ajax_cart`, `returns`, `404`, `other` | Special pages | ### Hook Result The hook returns everything needed to render and attribute recommendations: ```tsx theme={null} const { sections, // RecommendationSection[] β€” sections with products data, // Full SectionsResponse (request_id, experience, ...) loading, // true while fetching error, // Error | null refetch, // Re-run the request with the same params trackRender, // Attribution helpers (see below) trackView, trackClick, trackAddToCart, } = useRecommendations({ pageType: 'product_page', productId }); ``` ### Deferring the Request Pass `{ skip: true }` as the second argument to wait until required params are ready: ```tsx theme={null} const { sections } = useRecommendations( { pageType: 'product_page', productId }, { skip: !productId }, ); ``` ## Server-Side: fetchRecommendationSections For SSR, fetch recommendations inside a Hydrogen route loader. Pass `pageUrl` and `locale` explicitly β€” there is no browser context on the server: ```tsx theme={null} import { fetchRecommendationSections } from '@glood/hydrogen'; import { useLoaderData } from 'react-router'; export async function loader({ request, params, context }) { const recommendations = await fetchRecommendationSections( { apiKey: context.env.GLOOD_API_KEY, myShopifyDomain: 'your-store.myshopify.com', }, { pageType: 'product_page', pageUrl: request.url, locale: 'en-US', productId: params.productId, }, ).catch(() => null); // Never let recommendations break the page return { recommendations }; } export default function ProductPage() { const { recommendations } = useLoaderData(); return ( <> {recommendations?.sections.map((section) => (

{section.title}

{/* render section.products */}
))} ); } ``` > [!WARNING] > > Always wrap the call in a `.catch()` (or try/catch) inside loaders. A recommendations outage should degrade gracefully, not 500 your page. ### Rendering SSR sections with attribution The loader only fetches the data β€” you still render and track it in a client component. Because you are **not** using the `useRecommendations` hook here, the hook's `trackRender`/`trackView`/`trackClick`/`trackAddToCart` helpers aren't available; instead get the recommendations app from [`useGloodAnalytics()`](/for-developers/glood-hydrogen-sdk/api-reference/components#usegloodanalytics) and call its attribution methods directly. Two SSR-specific details are handled below: * **Persist the assigned `experience`** to `localStorage` yourself. `fetchRecommendationSections` only persists it in the browser, and the loader runs on the server β€” so pixel/attribution events won't carry it unless you save it client-side. * **Fire `trackRender`** once the component mounts in the browser (the data is already in the SSR HTML, but attribution events are always sent client-side). ```tsx theme={null} import { useEffect, useRef } from 'react'; import { useGloodAnalytics } from '@glood/hydrogen'; export function GloodRecommendations({ data, pageType, productId }) { const client = useGloodAnalytics(); const app = client?.getApp('recommendations'); const rendered = useRef(new Set()); const sections = data?.sections ?? []; const buildTrack = (section, products) => ({ section: String(section.id), sectionServeId: section.section_serve_id, // from the API response requestId: data?.request_id, page: pageType, parent: productId ? { productId } : undefined, ...(products ? { products } : {}), }); // Persist the SSR-assigned experience so pixel events carry it useEffect(() => { if (!data?.experience) return; try { window.localStorage.setItem('gai_s_e', String(data.experience)); } catch { // ignore storage errors } }, [data]); // glood:section:render β€” once per section useEffect(() => { if (!app) return; sections.forEach((section) => { if (rendered.current.has(section.section_serve_id)) return; rendered.current.add(section.section_serve_id); app.trackRender(buildTrack(section)); }); }, [app, sections]); return ( <> {sections.map((section) => (

{section.title}

{section.products.map((product) => { const track = buildTrack(section, [ { productId: String(product.product_id), quantity: 1 }, ]); return ( app?.trackClick(track)} > {product.title} {product.title} {product.price} ); })}
))} ); } ``` Render it with the loader data (it's already in the initial HTML β€” no client fetch, no layout shift): ```tsx theme={null} export default function ProductPage() { const { recommendations } = useLoaderData(); return ( ); } ``` > [!NOTE] > > Unlike the client-side hook, an SSR loader does not run `/v3/headless/init` and cannot read the browser's `_glood_user_id` cookie. To attribute SSR requests to a returning visitor, parse the id from the incoming request cookies and pass it explicitly as `userId` (and `clientId`) to `fetchRecommendationSections`. ## Attribution Tracking To attribute recommendation performance (views, clicks, and add-to-carts tied back to revenue in Glood analytics), fire the attribution helpers at the right moments. Each takes a `SectionTrack` object that links the interaction to the exact section render via `sectionServeId`: ```tsx theme={null} function ProductRecommendations({ productId }) { const { sections, data, trackRender, trackClick, trackAddToCart } = useRecommendations({ pageType: 'product_page', productId }); return sections.map((section) => { const baseTrack = { section: String(section.id), sectionServeId: section.section_serve_id, // from the API response requestId: data?.request_id, page: 'product_page', parent: { productId }, }; return (
trackRender(baseTrack)} >

{section.title}

{section.products.map((product) => ( trackClick({ ...baseTrack, products: [{ productId: String(product.product_id) }], }) } > {product.title} ))}
); }); } ``` | Helper | Event Sent | When to Call | | - | - | - | | `trackRender(track)` | `glood:section:render` | Section is rendered in the DOM | | `trackView(track)` | `glood:section:view` | Section scrolls into the viewport | | `trackClick(track)` | `glood:section:click` | Visitor clicks a recommended product | | `trackAddToCart(track)` | `glood:section:add_to_cart` | Visitor adds a recommended product to cart | > [!NOTE] > > Standard events (`page_viewed`, `product_added_to_cart`, etc.) are sent automatically by `GloodProvider` β€” you never emit those manually. Attribution helpers are the only events you call yourself, because only your UI knows when a recommendation is clicked. ## Experience Persistence The sections API assigns each visitor an A/B **experience**. The SDK automatically persists the assigned experience id to `localStorage` (key `gai_s_e`) after every fetch, and every pixel event carries it β€” so all analytics segment correctly by experience without any work on your side. ## Error Handling Failed requests throw (or surface via the hook's `error`) a `GloodApiError` carrying the HTTP status and response body: ```tsx theme={null} import { GloodApiError } from '@glood/hydrogen'; try { await fetchRecommendationSections(options, params); } catch (error) { if (error instanceof GloodApiError) { console.error(error.status, error.body); // e.g. 401, { error: 'Invalid authentication' } } } ``` Common failures: | Status | Cause | | - | - | | `401` | Wrong `apiKey`, or the key doesn't match `myShopifyDomain` | | `400` | Invalid params (bad `pageType`, missing `pageUrl`/`locale`), or shop plan not set up | | CSP error in console | `https://storefront.glood.ai` missing from your `connect-src` β€” see [Content Security Policy](/for-developers/glood-hydrogen-sdk/content-security-policy) | Empty `sections: []` with a `200` is not an error β€” it means no sections are enabled for that page type in the Glood dashboard (or targeting rules excluded them). ## See Also * [Recommendations API Reference](/for-developers/glood-hydrogen-sdk/api-reference/recommendations-api) - Full signatures, parameters, and return types * [Recommendations Example](/for-developers/glood-hydrogen-sdk/examples/recommendations) - Complete working page * [TypeScript Types](/for-developers/glood-hydrogen-sdk/api-reference/types) - `SectionsResponse`, `RecommendationSection`, `SectionProduct` * [Content Security Policy](/for-developers/glood-hydrogen-sdk/content-security-policy) - Required CSP entries # Search & Discovery Source: https://docs.glood.ai/for-developers/glood-hydrogen-sdk/search Fetch config, run instant + full search, render filters, do image search, and attribute interactions with the Glood Hydrogen Search SDK # Search & Discovery The SDK wraps Glood's headless **Search v1** APIs so you can build a fully custom search experience β€” instant (type-ahead) search, a full results page, faceted filters, and visual (image) search β€” rendering everything with your own React components. > [!NOTE] > > Search is a **v1** headless API on its own host (`https://search.glood.ai`), independent of the > recommendations app's version. Registering `search()` pins it to v1 automatically β€” you can > run search (v1) and recommendations (v3) on the same client. ## Setup Register the search app on your Glood client, alongside (or instead of) recommendations: ```tsx theme={null} // app/lib/glood.ts import { createGlood, search } from '@glood/hydrogen'; export const glood = createGlood({ apiKey: 'gl_sf_your_storefront_token', myShopifyDomain: 'your-store.myshopify.com', debug: import.meta.env.DEV, }).use(search()); ``` Then wrap your app in `` (inside Shopify's `Analytics.Provider`) exactly as for recommendations β€” see [Installation](/for-developers/glood-hydrogen-sdk/installation). > [!WARNING] > > Add `https://search.glood.ai` to your CSP `connectSrc`, or the browser blocks every search > fetch and event. See [Content Security Policy](/for-developers/glood-hydrogen-sdk/content-security-policy). ## Session bootstrap When `search()` is registered, `GloodProvider` fires the search **init** call once on mount β€” it resolves the visitor, loads their history (browsed / cart / purchased product ids), and returns a lean feature-flag config plus the storefront token and a fresh `visit_id`. You don't wire this up: `useSearch` and `useInstantSearch` automatically wait for it to settle before firing. Read the result with `useSearchInit()` (or `useSearchInitReady()` for the settled flag): ```tsx theme={null} import { useSearchInit } from '@glood/hydrogen'; function Recents() { const init = useSearchInit(); // SearchInitResponse | null return ; } ``` For SSR / non-React use, call the standalone `fetchSearchInit(options, params?)` directly. ## Loading the config The config carries feature flags, filter definitions, the shop currency/locale, and the Shopify storefront token. Fetch it once (e.g. in a layout) with `useSearchConfig`: ```tsx theme={null} import { useSearchConfig } from '@glood/hydrogen'; function SearchProvider() { const { config, loading, error } = useSearchConfig(); if (loading || error || !config) return null; const minChars = config.config.minimum_type_ahead_input_count; // e.g. 2 // ...expose config to your search UI } ``` ## Instant (type-ahead) search `useInstantSearch` runs a type-ahead query and returns products, collections, pages, articles, keyword suggestions and autocorrect. On an empty / too-short query the response carries a `trending` block instead. Pass `{ skip }` to hold fetching until the input clears the minimum length: ```tsx theme={null} import { useState } from 'react'; import { useInstantSearch } from '@glood/hydrogen'; function SearchBox() { const [term, setTerm] = useState(''); const { products, suggestions, collections, data, loading } = useInstantSearch( { query: term }, { skip: term.length < 2 }, ); return (
setTerm(e.target.value)} placeholder="Search…" /> {data?.corrected_query &&

Did you mean {data.corrected_query}?

} {loading && …}
    {suggestions.map((s) => (
  • {s.text}
  • ))}
{products.map((p) => ( {p.title} {p.title} {p.display_price ?? p.price} ))}
); } ``` > [!NOTE] > > The `products`, `suggestions`, `collections` and `pages` return values are convenience > accessors. The full response β€” including `articles`, `autocorrect`, `trending` and > `metadata` β€” is on `data`. ## Full search results `useSearch` runs a full hybrid (text + vector) product search with applied facets, sort and page-based pagination. It also returns attribution helpers (see below): ```tsx theme={null} import { useSearch } from '@glood/hydrogen'; function SearchResults({ query }: { query: string }) { const { products, data, loading, error, trackResultClick } = useSearch({ query, sort: 'relevance', facets: [{ key: 'color', operator: 'or', value: ['red'] }], pagination: { page: 1, limit: 24 }, options: { includeFacets: true }, }); if (loading) return

Searching…

; if (error) return

{error.message}

; return ( <>

{data?.pagination.total} results

); } ``` ### Sort & pagination `sort` accepts `relevance` (default), `title_asc`, `title_desc`, `price_asc`, `price_desc`, `best_selling`, `oldest`, `newest`. The response `pagination` block gives `total`, `page`, `limit`, `total_pages`, `has_next_page`/`has_prev_page` and `next_page`/`prev_page`. ## Filters & aggregations There are two facet endpoints, exposed via the `SearchApp` (or the standalone functions): | Call | Returns | | - | - | | `filters()` / `fetchFilters` | DB-driven facet **definitions** (labels, value lists, swatches) β€” no counts | | `fetchFilterAggregations` | **Live counts** for a query + applied filters | ```tsx theme={null} import { useGloodAnalytics, fetchFilterAggregations } from '@glood/hydrogen'; // Facet definitions (structure) const app = useGloodAnalytics()?.getApp('search'); const { facets } = await app.filters({ collection: '123' }); // Live counts (numbers) β€” standalone, works in loaders too const agg = await fetchFilterAggregations( { apiKey, myShopifyDomain }, { query: 'shoe', appliedFilters: [{ key: 'color', value: ['red'] }], facets: [{ key: 'size' }] }, ); ``` Render the definitions from `filters()` for stable labels/order, and merge in the live `aggregations` counts as the query/selection changes. ## Image (visual) search Pass exactly one image source β€” a base64 image, a `data:` URL, or an http(s) URL: ```tsx theme={null} import { useGloodAnalytics } from '@glood/hydrogen'; async function searchByImage(file: File) { const app = useGloodAnalytics()?.getApp('search'); const dataUrl = await toDataUrl(file); // FileReader.readAsDataURL const res = await app.imageSearch({ image: dataUrl, pagination: { limit: 24 } }); return res.products; } ``` > [!NOTE] > > Images are strictly validated server-side: `jpeg` / `png` / `webp` only, 1 KB–5 MB, > 100Γ—100 to 4096Γ—4096 px. Anything else returns `400`. > [!NOTE] > > Image search always runs against the app's **`controlEndpoint`** (the non-edge host), because the > vision/embedding pipeline it needs isn't available on regional edges. If you point `endpoint` at an > edge, image search stays on the control plane automatically β€” see > [Configuration β†’ Edge vs. non-edge routing](/for-developers/glood-hydrogen-sdk/configuration#edge-vs-non-edge-routing-controlendpoint). ## Server-side (SSR) To render search results in the initial HTML, call the standalone fetchers in a Hydrogen route loader. Pass credentials explicitly β€” there is no browser context on the server: ```tsx theme={null} import { fetchSearchResults } from '@glood/hydrogen'; export async function loader({ request, context }) { const url = new URL(request.url); const query = url.searchParams.get('q') ?? ''; const results = await fetchSearchResults( { apiKey: context.env.GLOOD_API_KEY, myShopifyDomain: 'your-store.myshopify.com' }, { query, pagination: { page: 1, limit: 24 } }, ).catch(() => null); // never let search break the page return { results }; } ``` Every standalone fetcher (`fetchSearchConfig`, `fetchInstantSearch`, `fetchFilters`, `fetchFilterAggregations`, `fetchSearchResults`, `fetchImageSearch`, `sendSearchEvent`) takes `(options, params)` and is isomorphic. ## Events & attribution Two kinds of events flow to the search backend: 1. **Standard Shopify events** (`product_viewed`, `search_submitted`, `product_added_to_cart`, …) are forwarded **automatically** by `GloodProvider` once `search()` is registered β€” no wiring required. Narrow them with `search({ events: ['search_submitted', 'product_added_to_cart'] })`. 2. **Custom `glood:search:*` attribution events**, which only your UI can time, are sent via the track helpers: | Helper | Event | Call when | | - | - | - | | `trackSearch(track)` | `glood:instant_search_triggered` | A search / results set is rendered | | `trackResultView(track)` | `glood:search_result_rendered` | A result enters the viewport | | `trackResultClick(track)` | `glood:search_result_clicked` | A result is clicked | | `trackAddToCart(track)` | `glood:search:add_to_cart` | A result is added to cart | | `trackFilter(track)` | `glood:search_filter_updated` | A facet is applied/changed | The helpers are returned by `useSearch` and also live on the `SearchApp` (`useGloodAnalytics().getApp('search')`) for SSR / non-hook use. Each takes a `SearchTrack` (`request_id`, `search_term`, `search_type`, `products`, `filters`, `source`, `page_type`). For SSR / non-React contexts, send a single event directly with [`sendSearchEvent(options, event)`](/for-developers/glood-hydrogen-sdk/api-reference/search-api#sendsearchevent). > [!NOTE] > > Both kinds of events are ingested at the app's **`controlEndpoint`** (non-edge), not `endpoint`. > This keeps event ingestion on the control plane even when `endpoint` points at a regional edge β€” > see [Configuration β†’ Edge vs. non-edge routing](/for-developers/glood-hydrogen-sdk/configuration#edge-vs-non-edge-routing-controlendpoint). ## Error handling Fetchers throw (and the hooks surface via `error`) a `GloodApiError` carrying the HTTP status and response body: ```tsx theme={null} import { GloodApiError } from '@glood/hydrogen'; try { await fetchSearchResults(options, params); } catch (error) { if (error instanceof GloodApiError) { console.error(error.status, error.body); // e.g. 401, { error: 'Invalid authentication' } } } ``` | Status | Cause | | - | - | | `401` | Wrong `apiKey`, or the key doesn't match `myShopifyDomain` | | `400` | Invalid params, or shop plan not set up (`{ error: 'Select a plan' }`) | | `403` | The shop's plan requires a charge that isn't active | | CSP error | `https://search.glood.ai` missing from `connectSrc` β€” see [Content Security Policy](/for-developers/glood-hydrogen-sdk/content-security-policy) | ## See Also * [Search API Reference](/for-developers/glood-hydrogen-sdk/api-reference/search-api) β€” full signatures, parameters, returns * [Search Example](/for-developers/glood-hydrogen-sdk/examples/search) β€” complete working route * [Event System](/for-developers/glood-hydrogen-sdk/api-reference/event-system) β€” how events are transmitted * [Content Security Policy](/for-developers/glood-hydrogen-sdk/content-security-policy) β€” required CSP entries # Load a Section into a Custom Location Source: https://docs.glood.ai/for-developers/how-to-load-a-section-into-a-custom-location Use window.glood.loadSection to render a single recommendation section into any element β€” including DOM that does not exist when the page loads, such as a modal injected on trigger. By default, Glood decides where a section goes: into its app block container, into the location configured on the section, or into a sensible fallback such as `
`. That works when the destination exists in the page's HTML. It does not work when the destination is created at runtime β€” a modal opened on a button click, a drawer rendered by your theme's JS, a tab panel mounted on demand. `window.glood.loadSection` covers that case: you tell Glood which section to render and exactly where to put it. ## API ### `window.glood.loadSection(sectionId, target)` Renders one section into `target`. | Parameter | Type | Required | Description | | - | - | - | - | | `sectionId` | `number` | Yes | The section's ID, from the Glood admin URL when editing the section. | | `target` | `Element` \| `string` | No | Where to put it. Accepts a DOM element or a selector string. Omit it to use the section's normal placement. | The `target` string is resolved the same way section locations are: it is tried as a tag name, class name, element ID, `querySelector`, and finally an XPath expression. `'#modal-body'`, `'.modal-body'`, and `'modal-body'` all work. ### `window.glood.unloadSection(sectionId)` Removes the section that `loadSection` placed and stops it rendering. Copies of the same section rendered normally elsewhere on the page are left alone. ## Basic usage ```javascript theme={null} // Into an element you already have a reference to window.glood.loadSection(4231, document.getElementById('my-modal-body')) // Into a selector window.glood.loadSection(4231, '#my-modal-body') // Using the section's configured placement (no target) window.glood.loadSection(4231) ``` Always feature-detect, the same way you would for `loadPage`: ```javascript theme={null} if (window.glood && typeof window.glood.loadSection === 'function') { window.glood.loadSection(4231, '#my-modal-body') } ``` ## Loading into a modal The target must exist in the DOM at the moment you call `loadSection`. Inject your modal first, then load into it. ```javascript theme={null} document.querySelector('#open-recommendations').addEventListener('click', () => { // 1. Inject the modal so the target exists document.body.insertAdjacentHTML('beforeend', `
`) // 2. Now load the section into it if (typeof window.glood?.loadSection === 'function') { window.glood.loadSection(4231, '#my-modal-body') } }) document.addEventListener('click', (e) => { if (!e.target.matches('.my-modal__close')) return window.glood?.unloadSection?.(4231) document.querySelector('.my-modal')?.remove() }) ``` Calling `loadSection` again for the same section and target re-renders it in place β€” it does not stack up duplicates. So re-opening the modal simply works, and you do not have to call `unloadSection` first. > [!NOTE] > > Re-rendering is cheap. The section and product responses are cached in memory for 5 minutes, so re-opening a modal within that window makes no additional network requests. ## Knowing when the section has rendered `loadSection` returns immediately β€” the section renders asynchronously once its data arrives. To run code after it lands, listen for the `glood:section:rendered` window event: ```javascript theme={null} window.addEventListener('glood:section:rendered', (event) => { const section = event.detail.section if (section.id !== 4231) return console.log('section rendered with', section.products.length, 'products') // e.g. reposition or reveal your modal now that it has content }) ``` ## Running alongside the normal placement Passing a `target` for a section that is **already rendered on the page** gives you a second, fully independent copy. The existing copy is not moved, removed, or re-rendered. Both stay live, each with its own add-to-cart handlers and its own event tracking: | Action | Copy on the page | Copy in your target | | - | - | - | | `loadSection(id, target)` | untouched | created | | `loadSection(id, target)` again | untouched | replaced in place, never duplicated | | `unloadSection(id)` | untouched | removed | | `reloadPage(...)` or a normal re-render | re-rendered | untouched | This costs one extra sections request, since it is fetched by ID rather than as part of the page's batch. The product data is shared from cache. > [!WARNING] > > Two visible placements of one section report **two impressions** β€” each copy fires its own `section:render` analytics event and its own `glood:section:rendered` window event. If you show the same section both inline and in a modal, expect its impression count to reflect both. Use different sections for the two placements if you need them measured separately. > [!WARNING] > > **Do not call `loadSection(id)` without a target for a section that is already on the page.** With no target the section uses its normal placement, which replaces the existing copy rather than adding a second one β€” so you end up with two renderers writing to the same spot and clearing each other's markup. Depending on timing the section can disappear entirely. If a section already renders automatically, `loadSection` without a target adds nothing. ## Requirements and limitations > [!NOTE] > > **The section must belong to the current page type.** Glood resolves sections against the page you are on, so a section configured for the cart page cannot be loaded on a product page β€” `loadSection` will find nothing and log an error. Configure the section on the page type where you intend to load it. Beyond that, the section must be **enabled** and part of the experience assigned to the visitor. It does **not** need an app block placed on the page: `loadSection` requests the section by ID, which bypasses the "requires app block" restriction. That makes "requires app block" a useful setting for sections you only ever want to show through `loadSection` β€” it keeps them out of the automatic page render, so the modal copy is the only one. ## Troubleshooting Open your browser console β€” every failure below logs an error prefixed with `GLOOD.AI:ERROR`. | Console message | Cause | | - | - | | `loadSection target not found β€” skipping insert` | The target did not resolve. Check the modal is in the DOM *before* you call `loadSection`. The section is deliberately not rendered anywhere else rather than being dropped into an unintended container. | | `loadSection expects a numeric section id` | `sectionId` was missing, `0`, or not a number. | | `Failed to fetch section with id … from backend` | The section is disabled, not on the current page type, or not in the visitor's experience. | | Nothing at all happens | `window.glood.loadSection` is undefined β€” the Glood app embed is not enabled, or the recommendations bundle has not initialised yet. | ## Related * [Reloading mini cart sections](/for-developers/how-to-reload-mini-cart-sections-using-javascript) β€” `loadPage` / `unloadPage` for whole page types. ## Support If you need help placing a section in a custom location, contact our support team at [support@glood.ai](mailto:support@glood.ai) # How to reload mini cart sections using javascript Source: https://docs.glood.ai/for-developers/how-to-reload-mini-cart-sections-using-javascript This comprehensive guide explains how to reload mini cart sections in your Glood application using JavaScript. ## Overview The Glood framework offers two primary JavaScript methods for managing mini cart sections: * `window.glood.loadPage('ajax_cart')` - Loads or reloads the mini cart section * `window.glood.unloadPage('ajax_cart')` - Unloads the mini cart section These methods allow you to update cart content based on user interactions, server responses, or application state changes. ## Prerequisites Before implementing mini cart reloading functionality, ensure that: 1. **Glood Framework**: The Glood framework is properly loaded on your page 2. **Global Object**: The `window.glood` object is available and accessible 3. **Section Configuration**: The `ajax_cart` section is properly configured in your application ## Basic Implementation ### Simple Reload You can reload the mini cart section by using this code in your section template: ```javascript theme={null} if (window.glood && shouldLoadAjaxCart && typeof window.glood.loadPage === 'function') { window.glood.loadPage('ajax_cart'); } ``` ### Basic Unload To unload the mini cart section: ```javascript theme={null} if (window.glood && shouldUnloadAjaxCart && typeof window.glood.unloadPage === 'function') { window.glood.unloadPage('ajax_cart'); } ``` ## Conditional Load/Unload For more advanced scenarios where you need to conditionally load or unload the mini cart section based on specific conditions, use this code: ```javascript theme={null} if ( window.glood && shouldLoadAjaxCart && typeof window.glood.loadPage === 'function' ) { window.glood.loadPage('ajax_cart') } else if ( shouldUnloadAjaxCart && typeof window.glood.unloadPage === 'function' ) { window.glood.unloadPage('ajax_cart') } ``` This code checks for the Glood framework availability and your custom conditions (`shouldLoadAjaxCart` and `shouldUnloadAjaxCart`) to either load or unload the mini cart section accordingly. ## Support If you need help with setting up or customizing mini cart section reloading, contact our support team at [support@glood.ai](mailto:support@glood.ai) # Integrations Source: https://docs.glood.ai/for-developers/integrations/introduction Learn about available integrations for Glood.AI recommendations # Integrations Glood.AI provides several integrations to enhance your product recommendations with additional functionality. ## Available Integrations ### Product Ratings Add product ratings and reviews from Judge.me to your recommendation sections. This helps build trust and provides social proof for recommended products. [Learn more about Product Ratings integration β†’](/for-developers/integrations/product-ratings) ### Quick View Enable quick product previews directly from recommendation sections. This allows customers to view product details without leaving the current page. [Learn more about Quick View integration β†’](/for-developers/integrations/quick-view) ### Wishlist Add wishlist functionality to products in recommendation sections. This lets customers save products for later directly from recommendations. [Learn more about Wishlist integration β†’](/for-developers/integrations/wishlist) ## Implementation Overview Each integration can be enabled and configured through: 1. Dashboard settings in your Glood.AI admin 2. Template customization using provided tags and filters 3. Optional custom styling to match your theme ## Getting Started Choose an integration from the sidebar to learn more about its specific implementation details and requirements. For general template customization, see the [Section Template](/for-developers/section-template/introduction) documentation. # Product Ratings Integration Source: https://docs.glood.ai/for-developers/integrations/product-ratings Learn how to integrate product ratings and reviews with Glood.AI recommendations # Product Ratings Integration This guide explains how to integrate Judge.me product ratings and reviews with Glood.AI recommendations. ## Overview Product ratings integration allows you to display review stars and ratings from Judge.me within your Glood.AI recommendation sections. ## Supported Review Apps Currently, we support: * Judge.me ## Implementation Steps ### 1. Enable Product Reviews Integration First, enable the product reviews integration in your Glood.AI dashboard: 1. Go to **Settings** in your Glood.AI admin 2. Navigate to the **Integrations** tab 3. Find **Judge.me** in the Product Reviews section 4. Click **Enable** ### 2. Add Review Tag to Template Add the `product_ratings` tag to your section template where you want the reviews to appear: ```liquid theme={null}
{{ product.title }}

{{ product.title }}

{{ product.price | money_formatter: glood }}
{% product_ratings product_id: product.id %}
``` The `product_ratings` tag will automatically: * Generate the appropriate Judge.me widget markup * Handle the review data fetching * Display review stars and rating count ### Example Output When properly configured, the tag will generate HTML like this: ```html theme={null}
``` ## Troubleshooting Common issues and solutions: * **Reviews not showing**: Verify that Judge.me is properly installed and configured in your store * **Missing ratings**: Ensure the product has reviews in Judge.me * **Widget not loading**: Check that Judge.me scripts are properly loaded in your theme ## Best Practices 1. Always test the integration with products that have reviews 2. Consider loading performance when adding reviews to many products 3. Provide fallback content when reviews are not available 4. Test the integration across different devices and screen sizes For more details on available tags and configuration options, see the [Template Tags](/for-developers/section-template/tags) documentation. # Quick View Integration Source: https://docs.glood.ai/for-developers/integrations/quick-view Learn how to integrate quick view functionality with Glood.AI recommendations # Quick View Integration This guide explains how to integrate quick view functionality with Glood.AI recommendations. ## Overview Quick view integration allows customers to quickly preview products from recommendation sections without leaving the current page. ## Implementation Steps Coming soon... # Wishlist Integration Source: https://docs.glood.ai/for-developers/integrations/wishlist Learn how to integrate wishlist functionality with Glood.AI recommendations # Wishlist Integration This guide explains how to integrate wishlist functionality with Glood.AI recommendations. ## Overview Wishlist integration allows you to add wishlist functionality to products displayed in your Glood.AI recommendation sections. ## Implementation Steps Coming soon... # Developer Guide Source: https://docs.glood.ai/for-developers/introduction Advanced integration guide for developers implementing Glood.AI # Developer Guide Welcome to the Glood.AI developer documentation. This guide covers advanced integration topics and requires familiarity with: * Shopify Liquid * HTML/CSS * JavaScript * REST APIs ## Topics Covered ### Template Customization Learn how to customize the appearance and behavior of Glood.AI recommendation sections using our template specification system. ### Programmatic Section Placement Understand how to dynamically insert and position Glood.AI sections in your store using code rather than the visual editor. ### Headless Integration Integrate Glood.AI recommendations into headless storefronts using our REST APIs. ### Hydrogen Support Step-by-step guide for implementing Glood.AI in Shopify Hydrogen stores. > [card] [Glood Hydrogen SDK](/for-developers/glood-hydrogen-sdk) > > Complete TypeScript SDK for seamless Glood integration with Shopify Hydrogen storefronts ### Custom Events Learn how to send custom tracking events to enhance Glood.AI's recommendation engine. ## Prerequisites Before diving into the developer documentation, you should: * Have Glood.AI installed on your Shopify store * Be familiar with Shopify theme development * Understand basic web development concepts * Have access to your store's theme code ## Getting Help If you run into any technical issues: * Check our API Reference documentation * Contact our developer support at [support@glood.ai](mailto:support@glood.ai) * Join our developer community Let's get started with implementing advanced Glood.AI features in your store! # Code Source: https://docs.glood.ai/for-developers/section-template/code Learn about the core components of a section template # Template Code Every section template in Glood.AI consists of several core files that work together to create a complete recommendation section. We use the [liquidJS](https://liquidjs.com/api/classes/Liquid.html) library to render Liquid code at the client side. For any queries regarding Liquid-specific data structures, filters, or tags, please refer to the [Shopify Liquid documentation](https://shopify.dev/docs/api/liquid/objects). ## Core Parts ### 1. Section Template The main template that defines the HTML structure and dynamic content rendering. It uses data structures defined in the [Object Definitions](/for-developers/section-template/schemas#object-definitions). #### Dynamic Implementation * Uses [translations object](/for-developers/section-template/schemas#translations-object) for text content * Accesses [glood object](/for-developers/section-template/schemas#glood-object) for store configuration * Renders [product data](/for-developers/section-template/schemas#product-array) in templates * Applies [template settings](/for-developers/section-template/schemas#template-object) for styling #### Liquid Filters Our filters used in the template: | Filter | Purpose | Parameters | Output | Example | | - | - | - | - | - | | `money` | Price formatting | Number/String, `money_format`: Override default format | Formatted price | `19.99 \| money` β†’ `"$19.99"` | | `optimize_image` | Image optimization | URL, `width`: Desired width, `height`: Desired height, `crop`: Crop mode | Optimized URL | `product.image \| optimize_image: width: 300, height: 300` | | `tracking_url` | Add tracking | Product, `section` (required): Section context, `ref_product_id`: Reference product ID | URL with params | `product \| tracking_url: section` | | `section_discount` | Format discount | Section, `money_format`: Price format, `locale`: Language code | Discount string | `section \| section_discount: money_format: shop.money_format` | ### 2. JS Hooks The JavaScript hooks system provides a powerful way to customize and extend section behavior. These hooks are called at specific points in the section's lifecycle, allowing you to implement custom functionality and handle various events. #### Core callBacks available | Method Name | Parameters | Description | Return | | - | - | - | - | | `initSwiper` | `(Swiper, templateSettings, container, params, defaultSettings, utils)` | Initializes carousel functionality | `Swiper instance` | | `onSectionInit` | `(args, cb, gloodUtils)` | Called when section initializes | `void` | | `onSectionRenderComplete` | `(args, utils)` | Called after section rendering | `void` | | `onVariantChange` | `(args, utils)` | Handles variant selection | `void` | | `onSwatchChange` | `(args, utils)` | Handles swatch selection | `void` | | `validateCartOperation` | `(payload, recommendation, utils)` | Validates cart operations | `{payload, error}` | | `onCartOperationComplete` | `(args, utils)` | Called after cart operation | `void` | | `onProductDataReceived` | `(args, utils)` | Handles product data | `void` | | `getProductDetailsQuery` | `(recommendation, glood)` | Returns GraphQL query | `string` | | `transformProductData` | `(product, recommendation)` | Transforms product data | `object` | | `onSectionRendered` | `(section, products)` | Fired when section is fully rendered | `void` | | `onProductClick` | `(section, products, productId)` | Fired when product is clicked | `void` | | `onAddToCart` | `(section, products, items, response)` | Fired on successful cart addition | `void` | | `onVariantSelected` | `(section, products, productId, variantId)` | Fired when variant is selected | `void` | #### Example Implementation ```javascript theme={null} // Example: Carousel Initialization Hook initSwiper: (Swiper, templateSettings, container, params) => { const carouselContainer = container.querySelector('._gai-crz-cnt'); if (!carouselContainer) return; return new Swiper(carouselContainer, { slidesPerView: templateSettings.breakpoints.small.cardsPerView, spaceBetween: templateSettings.breakpoints.small.gutter }); } // Example: Variant Change Hook onVariantChange: (args, utils) => { const { variant, product, container } = args; const priceElement = container.querySelector('._gai-prod-prc'); if (priceElement && variant.price) { priceElement.textContent = utils.formatMoney(variant.price); } } ``` ### 3. CSS Template The CSS template system provides a flexible way to style your recommendation sections. It uses Liquid templating for dynamic styling based on section settings and configuration. Both section template and CSS template have access to the same template object. For a complete reference of available objects and their structure, see [Template Objects](/for-developers/section-template/schemas#object-definitions). #### Structure and Organization The CSS is organized by components and breakpoints: * Base styles for mobile-first approach * Tablet styles (default: 768px) * Desktop styles (default: 1024px) **NOTE:** 1. The CSS follows a mobile-first approach, where base styles are written for mobile devices and then progressively enhanced for larger screens through media queries. This ensures optimal performance and maintainability while providing a solid foundation for responsive design. 2. These breakpoint values are customizable through the template settings. For detailed configuration options, see [`settings.breakpoints[].screenSize`](/for-developers/section-template/schemas#template-object) in the Template Object documentation. #### CSS Class Reference | Class Name | Purpose | Properties Controlled | Example Usage | | - | - | - | - | | `._gai-grid` | Main product grid container | - Grid layout (`grid-template-columns`) - Gap between items - Responsive columns | Controls overall product grid layout | | `._gai-sec-tit` | Section title styling | - Font size - Text alignment - Line clamping - Display properties - Webkit box orientation | Main section heading appearance | | `._gai-prod-card` | Individual product card | - Background color - Font family - Max width (for bundle layout) | Container for each product | | `._gai-prod-img` | Product image container | - Aspect ratio - Object-fit | Product image display | | `._gai-prod-img-wrap` | Image wrapper | - Aspect ratio | Controls image container proportions | | `._gai-prod-tit` | Product title | - Color - Font weight - Line clamping - Text alignment - Font size - Font family | Product name styling | | `._gai-prod-vndr` | Vendor name | - Font size - Display properties | Brand/vendor name display | | `._gai-prod-vndr--above-title` | Vendor name above title | - Display (block/none) | Vendor positioning above title | | `._gai-prod-vndr--below-title` | Vendor name below title | - Display (block/none) | Vendor positioning below title | | `._gai-prod-prc` | Product price | - Color - Font family - Font size | Main price display | | `._gai-prod-prc--compare-at` | Compare-at price | - Color - Display - Visibility conditions | Original/compare price styling | | `._gai-atc-btn` | Add to cart button | - Background color - Text color - Border - Border radius - Disabled state | Add to cart button styling | | `._gai-dis-cnt` | Discount container | - Justification - Background color - Display (flex/none) | Discount information wrapper | | `._gai-dis-txt` | Discount text | - Color - Font size | Discount amount/percentage text | | `._gai-dis` | Discount badge | - Background color - Text color - Opacity | Discount label styling | | `._gai-container` | Main section container | - Background color | Section wrapper styling | | `._gai-bundle-products` | Bundle products grid | - Grid template columns | Layout for bundled products | | `._gai-skl-atc` | Skeleton add to cart | - Display visibility | Loading state for add to cart | | `._gai-bndl-sec` | Bundle section | - Justify content | Bundle section layout | | `._gai-amz-tit` | Amazon bundle title | - Text alignment | Title for Amazon-style bundles | #### Label Classes Special classes for product status and badges: | Class Name | Purpose | Customizable Properties | | - | - | - | | `._gai-oos` | Out of stock badge | - Background color - Text color | | `._gai-bestseller` | Bestseller badge | - Background color - Text color | | `._gai-new` | New product badge | - Background color - Text color | | `._gai-trending` | Trending item badge | - Background color - Text color | #### Responsive Behavior The code includes media queries for different screen sizes: ```scss theme={null} /* Mobile (default) */ [data-gai-section-id="{{ section_id }}"] ._gai-grid { grid-template-columns: repeat({{- settings.breakpoints.small.cards_per_view -}}, 1fr); gap: {{ settings.breakpoints.small.gutter }}px; } /* Tablet */ @media (min-width: {{ settings.breakpoints.medium.screen_size }}px) { /* Tablet-specific styles */ } /* Desktop */ @media (min-width: {{ settings.breakpoints.large.screen_size }}px) { /* Desktop-specific styles */ } ``` ## Support For help with template customization or troubleshooting, contact our support team at [support@glood.ai](mailto:support@glood.ai) # Filters Source: https://docs.glood.ai/for-developers/section-template/filters Reference for custom Liquid filters available in section templates ## format\_money **Description:**\ Formats numeric values into the store's currency format based on the money\_format setting from the glood object. **Parameters:** * `value` (Number/String): The numeric price value to be formatted * `money_format` (String): Override default money format * `intl_options` (Object, optional): Currency formatting configuration ```js theme={null} { "en": { style: 'currency', currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: 2 } } ``` **Returns:**\ String - Formatted price string with currency symbol **Example:** ```liquid theme={null} {{ product.price | format_money: glood.shop.money_format, template.settings.intl_options }} ``` **Use Cases:** * Formatting product prices * Displaying compare at prices * Showing discount amounts * Bundle total prices ## optimize\_image **Description:**\ Optimizes and resizes images for better performance using CDN parameters. **Parameters:** * `url` (String): The original image URL to be optimized * `width` (Number, optional): Desired image width * `height` (Number, optional): Desired image height * `crop` (String, optional): Crop mode for the image **Returns:**\ String - Optimized image URL with CDN parameters **Example:** ```liquid theme={null} {{ product.featured_image.src | optimize_image: width: 300, height: 300 }} {{ product.image | optimize_image: width: 600, height: 600, crop: 'center' }} ``` **Use Cases:** * Product card images * Responsive image loading * Thumbnail generation * Banner image optimization ## product\_url **Description:**\ Generates a complete product URL with tracking parameters and localization. **Parameters:** * `handle` (String, required): Product handle/slug * `ref_product_id` (String, optional): Reference product ID * `layout` (String, optional): Section layout type **Returns:**\ String - Complete product URL with parameters **Example:** ```liquid theme={null} {% assign url = root_url | product_url: product.handle, glood.product.id, section.layout %} {{ product.title }} ``` **Use Cases:** * Product link generation * Navigation building * Tracking implementation * Multi-language support ## product\_discount **Description:**\ Calculates and formats product discount information based on configuration. **Parameters:** * `discount_config` (Object, required): Discount configuration settings * `label_text` (String, required): Template for discount label * `money_format` (String, required): Store's money format * `intl_options` (Object, optional): Currency formatting configuration **Returns:**\ String - Formatted discount text **Example:** ```liquid theme={null} {% assign discount = product | product_discount: section.discount_config, translations.discount_label_text, glood.shop.money_format, template.settings.intl_options %} {{ discount }} ``` **Use Cases:** * Sale badges * Discount displays * Price comparison * Promotional messaging ## save\_amount **Description:**\ Calculates and formats savings information based on discount configuration. **Parameters:** * `discount_config` (Object, required): Discount configuration settings * `save_text` (String, required): Template for savings text * `money_format` (String, required): Store's money format * `intl_options` (Object, optional): Currency formatting configuration **Returns:**\ String - Formatted savings text **Example:** ```liquid theme={null} {{ product | save_amount: section.discount_config, translations.discount_save_text, glood.shop.money_format, template.settings.intl_options }} ``` **Use Cases:** * Savings displays * Discount comparison * Promotional messaging ## color\_value **Description:**\ Retrieves color code from a color map object. **Parameters:** * `color_mapping` (Object, required): Color map object **Returns:**\ String - Color code **Example:** ```liquid theme={null} {{ value | color_value: template.settings.color_mapping }} ``` **Use Cases:** * Theme customization * Product attribute mapping * UI element styling ## to\_boolean **Description:**\ Converts any value to a boolean. **Parameters:** * None **Returns:**\ Boolean - True or False **Example:** ```liquid theme={null} ``` **Use Cases:** * Conditional rendering * Boolean logic * UI state management ## image\_dimensions **Description:**\ Calculates responsive image dimensions based on template breakpoint settings. **Parameters:** * `breakpoints` (Object, required): Template breakpoint settings **Returns:**\ Object - Object containing calculated dimensions **Example:** ```liquid theme={null} {{ client_info.client_width | image_dimensions: template.settings.breakpoints }} ``` **Use Cases:** * Responsive image loading * UI element sizing * Image optimization ## default **Description:**\ Provides a default value if the input is null, undefined or empty. **Parameters:** * `default_value` (Any, required): Value to use if input is empty **Returns:**\ Any - Original value or default value **Example:** ```liquid theme={null} {{ template.settings.product_card.min_quantity | default: 1 }} {{ translations.oos_text | default: 'Out of stock' }} ``` **Use Cases:** * Setting default quantities * Fallback text * Configuration defaults * Error prevention ## Error Handling | Error | Description | Solution | | - | - | - | | Invalid Price Format | Price value is null or not a number | 1. Use the default filter to set a fallback value (0) 2. Apply money filter to format the price | | Missing Image Dimensions | Width/height not specified for image optimization | 1. Always specify width and height parameters 2. Use default dimensions (300x300) if not provided | | Invalid Tracking Parameters | Missing required section context | 1. Check if section ID exists 2. Verify product handle is present 3. Fall back to standard product URL if missing | | Invalid Discount Configuration | Missing money format or invalid discount structure | 1. Ensure shop money format is provided 2. Validate discount configuration before applying | These errors require proper handling to: * Prevent template rendering failures * Maintain consistent price display * Ensure proper image loading * Keep tracking functionality intact ## Notes * All filters are available in both section templates and CSS templates * Some filters require specific objects from the template context * Filter parameters marked as required must be provided for the filter to work correctly * See [Object Definitions](/for-developers/section-template/schemas#object-definitions) for details about input objects ## Support For help with template customization or troubleshooting, contact our support team at [support@glood.ai](mailto:support@glood.ai) # Hooks Source: https://docs.glood.ai/for-developers/section-template/hooks Complete guide to hooks in Glood.AI section templates # Template Hooks ## Hook Lifecycle Flow ### 1. Section Initialization Phase * `onSectionInit` is called when section is first created * Sets up initial state and variables * Configures section parameters * Registers event listeners ### 2. Data Fetching Phase * `getProductDetailsQuery` is called to prepare GraphQL query * Defines required product fields * Sets up query variables * Configures custom data requirements * Sets up filtering parameters ### 3. Data Processing Phase * `postProductFetch` processes raw product data * Filters products if needed * Adds computed properties * Transforms data structure * `transformProductData` transforms individual product data * Normalizes data format * Adds custom fields * Prepares for rendering ### 4. Rendering Phase * `afterSectionRendered` is called once section is rendered on the page and ready to be used. **Note:** This is an optional hook, if you want to perform certain task, you can add your logic in this hook. * `initSwiper` (if carousel is enabled) * Configures carousel settings * Sets up navigation * Initializes responsive behavior * Sets up pagination ### 5. Interaction Phase * `onVariantChange` handles variant selection **Note:** This is an optional hook, if you want to perform certain task, you can add your logic in this hook. * `onSwatchChange` handles swatch interactions **Note:** This is an optional hook, if you want to perform certain task, you can add your logic in this hook. ### 6. Cart Operation Phase * `beforeAddToCart` validates cart operations * Validates product selection * Modifies cart payload * Handles quantity validation * `afterAddToCart` handles post-cart updates **Note:** This is an optional hook, if you want to perform custom logic, you can setup your logic in this hook. ## Available Hooks ### 1. onSectionInit **Purpose:**\ Primary initialization hook called when a section is first created. **Parameters:** 1. `args` contains: * `recommendation` object which includes: * [`section`](/for-developers/section-template/schemas#section-object) containing section ID, layout type, title, and discount configuration * Array of [`products`](/for-developers/section-template/schemas#product-array) with product data * `engine` object containing: * Engine name and version * Engine-specific configuration * `initEnginePayload` containing engine initialization data 2. `cb` (Callback Function): * Receives the processed recommendation object * Used to handle initialization completion * No return value expected 3. `gloodUtils` provides: | Function | Description | | - | - | | `formatMoney` | Formats price values according to store's money format | | `optimizeImage` | Optimizes image URLs with specified dimensions and crop settings | | `getVariantFromOptions` | Finds a variant based on selected options | | `findVariantById` | Retrieves a variant using its ID | | `getSelectedVariant` | Gets currently selected variant for a product | | `getDefaultVariant` | Returns the default/first available variant | | `addToCart` | Handles adding items to cart with proper validation | | `updateCart` | Updates existing cart items (quantity, properties) | | `getProductUrl` | Generates product URL with tracking parameters | | `getDiscountedPrice` | Calculates discounted price based on rules | | `formatDiscount` | Formats discount text with proper currency/percentage | | `getTranslation` | Retrieves translated text with fallback support | | `trackEvent` | Sends tracking events to analytics | | `refreshSection` | Re-renders section with updated data | | `showNotification` | Displays toast/notification messages | **Example:** ```javascript theme={null} onSectionInit: (args, cb, gloodUtils) => { const { recommendation, engine, initEnginePayload } = args; cb({ recommendation, engine, initEnginePayload, }); } ``` **Use Cases:** * Section configuration * State initialization * Event listener setup * Feature initialization * Engine configuration ### 2. getProductDetailsQuery **Purpose:**\ Builds the GraphQL query for fetching product data. **Parameters:** 1. `recommendation` contains: * [`section`](/for-developers/section-template/schemas#section-object) object with: * `id` (number): Unique section identifier * `layout` (String): Section layout type * `discount_config` (Object): Discount settings * `widget_message` (String): Custom message template * `products` (Array): Currently loaded products * `template` (Object): Template-specific settings 2. `glood` provides: * `shop` object containing: * `money_format` (String): Store currency format * `locale` (String): Store language code * `product` object with: * `id` (String): Current product context (format: "gid://shopify/Product/") * `handle` (String): Product URL handle * `localization` settings for: * Currency formatting * Language preferences * Regional settings **Returns:**\ GraphQL query string containing required product fields **Example:** ```javascript theme={null} getProductDetailsQuery: (recommendation, glood) => { return ` featuredImage { url } handle id title availableForSale priceRange { minVariantPrice { amount currencyCode } } compareAtPriceRange { minVariantPrice { amount currencyCode } } variants(first: 250) { nodes { id price { amount currencyCode } availableForSale // ... other variant fields } } `; } ``` **Use Cases:** * Product data fetching * Field selection * Query customization * Data filtering * Performance optimization ### 3. postProductFetch **Description:**\ Processes raw product data after fetching. Allows for data transformation and enrichment before rendering. **Parameters:** * `args` (Object): * `products` (Array): Raw product data array * `recommendation` (Object): Section configuration * `template` (Object): Template settings * `utils` (Object): Helper functions **Returns:**\ Array - Processed product data **Example:** ```javascript theme={null} postProductFetch: (args, utils) => { const { products, recommendation, template } = args; return products.map(product => ({ ...product, formattedPrice: utils.formatMoney(product.price), hasDiscount: product.compare_at_price > product.price, isAvailable: product.variants.nodes[0].availableForSale, imageUrl: utils.optimizeImage(product.featured_image, template.settings) })); } ``` **Use Cases:** * Price formatting * Discount calculations * Image optimization * Availability checks * Data enrichment ### 4. transformProductData **Purpose:**\ Transforms raw GraphQL product data into template-friendly format. **Parameters:** 1. `product` (Raw GraphQL data) contains: * Basic information: * `id` (String): GraphQL product ID (format: "gid://shopify/Product/") * `handle` (String): Product URL handle * `title` (String): Product title * `vendor` (String): Product vendor * Images: * `featuredImage` (Object): Main product image * `images` (Object): Additional product images * Pricing: * `priceRange` (Object): Min/max prices * `compareAtPriceRange` (Object): Original prices * Variants: * `variants` (Object): Product variants data * `variantsCount` (Object): Total variants count * Options: * `options` (Array): Product options * `selectedOptions` (Array): Default selections * Status: * `availableForSale` (Boolean): Stock status * `tags` (Array): Product tags 2. `recommendation` provides: * [`section`](/for-developers/section-template/schemas#section-object) settings: * Display configuration * Pricing rules * Layout settings * Tracking configuration **Returns:**\ [`Product`](/for-developers/section-template/schemas#product-object) object containing: * Normalized product data * Formatted prices * Processed images * Structured variants * Computed fields **Example:** ```javascript theme={null} transformProductData: (product, recommendation, utils) => { return { ...product, trackingData: utils.generateTrackingData(product, recommendation), variants: product.variants.map(variant => ({ ...variant, formattedPrice: utils.formatMoney(variant.price), isAvailable: variant.inventory_quantity > 0 })), labels: utils.generateProductLabels(product, recommendation.settings) }; } ``` **Use Cases:** * Tracking setup * Variant processing * Label generation * Price formatting * Custom field addition ### 5. initSwiper **Purpose:**\ Initializes and configures the carousel/slider functionality for sections using Swiper.js. **Parameters:** 1. `Swiper` (Constructor Class): * Swiper.js constructor * Used to create carousel instances * Handles slide functionality * Manages touch events * Controls navigation 2. `templateSettings` contains: * [`template.settings`](/for-developers/section-template/schemas#template-object) with: * `carousel` (Object): Carousel-specific settings * `breakpoints` (Object): Responsive configuration: * `small` (Object): Mobile settings * `medium` (Object): Tablet settings * `large` (Object): Desktop settings * Each breakpoint contains: * `screenSize` (Number): Width breakpoint * `cardsPerView` (Number): Visible slides * `gutter` (Number): Space between slides 3. `container` (HTMLElement): * Root section element * Contains carousel structure: * Wrapper element * Slide elements * Navigation buttons * Pagination dots 4. `params` contains: * [`recommendation`](/for-developers/section-template/schemas#recommendation-object): * `section` (Object): Section configuration * `products` (Array): Product data * Layout settings * Template-specific parameters 5. `defaultSettings` contains: * Default Swiper configuration: * Navigation options * Pagination settings * Autoplay configuration * Effect settings * Loop behavior 6. `utils` provides: * `merge`: Deep object merging * DOM manipulation helpers * Event handling utilities * Error handling functions **Returns:** * `Swiper` instance if initialization succeeds * `undefined` if initialization fails **Example:** ```javascript theme={null} initSwiper: (Swiper, templateSettings, container, params, defaultSettings, utils) => { const carouselContainer = container.querySelector('._gai-crz-cnt'); if (!carouselContainer) { console.error('GLOOD.AI:ERROR: Carousel container not found for section', params.recommendation.section.id); return; } const settings = templateSettings?.carousel?.swiperConfig || {}; const swiperConfig = utils.merge(defaultSettings, settings); const breakpoints = Object.values(templateSettings.breakpoints).reduce( (acc, curr) => ({ ...acc, [curr.screenSize]: { slidesPerView: curr.cardsPerView, spaceBetween: curr.gutter, }, }), {} ); return new Swiper(carouselContainer, utils.merge(swiperConfig, { breakpoints })); } ``` ### 6. onVariantChange **Purpose:**\ Handles product variant selection changes and updates the UI. **Parameters:** 1. `args` contains: * `variant` information: * Basic details: ID, price, compare price * Image information with source and alt text * Availability status and quantity * Selected options (color, size, etc.) * Complete [`product`](/for-developers/section-template/schemas#product-object) data * DOM container element for the product card 2. `utils` provides: * Price formatting functions * Image update utilities * Price display update functions * Other UI manipulation helpers ### 7. onSwatchChange **Purpose:**\ Handles swatch selection events and updates product display accordingly. **Parameters:** 1. `args` contains: * `option` object with: * `name` (String): Option name (e.g., "Color", "Size") * `value` (String): Selected option value * `type` (String): Swatch type (color/size/material) * `swatchImage` (String, optional): Custom swatch image URL * [`product`](/for-developers/section-template/schemas#product-object) object containing: * `variants` (Array): All product variants * `options` (Array): Available option types * `selectedVariant` (Object): Currently selected variant * `images` (Array): Product images * `container` (HTMLElement): Product card DOM element 2. `utils` provides: * `updateSwatchUI`: Updates swatch selection state * `findMatchingVariant`: Finds variant by options * `updateProductImage`: Updates product image * `updatePriceDisplay`: Updates price display * Event tracking utilities **Returns:**\ void ### 8. onCartOperationComplete **Purpose:**\ Handles post-cart operation tasks and updates UI accordingly. **Parameters:** 1. `args` contains: * `operation` (String): Type of operation ('add'|'update'|'remove') * `response` object with: * `cart` (Object): Updated cart state * `items` (Array): Modified cart items * `total` (Number): New cart total * `count` (Number): Updated item count * [`section`](/for-developers/section-template/schemas#section-object) containing: * Section configuration * Template settings * Tracking data * `container` (HTMLElement): Section container 2. `utils` provides: * `updateCartUI`: Updates cart display * `showNotification`: Displays notifications * `updateInventory`: Updates stock status * Animation utilities 3. `gloodUtils` provides: * `trackCartEvent`: Analytics tracking * `formatCartData`: Data formatting * `updateShopifyCart`: Cart sync utilities * Store-specific helpers **Returns:**\ void ### 9. validateCartOperation **Purpose:**\ Validates and potentially modifies cart operations before execution. **Parameters:** 1. `payload` contains: * Array of items being added/modified: * Product identifier * Variant identifier * Quantity * Additional cart-specific data 2. `recommendation` provides: * [`section`](/for-developers/section-template/schemas#section-object) configuration * Product data * Template settings 3. `utils` and `gloodUtils`: * Validation helpers * Cart operation utilities * Format and transformation functions **Returns:** * Modified payload if valid * Error message if validation fails * Optional redirect URL ### 10. onProductDataReceived **Purpose:**\ Processes raw product data before transformation and rendering. **Parameters:** 1. `args` contains: * `products` array with raw product data: * `id` (number): Product identifier * `title` (String): Product title * `handle` (String): Product URL handle * `featuredImage` (Object): Main product image * `variants` (Array): Raw variant data * `options` (Array): Product options * `tags` (Array): Product tags * [`section`](/for-developers/section-template/schemas#section-object) object with: * Layout configuration * Discount settings * Template rules * Display settings * [`template`](/for-developers/section-template/schemas#template-object) containing: * Breakpoint settings * Card configuration * Image dimensions * Price display rules 2. `utils` provides: * `processImages`: Image optimization utilities * `formatProductData`: Data formatting helpers * `validateProducts`: Data validation functions * `enrichProductData`: Data enrichment utilities * `handleErrors`: Error handling functions **Returns:**\ void ### 11. loadAjaxCart **Purpose:**\ Determines when to load the AJAX cart section by checking if the AJAX cart is active. **Parameters:** 1. `bodyElem` (HTMLElement): * The document body element * Provides access to AJAX cart state **Returns:**\ `Boolean` - True if AJAX cart is active and should be loaded **Example:** ```javascript theme={null} loadAjaxCart: (bodyElem) => { const ajaxCart = bodyElem.querySelector('cart-drawer'); return ajaxCart.classList.contains("active"); } ``` **Use Cases:** * Update recommendations dynamically when products are added to cart ### 12. unloadAjaxCart **Purpose:**\ Determines when to unload the AJAX cart section by checking if the AJAX cart is inactive. **Parameters:** 1. `bodyElem` (HTMLElement): * The document body element * Provides access to AJAX cart state **Returns:**\ `Boolean` - True if AJAX cart is inactive and should be unloaded **Example:** ```javascript theme={null} unloadAjaxCart: (bodyElem) => { const ajaxCart = bodyElem.querySelector('cart-drawer'); return !ajaxCart.classList.contains("active"); } ``` **Use Cases:** * Control AJAX cart unloading timing * Clean up cart resources * Manage AJAX cart states * Handle cart closure events ## Hook Dependencies ### Required Utils * `formatMoney`: Price formatting * `getVariantById`: Variant lookup * `updateUrl`: URL manipulation * `merge`: Object merging * `imageOptimizer`: Image optimization ### Global Context * `glood`: Store configuration * `translations`: Text strings * `template`: Template settings * `section`: Section configuration * `utils`: Common utilities ### Hook Flow Dependencies * `transformProductData` needs data from `getProductDetailsQuery` * `afterSectionRendered` needs data from `transformProductData` * Cart operations need data from `onVariantChange` * Swiper needs container from `afterSectionRendered` ## Error Handling Each hook should handle these critical errors: 1. Carousel Initialization Errors ```javascript theme={null} // Critical: Section won't render if carousel container is missing if (!carouselContainer) { console.error('GLOOD.AI:ERROR: Carousel container not found for section', params.recommendation.section.id); return; } ``` 2. Product Data Transformation Errors ```javascript theme={null} // Critical: Invalid product data will break the section if (!product.variants?.nodes) { console.error('GLOOD.AI:ERROR: Invalid variant data structure for product', product.id); return { ...product, variants: [], available: false }; } ``` 3. GraphQL Query Response Errors ```javascript theme={null} // Critical: Missing required fields will cause rendering issues if (!product.priceRange?.minVariantPrice?.amount) { console.error('GLOOD.AI:ERROR: Missing price data for product', product.id); return null; } ``` These errors require immediate attention as they: * Prevent sections from rendering correctly * Break core product functionality * Impact the shopping experience * Can cause JavaScript runtime errors ## Support If you need help with creating or customizing section templates, contact our support team at [support@glood.ai](mailto:support@glood.ai) # Introduction Source: https://docs.glood.ai/for-developers/section-template/introduction Learn about section templates in Glood.AI # Section Templates Section templates in Glood.AI are the building blocks for displaying product recommendations in your Shopify store. They function similarly to Shopify themes, allowing you to create custom layouts and designs for your product recommendations. ## What are Section Templates? Section templates are modular components that determine how your product recommendations are displayed. They are: 1. **Similar to Shopify Themes**: They follow the same principles as Shopify themes, using Liquid templating for dynamic content rendering. 2. **JavaScript-Powered**: Templates are loaded dynamically using JavaScript through the Glood.AI app embed, which handles recommendation fetching and rendering. 3. **Headless Compatible**: While templates are primarily for traditional Shopify stores, headless stores and Hydrogen apps can use our headless APIs instead. 4. **Multi-Component Structure**: Each template consists of: * Liquid templates for markup * JavaScript for interactivity * CSS for styling * Settings schema for customization * Translation strings for internationalization 5. **Flexible Rendering**: Templates can be rendered either on the frontend or backend, depending on your needs and configuration. 6. **Extensible**: We provide built-in Tags, Filters, and JavaScript Hooks for easy customization and third-party app integration. ## Template Components A basic section template includes these core components: ```liquid theme={null}
{%- comment -%} Template markup {%- endcomment -%}
{% stylesheet %} /* Template styles */ {% endstylesheet %} {% javascript %} // Template JavaScript {% javascript %} ``` ## Template Features ### 1. Settings Schema * Configurable options for layout, styling, and behavior * Support for various input types (text, select, color, etc.) * Section-specific configurations ### 2. Translations * Multi-language support * Customizable text strings * Fallback handling for missing translations ### 3. Liquid Markup * Dynamic content rendering * Built-in filters for data manipulation * Conditional rendering and loops ### 4. JavaScript * Event handling * DOM manipulation * API integrations * Cart operations ### 5. CSS * Responsive layouts * Custom styling * Animation support * Theme compatibility ## Extension Points We provide several ways to extend and customize templates: 1. **Tags**: Custom Liquid tags for template functionality ```liquid theme={null} {% product_ratings product_id: product.id %} ``` 2. **Filters**: Data manipulation filters ```liquid theme={null} {{ product.price | format_money: glood.shop.money_format }} ``` 3. **Hooks**: JavaScript hooks for lifecycle events ```javascript theme={null} initSection: (args, cb, utils) => { // Initialization logic } ``` ## Best Practices 1. **Performance** * Optimize images and assets * Minimize JavaScript execution time * Use efficient selectors * Implement lazy loading 2. **Compatibility** * Test across different themes * Ensure mobile responsiveness * Handle edge cases gracefully * Support various browser versions 3. **Maintainability** * Follow naming conventions * Document custom functionality * Use modular code structure * Implement error handling 4. **Accessibility** * Use semantic HTML * Add ARIA attributes * Ensure keyboard navigation * Provide alt text for images ## Libraries The section template system uses the following core libraries that you'll interact with when customizing templates: ### Core Libraries > [tab] Preact > > ```json theme={null} > "preact": "^10.22.1" > ``` > > Our UI library for building interactive components. > > **Key Features**: > > * React-compatible API > * Lightweight (3kB) > * Virtual DOM > * Component-based architecture > > [View Preact Documentation β†’](https://preactjs.com/) > [tab] Swiper > > ```json theme={null} > "swiper": "^11.1.15" > ``` > > Powers carousel functionality in templates. > > **Common Uses**: > > * Product carousels > * Image galleries > * Touch-enabled sliders > * Responsive layouts > > [View Swiper Documentation β†’](https://swiperjs.com/) > [tab] Liquid.js > > ```json theme={null} > "liquidjs": "^10.19.0" > ``` > > Template engine for rendering Shopify-compatible templates. > > **Features**: > > * Shopify Liquid syntax > * Custom tags and filters > * Theme compatibility > > [View Liquid.js Documentation β†’](https://liquidjs.com/) ## Next Steps * Learn about [Filters](filters) for data manipulation * Explore [Tags](tags) for template functionality * Understand [Hooks](hooks) for JavaScript integration * Check out [Template Structure](template-structure) for detailed component information ## Support If you need help with creating or customizing section templates, contact our support team at [support@glood.ai](mailto:support@glood.ai) # Schemas Source: https://docs.glood.ai/for-developers/section-template/schemas ## Understanding Core Components The template system uses seven essential building blocks that work together: 1. `glood` - Global store configuration 2. `products` - Product data management 3. `translations` - Multi-language support 4. `section` - Layout and behavior control 5. `template` - Appearance and styling settings 6. `clientInfo` - Device and viewport information 7. `config` - Integration and feature management ## `glood` Object The global object contains the store information required by the glood application to work properly on your store. ### Purpose and Usage The glood object provides essential store information and configuration settings that are used throughout the template. It's particularly important for: * Building correct store URLs * Formatting prices according to store settings * Handling localization ### Properties Reference ### Core Properties | Key | Type | Description | Default Value | | - | - | - | - | | `shopify.rootUrl` | string | Base URL of the Shopify store | "/" | ### Localization Properties | Key | Type | Description | Default Value | | - | - | - | - | | `localization.language.locale` | string | Language code | "en" | | `localization.language.primary` | boolean | Whether this is primary language | true | | `localization.language.rootUrl` | string | Base URL for language | "/" | | `localization.country` | string | Country code | "IN" | | `localization.currency` | string | Currency code | "INR" | ### Market Properties | Key | Type | Description | Default Value | | - | - | - | - | | `market.id` | string | Unique market identifier | "27455750381" | | `market.handle` | string | Market handle | "in" | ### Shop Properties | Key | Type | Description | Default Value | | - | - | - | - | | `shop.domain` | string | Store's domain | "adarsh-test2-store.myshopify.com" | | `shop.id` | string | Shop identifier | "73540239597" | | `shop.productsCount` | number | Total number of products | 15 | | `shop.currencyRate` | string | Currency conversion rate | "1.0" | | `shop.moneyFormat` | string | Store's currency format | `"Rs. \{\{amount\}\}"` | | `shop.currencyCode` | string | Store's currency code | "INR" | ### Product Properties | Key | Type | Description | Default Value | | - | - | - | - | | `product.id` | number | Current product identifier | 8925145628909 | | `product.title` | string | Product title | "(Sample) Coconut Bar Soap" | | `product.handle` | string | Product handle | "soap" | | `product.available` | boolean | Product availability status | true | | `product.price` | number | Product price | 2000 | | `product.vendor` | string | Product vendor | "adarsh-test2-store" | | `product.type` | string | Product type | "" | ### Cart Properties | Key | Type | Description | Default Value | | - | - | - | - | | `cart.currency` | string | Cart currency | "INR" | | `cart.itemCount` | number | Number of items in cart | 16 | | `cart.totalPrice` | number | Total cart price | 752945 | | `cart.requiresShipping` | boolean | Whether cart requires shipping | true | | `cart.totalWeight` | number | Total cart weight | 250 | ### Config Properties | Key | Type | Description | Default Value | | - | - | - | - | | `config.pageType` | string | Type of current page | "product" | | `config.pageUrl` | string | Current page URL | "adarsh-test2-store.myshopify.com/products/soap" | | `config.uid` | string | Unique identifier | "1737978965-cd63b5e8-9f99-4519-a4bc-b0dac71ccead" | **NOTE:** 1. All property keys are automatically converted to snake\_case when used in Liquid templates. For example: * `rootUrl` β†’ `root_url` * `devicePixelRatio` β†’ `device_pixel_ratio` * `moneyFormat` β†’ `money_format` 2. If you want to get the content of glood object, you can access it through `window.glood` inside your store. Example usage in Liquid: ```liquid theme={null} {{ glood.shop.moneyFormat }} {{ glood.localization.language.rootUrl }} ``` ## `products` Array The products array is a fundamental component that manages product data in the template system. ### Purpose and Usage The products array is responsible for: * Managing the collection of products to be displayed * Handling product data organization * Controls variant and option configurations * Managing pricing and inventory information * Providing media assets for product display ### Properties Reference | Key | Type | Description | Example | | - | - | - | - | | `id` | number | Product identifier | 8925145628909 | | `title` | string | Product name | "Coconut Bar Soap" | | `handle` | string | Product URL handle | "coconut-bar-soap" | | `vendor` | string | Product vendor name | "Natural Essentials" | | `tags` | array | Product tags | \["new", "organic", "bestseller"] | | `featuredImage.src` | string | Main product image URL | "[https://cdn.shopify.com/s/files/1/soap.jpg](https://cdn.shopify.com/s/files/1/soap.jpg)" | | `images[].src` | string | Additional image URLs | \["[https://cdn.shopify.com/s/files/1/soap-1.jpg](https://cdn.shopify.com/s/files/1/soap-1.jpg)"] | | `variants` | array | Product variants | \[See variant example below] | | `variants[].id` | string | Variant identifier | "40468007231725" | | `variants[].title` | string | Variant title | "Small / Blue" | | `variants[].availableForSale` | boolean | Stock availability | true | | `variants[].price` | string | Variant price | "19.99" | | `variants[].compareAtPrice` | string | Original price | "24.99" | | `variants[].image.src` | string | Variant image URL | "[https://cdn.shopify.com/s/files/1/blue-soap.jpg](https://cdn.shopify.com/s/files/1/blue-soap.jpg)" | | `variants[].selectedOptions` | array | Selected variant options | \[See options example below] | | `variants[].selectedOptions[].name` | string | Option name | "Size" | | `variants[].selectedOptions[].value` | string | Option value | "Small" | | `options` | array | Product options | \[See options example below] | | `options[].name` | string | Option name | "Size" | | `options[].optionValues` | array | Available option values | \["Small", "Medium", "Large"] | | `showComparePrice` | boolean | Show compare at price | true | | `firstVariant` | object | First available variant | \[See variant example above] | **NOTE:** Product array structure is not fixed and it can be changed. If you want to change product array, you can visit the [transformProductData hook](/for-developers/section-template/hooks#4-transformproductdata) in the hooks section. ## `translations` Object The translations object manages multi-language support and customizable text throughout the template. ### Purpose and Usage The translations object serves multiple purposes: * Provides language-specific text content * Enables customizable UI messages * Supports fallback text handling ### Properties Reference | Key | Type | Description | Default Value | | - | - | - | - | | `oosText` | string | Out of stock message | "Out of stock" | | `addedToCartText` | string | Success message for cart addition | "Added to cart" | | `atcErrorText` | string | Error message for cart addition | "Error adding to cart" | | `atcText` | string | Add to cart button text | "Add to cart" | | `totalPriceText` | string | Total price label | "Total price" | | `fbtAddToCartText` | string | Bundle add to cart text | "Add bundle to cart" | | `fbtAddedToCartText` | string | Bundle success message | "Bundle added to cart" | | `discountLabelText` | string | Discount label text | "Save " | | `discountSaveText` | string | Savings amount text | "Save " | | `fbtSaveText` | string | Bundle savings text | "Save with this bundle" | | `new` | string | New product badge text | "New" | | `trending` | string | Trending product badge text | "Trending" | | `bestseller` | string | Bestseller badge text | "Bestseller" | **NOTE:** The `new`, `trending`, and `bestseller` translations are used to display text inside badge on product cards. These badges help highlight product status or popularity to customers. The badges will automatically appear on products based on their tags or other criteria set in the template settings. ## `section` Object The section object controls how your recommendation section is structured and behaves. ### Purpose and Usage The section object is crucial for: * Defining the section's basic structure * Managing product display layouts * Controlling interactive features * Setting up titles and descriptions * Handling responsive behaviors ### Properties Reference | Key | Type | Description | Example | | - | - | - | - | | `id` | number | Unique section identifier | 12345 | | `layout` | string | Section layout type | "horizontal\_grid" | | `location` | string | Section placement location | "product\_page" | | `position` | number | Section position order | 1 | | `title` | string | Section heading text | "You May Also Like" | | `template` | string | Template identifier | "default" | | `extra` | object | Additional section configuration | `{"maxProducts":4}` | | `discountConfig` | object | Discount settings | `{"type":"percentage","value":20}` | | `showDiscountLabel` | boolean | Display discount labels | true | | `translations` | object | Section-specific translations | `{"discountText":"Save"}` | | `templateV3` | boolean | Using template version 3 | true | | `sectionServeId` | string | Unique serve identifier | "s-12345-abcd-9876" | | `pageType` | string | Page section appears on | "product" | ## `template` Object The template object is your control center for visual styling and responsive behavior. ### Purpose and Usage The template object is responsible for: * Managing responsive breakpoints * Controlling visual styling * Handling product card appearance * Managing interactive behaviors * Implementing custom themes ### Properties Reference | Key | Type | Description | Example | Default Value | | - | - | - | - | - | | `settings.breakpoints.small` | object | Mobile device settings | See breakpoint example | | | `settings.breakpoints.medium` | object | Tablet device settings | See breakpoint example | | | `settings.breakpoints.large` | object | Desktop device settings | See breakpoint example | | | `settings.breakpoints[].cardsPerView` | number | Number of cards per row | `2` (mobile), `3` (tablet), `4` (desktop) | 4 | | `settings.breakpoints[].gutter` | number | Space between cards in pixels | `10` (mobile), `20` (desktop) | 20 | | `settings.breakpoints[].justifyWidgetTitle` | enum | Title alignment | `"left"`, `"center"`, `"right"` | "left" | | `settings.breakpoints[].widgetTitleAlignment` | string | Widget title positioning | `"left"`, `"center"`, `"right"` | "left" | | `settings.breakpoints[].productTitleAlignment` | string | Product title alignment | `"left"`, `"center"`, `"right"` | "left" | | `settings.breakpoints[].comparePriceVisible` | boolean | Show/hide compare price | `true`, `false` | false | | `settings.breakpoints[].imageWidth` | number | Product image width | `300` | 300 | | `settings.breakpoints[].imageHeight` | number | Product image height | `300` | 300 | | `settings.breakpoints[].screenSize` | number | Breakpoint width threshold | `768` | 768 | | `settings.breakpoints[].maxSectionTitleRows` | number | Maximum section title rows | `2` | 2 | | `settings.breakpoints[].maxProductTitleRows` | number | Maximum product title rows | `2` | 2 | | `settings.breakpoints[].widgetTitleFontSize` | number | Section title font size | `24` | 24 | | `settings.breakpoints[].productTitleFontSize` | number | Product title font size | `16` | 16 | | `settings.breakpoints[].productVendorFontSize` | number | Vendor name font size | `14` | 14 | | `settings.productCard.vendorPosition` | enum | Vendor position | `"above"`, `"below"`, `"hidden"` | hidden | | `settings.productCard.addToCartMode` | enum | Add to cart behavior | `"card_hover"`, `"image_hover"`, `"fix"` | card\_hover | | `settings.productCard.imageHoverMode` | enum | Image hover effect | `"secondary"`, `"zoom"`, `"none"` | secondary | | `settings.productCard.imageObjectFit` | enum | Image fitting mode | `"contain"`, `"cover"` | contain | | `settings.productCard.priceCompareMode` | enum | Compare price position | `"before"`, `"after"`, `"hidden"` | before | | `settings.productCard.discountLabelPosition` | enum | Discount badge position | `"left"`, `"right"`, `"center"` | center | | `settings.productCard.variantSelectorType` | enum | Variant selection UI | `"integrated"`, `"selector"`, `"swatch"` | integrated | | `settings.productCard.showQuantitySelector` | boolean | Show quantity selector | `true`, `false` | false | | `settings.productCard.minQuantity` | number | Minimum order quantity | `1` | | | `settings.productCard.maxQuantity` | number | Maximum order quantity | `10` | | | `settings.productCard.imageAspectRatio` | string | Image aspect ratio | `"1:1"` | | | `settings.productCard.showVendor` | boolean | Show/hide vendor name | `true` | | | `settings.productCard.maxTitleLines` | number | Maximum product title lines | `2` | | | `settings.productCard.showDiscountPill` | boolean | Show/hide discount badge | `true` | | | `settings.labels` | array | Product label configurations | See labels example | | | `settings.labels[].name` | string | Label name | `"new"`, `"sale"` | | | `settings.labels[].textColor` | string | Label text color | `"#ffffff"` | | | `settings.labels[].backgroundColor` | string | Label background color | `"#ff0000"` | | | `settings.maxLabelsCount` | number | Maximum labels to show | `2` | | | `settings.swatches` | array | Swatch configurations | See swatches example | | | `settings.swatches[].type` | enum | Swatch type | `"color"`, `"size"` | | | `settings.swatches[].key` | string | Option key to match | `"color"`, `"size"` | | | `settings.swatches[].optionNames` | array | Valid option names | `["Color", "Colour"]` | | | `settings.carousel.library` | string | Carousel library to use | `"swiper"` | | | `settings.carousel.showPagination` | boolean | Show carousel pagination | `true`, `false` | false | | `settings.amazonBoughtTogether.priceCompareAtMode` | enum | Bundle price compare mode | `"before"`, `"after"` | before | | `settings.amazonBoughtTogether.buttonBackgroundColor` | string | Bundle button background | `"#000000"` | | | `translations` | object | Section-specific translations | See translations object | | | `settings.intlOptions` | object | Locale based currency formatting options | Intl DOM API options | | **NOTE:** 1. `addToCartMode` behavior options: * `card_hover`: Add to cart button slides up from the bottom of the card when hovering over the product card * `image_hover`: Add to cart button appears over the product image on hover * `fix`: Add to cart button is always visible below the product details 2. The `translations` key in this table refers to the same structure as the [translations object](/for-developers/section-template/schemas#translations-object). 3. Example intlOptions: ```json theme={null} { "en": { "style": "currency", "currency": "USD", "minimumFractionDigits": 2, "maximumFractionDigits": 2, "currencyDisplay": "symbol" } } ``` This configuration allows for customization of: * Currency display format * Decimal place handling * Currency symbol presentation * Localized number formatting ## `clientInfo` Object The clientInfo object provides information about the client's device and viewport settings. ### Purpose and Usage The clientInfo object is essential for: * Responsive design decisions * Image optimization ### Properties Reference | Key | Type | Description | Example | | - | - | - | - | | `clientWidth` | number | Current viewport width in pixels | 1440 | | `clientHeight` | number | Current viewport height in pixels | 900 | | `devicePixelRatio` | number | Device pixel ratio for image optimization | 2 | | `userAgent` | string | Browser's user agent string | "Mozilla/5.0 (Macintosh; Intel Mac OS X 10\_15\_7) AppleWebKit/537.36" | ## `config` Object The config object manages global configuration settings for the recommendation section. ### Purpose and Usage The config object controls: * Integration enablement and management * Third-party app configurations * Feature availability * App-specific settings ### Properties Reference | Key | Type | Description | Possible Values | | - | - | - | - | | `config.integrationsEnabled` | array | List of enabled integration slugs | `["judge_me", "loox", "stamped", "rivyo", "okendo", "ali", "ssw", "ryviu", "spr", "lai", "junip"]` | | `config.productReviewApp` | string | Selected product review app name | `"judge_me", "loox", "stamped", "rivyo", "okendo", "ali", "ryviu", "lai", "junip" (or none if not using reviews)` | | `config.swatchApp` | string | Selected swatch app name | `"variant_options_swatch_king", "csp" (or none if not using swatches)` | ## Support For help with template customization or troubleshooting, contact our support team at [support@glood.ai](mailto:support@glood.ai) # Tags Source: https://docs.glood.ai/for-developers/section-template/tags Learn about available tags for extending section template functionality # Section Template Tags Tags in Glood.AI section templates provide additional functionality and integrations for your product recommendations. ## Available Tags ### Product Review Integration #### product\_ratings Integrates product reviews from supported review apps. **Parameters:** * `product_id`: The product ID to fetch reviews for **Supported Apps:** * Judge.me * Loox **Example:** ```liquid theme={null} {% product_ratings product_id: product.id %} ``` **Output Examples:** For Judge.me: ```html theme={null}
``` For Loox: ```html theme={null}
``` ## Using Tags in Templates Here's an example of using tags in a product card: ```liquid theme={null}
{{ product.title }}

{{ product.title }}

{{ product.price | money_formatter: glood }}
{% product_ratings product_id: product.id %}
``` ## Tag Configuration ### Review App Integration To use the review app integration: 1. Configure your review app in the Glood.AI dashboard 2. Add the appropriate review app scripts to your theme 3. Use the tag in your section templates The tag will automatically: * Detect the configured review app * Generate appropriate widget markup * Handle missing configurations gracefully ## Best Practices 1. Always check if review app is configured before using the tag 2. Handle cases where product ID might be missing 3. Consider loading performance of review widgets 4. Test integration with different review app configurations 5. Provide fallback content when review app is not available ## Error Handling The tag handles various error cases: * No review app configured: Shows HTML comment * Missing product data: Shows HTML comment * Unsupported review app: Shows HTML comment ## Support For questions about tags or custom tag development, contact our support team at [support@glood.ai](mailto:support@glood.ai) # Upsell Blocks β€” Theme Integration & JS Hooks Source: https://docs.glood.ai/for-developers/upsell-blocks-integration Wire the Glood Upsell PDP and Cart blocks into custom themes, integrate native variant + quantity selectors, and react to selections via the window.Glood.upsell pub/sub bus. The **Glood Upsell for PDP** and **Glood Upsell for Cart** theme app blocks ship with a small JS surface designed for easy integration into any Shopify theme β€” from Dawn out-of-the-box to deeply-customised builds. This guide covers: * Block placement requirements * Quick-start integration (zero-code for most themes) * Auto-listener behaviour * The `window.Glood.upsell` API β€” `refresh()`, `setQty()`, `setVariant()`, `setContext()`, `setMode()`, `getPendingItems()`, `commitSelections()`, `subscribe()`, `publish()`, `getState()` * Auto vs deeply-integrated mode (when to call the explicit setters) * Linked vs Standalone modes (atomic Add-to-cart bundling) * Wiring custom variant pickers, quantity inputs, cart-drawer refresh paths * Verifying the integration end-to-end + an error reference ## Quick start **Most themes need zero code.** Drag the block into a section, save the theme, you're done. 1. In the Shopify admin β†’ **Online Store β†’ Themes β†’ Customize**, open a product template. 2. In the section that should host the upsell (typically *Product information* below the price/description), click **Add block** β†’ pick **Glood Upsell for PDP**. 3. Repeat in the **Cart drawer** and the `/cart` page sections, adding **Glood Upsell for Cart**. 4. Save the theme. The blocks self-load their JS/CSS, auto-listen to standard `[name="id"]` / `[name="quantity"]` change events, and refresh on `Rk:Added_To_Cart` + Shopify-native `cart:updated`. Open the PDP, add the trigger product β†’ the panel re-renders with applicable offers. **You only need theme code if** the theme's PDP uses a custom variant/qty picker that doesn't dispatch standard form `change` events, OR you want the block linked to the theme's native Add-to-cart button (single atomic add for host + upsells). Both paths are below. ## Block placement Both blocks are dragged into theme sections via Shopify's theme editor. They depend on the section accepting **theme app blocks** β€” most modern themes do this via a `{ "type": "@app" }` entry in the section's schema `blocks` array. Dawn, Sense, Studio, and other Online Store 2.0 themes work out of the box. | Block | Where | Restriction | | - | - | - | | Glood Upsell for PDP | Any product-template section | `enabled_on: { templates: ["product"] }` | | Glood Upsell for Cart | Cart drawer section AND/OR `/cart` page section | None β€” merchant drags wherever | If your theme's section doesn't accept app blocks, the Glood entry won't appear in the **Add block** picker. Edit the section's `{% schema %}` and add `{ "type": "@app" }` to its `blocks` array. ## Auto-listener behaviour On boot, `glood-upsell.js` subscribes to a curated set of theme-agnostic events. **No theme integration is required** for any of these: | Trigger | What fires | | - | - | | `[name="id"]` change on any product form | `refresh({ variantId })` | | `[name="quantity"]` change | `refresh({ qty })` | | `glood-ai:on_bundle_variant_change` event | `refresh({ variantId })` (Glood Bundles bus) | | `Rk:Added_To_Cart` event | `refresh({ refetchCart: true })` | | Shopify-native `cart:updated` event | `refresh({ cart })` | | Shopify-native `cart:refresh` event | `refresh({ refetchCart: true })` | Each call to `refresh()` re-evaluates which offers apply, recomputes the qty-aware slot count, and re-renders all mounted Glood Upsell blocks on the page. ## The `window.Glood.upsell` API ```js theme={null} // Imperative β€” trigger a re-render with new state. Each field is optional. window.Glood.upsell.refresh({ variantId: 12345, // override the current variant qty: 2, // override the main-product quantity cart: cartSnapshot, // pass a /cart.js response object directly refetchCart: true, // OR fetch /cart.js fresh }) // Pub/sub β€” listen for state transitions. const unsubscribe = window.Glood.upsell.subscribe('cart-updated', ({ cart }) => { console.log('cart changed', cart) }) // later: unsubscribe() // Manually publish β€” useful for instrumentation. Subscribers fire, // but a publish() alone does NOT re-render (use refresh() for that). window.Glood.upsell.publish('variant-changed', { variantId: 12345, productId: 67890 }) // Read-only snapshot. const snapshot = window.Glood.upsell.getState() // β†’ { variantId, variantSource, productId, qty, qtySource, mode, modeSource, cart, selections } // Canonical cart-line attribute keys β€” exposed for custom add-to-cart flows. window.Glood.upsell.CART_LINE_ATTR // β†’ { EXTERNAL_ID, ROLE, SLOT_INDEX, TIER_ID, STATUS } // ─── Linked-mode helpers (see "Linked vs Standalone modes" below) ────────── // Snapshot of currently-picked pool slots, shaped exactly as Shopify // /cart/add.js expects. Returns [] when nothing is picked. window.Glood.upsell.getPendingItems() // β†’ [{ id, quantity, properties: { __glood_uo_external_id, __glood_uo_role, __glood_uo_slot_index, __glood_uo_status } }, …] // Two-trip commit β€” fires /cart/add.js for getPendingItems(), clears // selections, refreshes cart. Use when the theme can't atomically // bundle. Returns { ok: true, items } | { ok: false, error }. await window.Glood.upsell.commitSelections() // Flip integration mode at runtime β€” overrides the per-block schema setting. window.Glood.upsell.setMode('linked') // or 'standalone' ``` ## Auto mode vs deeply-integrated mode The block runs in one of two modes per state field (`qty`, `variantId`): | Mode | Trigger | Driver for slot count | | - | - | - | | **Auto** (default) | Anything else β€” DOM auto-listeners, cart events, `refresh()` without `source` | `max(qty input, trigger qty in cart)` β€” so PDP qty bumps AND cart-side qty bumps both grow the slot budget | | **Deeply integrated** | Theme calls `setQty()`, `setVariant()`, `setContext()`, or `refresh({ ..., source: 'explicit' })` | The explicit value β€” represents the TOTAL intended trigger qty, including whatever's already in the cart. Used verbatim even when it's lower than cart qty. | In deeply-integrated mode the block trusts the theme's number and computes: ``` effectiveMax = slotsPerMainQty Γ— explicitQty (capped at maxSlots) remainingBudget = effectiveMax βˆ’ pickQtyAlreadyInCart ``` So if the theme says `setQty(5)` and the cart already has 3 pick lines for the offer, the panel will show 2 remaining slots. ### Explicit setters ```js theme={null} // Set the active variant (used for trigger-matching on PDP). window.Glood.upsell.setVariant(45678) // Set the TOTAL intended trigger qty (cart + about-to-add combined). window.Glood.upsell.setQty(3) // Both at once. window.Glood.upsell.setContext({ variantId: 45678, qty: 3 }) // Drop back to auto mode (cart becomes the source of truth again). window.Glood.upsell.resetSource() ``` All three explicit setters flag the value as theme-owned for the rest of the session (or until `resetSource()` / page navigation). ### When to use which mode * **Use auto mode** when you have a standard `[name="quantity"]` input and `[name="id"]` variant selector. The block picks them up for free, and cart-side qty changes (drawer steppers, line removals) automatically grow / shrink the slot count. * **Use deeply-integrated mode** when: * Your custom variant/qty picker doesn't emit standard DOM events. * You want the block to treat your number as authoritative even when the cart has a different qty (e.g. a "configure 5, add all at once" flow). * You're embedding the block inside a custom configurator that owns its own state machine. If you mix the two β€” e.g. call `setVariant()` once and then let the auto-listener handle `[name="quantity"]` β€” only the field you called `setVariant()` on becomes explicit; the qty stays in auto mode. ### Published events | Event | Payload | When | | - | - | - | | `variant-changed` | `{ variantId, productId, source? }` | After `refresh({ variantId })` | | `qty-changed` | `{ qty, source? }` | After `refresh({ qty })` | | `cart-updated` | `{ cart }` | After `refresh({ cart })` or `{ refetchCart: true }` succeeds | | `offer-applied` | `{ offerExternalId, slotIndices?, source? }` | After a pick offer is added to cart via the block's Add button or `commitSelections()` | | `mode-changed` | `{ mode, source }` | After `setMode()` | ## Linked vs Standalone modes The PDP block ships with two integration modes β€” pick the one that matches your theme. | | Standalone (default) | Linked | | - | - | - | | Slot count driven by | Trigger qty already in the cart | PDP qty input **+** trigger qty in the cart | | Block's own "Add to cart" button | Visible | Hidden (a "Added with your purchase." caption sits in its place) | | Commit path | The block's own button fires `/cart/add.js` for the upsell items | The theme's native Add-to-cart fires for the host product; the upsell items ride along via your code | | Best fit | Theme exposes a separate upsell section after the product form, OR there's no native PDP form to integrate with | Theme owns a custom configurator/build flow, OR you want a single combined add-to-cart action | ### Choosing the mode **Per-block setting (theme editor β€” preferred).** Drag the *Glood Upsell for PDP* block into a product section, open its settings panel, and pick **Integration mode β†’ Linked to the product's Add to cart**. Save. The block sets `data-glood-upsell-mode="linked"` on the mount element and the JS picks it up on init. **JS override (runtime).** Themes that need to flip dynamically: ```js theme={null} window.Glood.upsell.setMode('linked') // or 'standalone' window.Glood.upsell.getState().mode // 'linked' window.Glood.upsell.getState().modeSource // 'explicit' (vs 'block' when set via schema) ``` ### Linked mode β€” the atomic-bundle pattern (preferred) Bundle the upsell items into the SAME `/cart/add.js` POST that adds the host product. Single network round-trip; no flicker between the host landing and the upsell items landing. **Minimal recipe β€” vanilla form intercept (works on Dawn / Sense / most OS 2.0 themes):** ```liquid theme={null} {%- comment -%} Place inside the section that hosts both the product form AND the Glood block. {%- endcomment -%} ``` **Notes:** * `getPendingItems()` returns `{ id, quantity, properties: { __glood_uo_* } }` per picked pool slot, **clamped to the offer's remaining slot budget**. Empty array when nothing's picked. * The fallback `form.submit()` on error ensures the customer can still complete the purchase even if Glood's add fails β€” never block the host product from landing. * If your theme uses a custom AJAX add-to-cart (e.g. Dawn's `product-form.js`'s `onSubmitHandler`), intercept at that layer instead of the form's `submit` event. The body of the recipe is identical. ### Linked mode β€” the two-trip fallback If the theme's Add-to-cart handler doesn't expose a pre-POST hook, call `commitSelections()` AFTER the theme's own ATC completes: ```js theme={null} // In a post-ATC `Rk:Added_To_Cart` listener, or wherever your theme signals success: const result = await window.Glood.upsell.commitSelections() if (!result.ok) console.warn('[upsell]', result.error) ``` `commitSelections()` fires its own `/cart/add.js` for the pending picks, clears `state.selections`, refetches the cart, fires `offer-applied`. Cost: the customer sees the host land first, then the upsell items land a moment later (two network trips). ### Standalone mode β€” no theme integration needed Just drop the block in. The block reads the cart, shows applicable offers when the trigger product is present, and uses its own Add-to-cart button to commit. The host PDP form is left alone. Empty-state copy: when the cart has zero of the offer's trigger product, the panel collapses to a single "Add this product to your cart to unlock the upsell." prompt instead of showing 0 selectable slots. ### When to use which mode * **Standalone** when the upsell is a reactive "after-purchase add-on" experience β€” the customer must first add the host product to the cart, and the upsell section lights up afterwards. Works with literally any theme. * **Linked** when the upsell is part of a *bundle-style* purchase β€” the customer configures host + accessories in one go and clicks one Add-to-cart button. Requires either picking the mode from the theme editor OR a small JS hook in the theme's ATC handler. ## Wiring native variant selectors The block auto-listens to `[name="id"]` changes on any product form, which covers \~95% of themes. For custom variant pickers that don't update a hidden `name="id"` input: ```liquid theme={null} {%- comment -%} Custom variant picker that doesn't fire a `change` event on a form input. Call refresh() directly after your picker's own state change. {%- endcomment -%} ``` For themes that integrate with the Glood Bundles widget, the existing `glood-ai:on_bundle_variant_change` bus is already auto-handled. ### Variant-aware pool items If a pool item's reward product has multiple variants, the block lazy-loads the variant list from Shopify's public `/products/{handle}.js` endpoint when the customer picks that card. The customer can then pick a different variant from the dropdown that appears under the product name. This works automatically when the canonical payload carries the product's `handle` (admin captures it via the App Bridge resource picker). Single-variant products show no dropdown. ## Wiring native quantity inputs The block auto-listens to `[name="quantity"]` changes anywhere on the page. The PDP block's slot meter is qty-aware: `slotsPerMainQty Γ— qty, capped at maxSlots`. For custom quantity pickers (e.g. a `data-action="increase"` button on a custom `+`/`βˆ’` widget), either dispatch a synthetic `change` event on the native input or call the API directly: ```js theme={null} // Option A β€” dispatch a change event so the auto-listener picks it up: const qtyInput = document.querySelector('input[name="quantity"]') qtyInput.value = String(newQty) qtyInput.dispatchEvent(new Event('change', { bubbles: true })) // Option B β€” call Glood directly (skips DOM event entirely): window.Glood.upsell.refresh({ qty: newQty }) ``` Both paths trigger the same internal state update. The slot meter and Add-to-cart button reflect the new qty within one paint. ## Reacting to cart updates The block has three complementary cart-refresh paths: 1. **Auto** β€” Shopify-native `cart:updated` / `cart:refresh` events. 2. **Existing Glood bus** β€” `Rk:Added_To_Cart` (dispatched by other Glood widgets). 3. **Manual** β€” `window.Glood.upsell.refresh({ refetchCart: true })`. If your theme's cart drawer uses the **Section Render API** to update its own markup, call `refresh({ refetchCart: true })` after the section swap so the Glood block re-renders against the new cart state: ```js theme={null} async function refreshCartDrawer() { // Your theme's existing Section Render swap goes here. Pseudocode: // const html = await fetch('/?section_id=cart-drawer').then(r => r.text()) // ...swap drawer markup using your theme's own helper... // Re-hydrate the Glood upsell block with the new cart state: if (window.Glood && window.Glood.upsell) { window.Glood.upsell.refresh({ refetchCart: true }) } } ``` The block doesn't store cart-line markup itself β€” re-rendering after a Section Render is cheap. ## Custom add-to-cart flows If your theme intercepts `/cart/add.js` POSTs (e.g. for analytics or to inject extra properties), the Glood Upsell add-to-cart uses the same endpoint with these properties: ```js theme={null} { items: [{ id: 12345, // variant id quantity: 1, properties: { __glood_uo_external_id: 'uo_xxxxxxxx', // offer.external_id __glood_uo_role: 'pick', // 'pick' | 'free_gift' __glood_uo_slot_index: '0', // pool slot index __glood_uo_status: 'pending', // Function flips to 'qualified' }, }] } ``` These properties drive the Discount Function's eligibility check at checkout. **Don't strip them in your theme middleware.** After a successful add, the block dispatches `Rk:Added_To_Cart` and refreshes its own cart state. Listen on `Rk:Added_To_Cart` from your theme to chain additional behaviour. ## Custom CSS Each block has a `Custom CSS` textarea in its theme-editor settings β€” content is scoped to that block instance. For repo-wide overrides, target the block's BEM-scoped classes from your theme's stylesheet: ```css theme={null} /* Override the Glood upsell PDP panel background in a dark theme */ .glood-upsell-panel--pick { background: linear-gradient(180deg, #2b2640 0%, #1a1729 60%); border-color: #4d3a73; color: #fff; } .glood-upsell-panel--pick .glood-upsell__gift-card { background: rgba(255, 255, 255, 0.04); border-color: rgba(255, 255, 255, 0.12); } ``` ## Verifying the integration After placing the block and (optionally) wiring any theme hooks, paste these into the browser console on the PDP to validate end-to-end: ```js theme={null} // 1. Block hydrated? Public API present? console.log({ mounted: document.querySelectorAll('[data-glood-upsell]').length, hasApi: !!window.Glood?.upsell, state: window.Glood?.upsell?.getState(), }) // 2. Payload reached the block? const mount = document.querySelector('[data-glood-upsell]') const payload = JSON.parse(mount.querySelector('script[data-glood-upsell-payload]').textContent) console.log({ pickOffers: payload.pickOffers.length, freeGiftOffers: payload.freeGiftOffers.length, }) // 3. Slot count reacts to qty input (PDP linked mode): window.Glood.upsell.setMode('linked') const qtyEl = document.querySelector('[name="quantity"]') qtyEl.value = '3'; qtyEl.dispatchEvent(new Event('change', { bubbles: true })) // β†’ check the panel's "You have N add-on gift slots." copy updates within a frame ``` **Health checks:** | What to look for | If broken | | - | - | | `payload.pickOffers.length > 0` on the PDP | Trigger product has no `glood.upsell_pick_offers` metafield β†’ run `yarn commands setup-upsell-shop ` | | `payload.freeGiftOffers.length > 0` on every page | No `glood` metaobject entries β†’ run setup-upsell-shop too | | `state.cart` is non-null one second after load | `/cart.js` request failed β€” usually a CORS or auth header issue in the theme | | Block visible but Add-to-cart button greyed out | Customer hasn't selected a pool item β€” expected; the standalone empty state replaces this when no host is in cart | ## Errors and what they mean Every error surfaces as a pill on the gift card (free-gift) or an inline banner under the pick panel. The exact text β†’ cause β†’ fix mapping: | Pill / banner | Cause | Fix | | - | - | - | | `Adding…` | A `POST /cart/add.js` for this tier is in flight | Wait β€” auto-clears on response. If stuck >5s, see *Stuck `Adding…`* below | | `βœ“ In cart` | Gift line confirmed in `/cart.js` | n/a β€” happy path | | `⚠ Reward variant no longer available` | Shopify returned "Cannot find variant" or "maximum quantity..." for the variant id we sent | Variant archived / out of stock. Run `yarn commands audit-upsell-offer-variants ` to surface, re-pick via admin | | `⚠ Reward variant missing β€” merchant needs to re-pick it` | Market entry has no `variantId` (or NaN) β€” the storefront short-circuited before POST | Open the offer in admin β†’ re-pick the reward variant on every tier/pool item | | `⚠ ` | `/cart/add.js` returned an unrelated 4xx (e.g. selling-plan-only variant, B2B price list mismatch) | Read the message; usually fixable on the product config | | Empty-state prompt: `Add this product to your cart to unlock the upsell.` | Standalone mode, trigger product not in cart yet, no PDP qty input intent | Expected. Add the trigger product to the cart and the panel hydrates | ### Stuck `Adding…` If the pill stays on `Adding…` indefinitely, check the Network tab for `POST /cart/add.js`: * **No request fired** β†’ the storefront short-circuited before POST. Usually `market.variantId` is null/NaN. The error pill should already say `Reward variant missing`; if it doesn't, hard-refresh the page (Cmd+Shift+R) β€” you may be on a stale extension JS bundle. * **Request returned 5xx** β†’ Shopify-side hiccup; the block retries on the next cart event automatically. * **Request returned 4xx but pill still says "Adding…"** β†’ bug; please send the request body + response to the Glood support channel. ## Debugging `glood-upsell.js` logs every render with the full payload + state, so production debugging is one console line away: ``` [Glood.upsell] render pdp { payload, state, topFreeGift } ``` Check `payload.pickOffers` and `payload.freeGiftOffers` to confirm the block has data; `state.cart` to confirm the cart snapshot is current. If you see `[Glood.upsell] mount has no payload`, the inline `