AI Commerce Search
Google Vertex AI retail search
medusa-ai-commerce-search
Google AI Commerce Search (Google Cloud Retail API / Vertex AI Search for Retail) module provider and client SDK for Medusa v2.
This package provides enterprise AI-powered search, product recommendations, real-time catalog synchronization, and user event tracking for Medusa v2 e-commerce platforms.
Table of Contents
- Features
- Installation
- Automated Onboarding (1-Command GCP Setup)
- Configuration
- Google Cloud Retail API Credentials
- medusa-config.ts
- Module Options
- Initial Catalog Ingestion
- Store & Admin API Endpoints
- Store Search (Copy to clipboard
POST /store/ai-search/search) - Store Events (Copy to clipboard
POST /store/ai-search/events) - Store Recommendations (Copy to clipboard
POST /store/ai-search/recommendations) - Admin Options Mapping (Copy to clipboard
GET& Copy to clipboardPOST /admin/ai-search/options-mapping) - Admin Bulk Ingest (Copy to clipboard
POST /admin/ai-search/catalog/import)
- Store Search (Copy to clipboard
- Storefront Client SDK (Copy to clipboard
medusa-ai-commerce-search-client) - Real-Time Event Subscribers
- Admin UI: Option Mapping
- Limitations
- License
Features
- Semantic & AI Search: Natural language understanding, auto-correction, query expansion, and faceted filtering powered by Google Cloud Retail API.
- Personalized Recommendations: Frequently-bought-together, similar items, recommended for you, and custom serving configs.
- Hierarchical Catalog Ingestion: Full parent-category hierarchies (Copy to clipboard
parent_category...), breadcrumbs, and collection metadata (Copy to clipboardcollection.id, Copy to clipboardcollection.title, Copy to clipboardcollection.handle). - Real-Time Streaming Sync: Automatic product indexing, debounced coalescing for high-frequency updates, and cascading variant deletion.
- Conversion & Event Tracking: Automated server-side purchase-complete tracking and client-side browsing event analytics.
- Admin Option Mapping: Map Medusa product options (e.g. Copy to clipboard
Color, Copy to clipboardSize, Copy to clipboardMaterial) directly to Google Retail system attributes or custom attributes via the Medusa Admin UI.
Installation
Install the backend plugin and search provider in your Medusa backend:
1npm install medusa-ai-commerce-search
For your storefront (Next.js, Remix, Astro, or vanilla JS), install the companion client tracker:
1npm install medusa-ai-commerce-search-client
Automated Onboarding (1-Command GCP Setup)
You can provision and configure all required Google Cloud Retail API resources with a single automated CLI setup wizard:
1npx medusa-ai-commerce-search setup
What the Setup Wizard Automates:
- Google Cloud Authentication: Detects your active Copy to clipboard
gcloudaccount or guides you through logging in with Copy to clipboardgcloud auth login. - Project Selection / Creation: Selects an existing Google Cloud project from your account or provisions a new one with smart auto-generated unique project IDs and conflict retry handling.
- Billing Verification & Linkage: Inspects project billing status and links an active Google Cloud Billing account (Copy to clipboard
gcloud billing projects link). - API Enablement: Automatically enables Copy to clipboard
retail.googleapis.comand Copy to clipboardserviceusage.googleapis.com. - Dedicated Service Account: Creates a dedicated service account Copy to clipboard
medusa-retail-searchand grants it Copy to clipboardroles/retail.admin, with automated retries and exponential backoff to handle Google Cloud IAM eventual consistency and replication delays. - Credential Export & Security: Exports the service account key JSON to Copy to clipboard
./gcp-retail-key.jsonwith strict file permissions (Copy to clipboard0600) and automatically adds it to Copy to clipboard.gitignore. - Environment Configuration: Safely appends or updates required variables in your Copy to clipboard
.env:- Copy to clipboard
GCP_RETAIL_PROJECT_ID: Your target Google Cloud project ID. - Copy to clipboard
GCP_RETAIL_KEY_PATH: Path to your exported credentials key JSON.
- Copy to clipboard
- Catalog Verification & Terms Activation: Checks whether the Google Cloud Retail Data Use Terms have been accepted. If unaccepted, displays the direct Cloud Console activation link and prompts to accept them before verifying and initializing the default catalog branch (Copy to clipboard
branches/0) so search, recommendations, and sync endpoints are immediately ready to serve queries.
Zero-Install via Google Cloud Shell
Click the Open in Cloud Shell button above to launch an interactive cloud environment directly in your browser. Google Cloud Shell provides a browser-based terminal with Node.js and Copy to clipboardgcloud pre-installed and pre-authenticated to your Google account. In the Cloud Shell terminal, simply run:
1npx medusa-ai-commerce-search setup
Non-Interactive & CI/CD Provisioning
To automate setup inside CI/CD pipelines, Docker environments, or scripted developer bootstrapping, pass non-interactive flags:
12345npx medusa-ai-commerce-search setup \--project-id my-ecommerce-project \--billing-account 012345-6789AB-CDEF01 \--key-path ./gcp-retail-key.json \--yes
CLI Options & Flags:
Option Alias Default Description Copy to clipboard--project-id <id> Copy to clipboard-p Prompted Target Google Cloud Project ID (creates if non-existent) Copy to clipboard--billing-account <id> Copy to clipboard-b Prompted Billing account ID to link to the project Copy to clipboard--key-path <path> Copy to clipboard-k Copy to clipboard./gcp-retail-key.json Destination path for the service account key JSON Copy to clipboard--env-file <path> Copy to clipboard./.env Destination Copy to clipboard.env file to update Copy to clipboard--service-account <name> Copy to clipboard-s Copy to clipboardmedusa-retail-search Dedicated service account name Copy to clipboard--location <loc> Copy to clipboard-l Copy to clipboardglobal Google Cloud Retail API location Copy to clipboard--catalog-id <id> Copy to clipboarddefault_catalog Catalog ID Copy to clipboard--branch-id <id> Copy to clipboard0 Branch ID Copy to clipboard--yes Copy to clipboard-y Copy to clipboardfalse Non-interactive mode (auto-accept prompts and defaults) Copy to clipboard--dry-run Copy to clipboardfalse Simulate provisioning actions without altering GCP resources Copy to clipboard--skip-catalog-verify Copy to clipboardfalse Skip Retail API catalog branch verification Copy to clipboard--help Copy to clipboard-h Show usage help
Configuration
Google Cloud Retail API Credentials
Ensure you have a Google Cloud Project with the Retail API (or Vertex AI Search for Retail) enabled. You can authenticate via:
- Automated Setup (Recommended): Run Copy to clipboard
npx medusa-ai-commerce-search setupas described above to automate credentials and project setup. - Application Default Credentials (ADC): When running in Google Cloud or with Copy to clipboard
GOOGLE_APPLICATION_CREDENTIALSconfigured, Copy to clipboardprojectIdand Copy to clipboardquotaProjectIdare automatically forwarded to Retail API clients. - Service Account Key File: Specify Copy to clipboard
keyFilename: process.env.GCP_RETAIL_KEY_PATH || "./gcp-retail-key.json". - Explicit Credentials Object: Pass Copy to clipboard
{ client_email: "...", private_key: "..." }.
Manual GCP Console Configuration Reference
If you prefer configuring resources manually in the Google Cloud Console rather than running the CLI wizard:
- Open the Google Cloud Console.
- Create or select a Google Cloud project and ensure billing is enabled.
- Enable the Retail API under APIs & Services > Library.
- Navigate to IAM & Admin > Service Accounts, create a service account named Copy to clipboard
medusa-retail-search, and assign the Copy to clipboardRetail Admin(Copy to clipboardroles/retail.admin) role. - Create and download a JSON key for the service account.
- Save the key file to your Medusa project root as Copy to clipboard
gcp-retail-key.json(ensure it is added to Copy to clipboard.gitignore). - Add Copy to clipboard
GCP_RETAIL_PROJECT_IDand Copy to clipboardGCP_RETAIL_KEY_PATHto your Copy to clipboard.envfile.
medusa-config.ts
Configure Copy to clipboardmedusa-ai-commerce-search in Copy to clipboardmedusa-config.ts under both Copy to clipboardmodules (as the Copy to clipboardModules.SEARCH search provider) and Copy to clipboardplugins (to register API routes, event subscribers, and Medusa Admin extensions):
1234567891011121314151617181920import { defineConfig, Modules } from "@medusajs/framework/utils";export default defineConfig({projectConfig: {// ...},modules: [{resolve: "@medusajs/medusa/search",options: {providers: [{resolve: "medusa-ai-commerce-search",id: "google-ai-search",options: {projectId: process.env.GCP_RETAIL_PROJECT_ID || process.env.GOOGLE_CLOUD_PROJECT_ID || "my-gcp-project",location: process.env.MEDUSA_AI_LOCATION || "global",catalogId: process.env.GOOGLE_CLOUD_CATALOG_ID || "default_catalog",branchId: process.env.GOOGLE_CLOUD_BRANCH_ID || "0",servingConfigs: {
Module Options
Option Type Default Description Copy to clipboardprojectId Copy to clipboardstring Required Google Cloud Project ID. Sets Copy to clipboardprojectId and Copy to clipboardquotaProjectId for ADC. Copy to clipboardlocation Copy to clipboardstring Copy to clipboard"global" Google Cloud Retail API location (Copy to clipboard"global", Copy to clipboard"us-central1", etc.). Copy to clipboardcatalogId Copy to clipboardstring Copy to clipboard"default_catalog" Catalog ID in Google Retail API. Copy to clipboardbranchId Copy to clipboardstring Copy to clipboard"0" Branch ID for product operations (Copy to clipboard"0" is default). Copy to clipboardservingConfigs Copy to clipboardRecord<string, string> Copy to clipboard{ search: "default_search" } Map of logical serving config aliases to Google Cloud placement names. Copy to clipboardcredentials Copy to clipboardobject Copy to clipboardundefined Service account credentials object (Copy to clipboard{ client_email, private_key }). Copy to clipboardkeyFilename Copy to clipboardstring Copy to clipboardundefined Absolute path to service account JSON key file. Copy to clipboardapiEndpoint Copy to clipboardstring Derived Custom Retail API endpoint (e.g. Copy to clipboard"${location}-retail.googleapis.com"). Copy to clipboardupdateDebounceMs Copy to clipboardnumber Copy to clipboard1000 Coalesce debounce delay in milliseconds for individual product updates. Copy to clipboardeventToggles Copy to clipboardobject Copy to clipboardundefined Copy to clipboard{ disableProductCreated, disableProductUpdated, disableProductDeleted }.
Initial Catalog Ingestion
To populate your Google Cloud Retail API catalog with all existing Medusa products, run the bulk import script using the Medusa CLI:
1npx medusa exec ./node_modules/medusa-ai-commerce-search/dist/scripts/import-catalog.js
This workflow:
- Queries Medusa products using full category hierarchies (Copy to clipboard
categories.parent_category...) and collection metadata (Copy to clipboardcollection.id, Copy to clipboardcollection.title, Copy to clipboardcollection.handle). - Applies product option mappings defined in Medusa Admin settings.
- Batches products inline via Copy to clipboard
importProductswith incremental reconciliation.
Alternatively, trigger the import programmatically or from an admin tool via Copy to clipboardPOST /admin/ai-search/catalog/import.
Store & Admin API Endpoints
Store Search (Copy to clipboardPOST /store/ai-search/search)
Searches the product catalog using Google Cloud Retail API.
Request Body:
1234567891011121314151617181920{"q": "running shoes","visitorId": "visitor_xyz","orderBy": "price desc","enableQueryExpansion": true,"filters": {"categories": ["Shoes"],"price": {"min": 50,"max": 200},"attributes": {"sizes": ["M", "L"]}},"facets": ["categories", "brands", "sizes"],"enableDynamicFacets": true,"pageToken": "next_page_token_xyz","options": {"skip": 0,
Pagination, Sorting & Expansion Parameters:
- Copy to clipboard
pageToken: Continuation token (Copy to clipboardnextPageTokenfrom a previous search response) to fetch the next page of results (accepted at the top level or inside Copy to clipboardoptions). - Copy to clipboard
offset/ Copy to clipboardpageSize: Top-level pagination alternatives to Copy to clipboardoptions.offset/ Copy to clipboardoptions.skipand Copy to clipboardoptions.limit/ Copy to clipboardoptions.take. - Copy to clipboard
orderBy: Ordering expression string (e.g., Copy to clipboard"price desc", Copy to clipboard"price"; trailing Copy to clipboard"asc"such as Copy to clipboard"price asc"is automatically normalized to Copy to clipboard"price"for Google Cloud Retail API). - Copy to clipboard
queryExpansionSpec: Object specification for query expansion (e.g., Copy to clipboard{ condition: "AUTO" }). - Copy to clipboard
queryExpansionCondition: Query expansion condition string (e.g., Copy to clipboard"AUTO", Copy to clipboard"DISABLED"), mapped to Copy to clipboard{ condition: queryExpansionCondition }. - Copy to clipboard
enableQueryExpansion: When Copy to clipboardtrue, automatically enables Copy to clipboard{ condition: "AUTO" }.
Response Body:
1234567891011121314151617181920{"hits": [{"id": "prod_123","title": "Air Zoom Running Shoe","description": "High performance road running shoe","thumbnail": "https://...","price": 120,"currency_code": "USD"}],"estimatedTotalHits": 42,"attributionToken": "token-123","nextPageToken": "next_page_token_abc","facets": [{"key": "categories","values": [{ "value": "Shoes", "count": 42 }]
Store Events (Copy to clipboardPOST /store/ai-search/events)
Records storefront user events in the Google Cloud Retail API for personalization, ranking, and recommendations.
Request Body:
123456789101112{"userEvent": {"eventType": "detail-page-view","visitorId": "visitor_xyz","productDetails": [{"product": { "id": "prod_123" }}],"uri": "/products/air-zoom-running-shoe"}}
Supported event types include:
- Copy to clipboard
search - Copy to clipboard
detail-page-view - Copy to clipboard
add-to-cart - Copy to clipboard
remove-from-cart - Copy to clipboard
category-page-view - Copy to clipboard
home-page-view - Copy to clipboard
shopping-cart-page-view - Copy to clipboard
purchase-complete
Store Recommendations (Copy to clipboardPOST /store/ai-search/recommendations)
Fetches personalized product recommendations for a serving configuration.
Request Body:
123456789101112{"servingConfig": "recommendations","userEvent": {"eventType": "shopping-cart-page-view","visitorId": "visitor_xyz","productDetails": [{"product": { "id": "prod_123" }}]}}
Response Body:
123456{"results": [{ "id": "prod_456", "product": { "title": "Running Socks" } }],"attributionToken": "rec-token-abc"}
Admin Options Mapping (Copy to clipboardGET & Copy to clipboardPOST /admin/ai-search/options-mapping)
Manages mapping of Medusa product options to Google Retail attributes in store metadata.
- Copy to clipboard
GET /admin/ai-search/options-mapping: Returns Copy to clipboard{ mapping: { "color": "colorInfo", "size": "sizes" }, available_options: ["color", "size"] }. - Copy to clipboard
POST /admin/ai-search/options-mapping: Saves Copy to clipboard{ mapping: { ... } }into store metadata.
Admin Bulk Ingest (Copy to clipboardPOST /admin/ai-search/catalog/import)
Runs the Copy to clipboardinitial-catalog-import workflow and returns Copy to clipboard{ status: "completed", products: <count> }.
Storefront Client SDK (Copy to clipboardmedusa-ai-commerce-search-client)
Copy to clipboardmedusa-ai-commerce-search-client is a zero-dependency client that tracks user events and manages visitor cookies automatically.
Initialization
12345678910import { createRetailTracker } from "medusa-ai-commerce-search-client";export const tracker = createRetailTracker({backendUrl: process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL || "http://localhost:9000",publishableKey: process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,// Optional custom visitor ID resolver (defaults to managed '_medusa_vid' cookie):// getVisitorId: () => getCookie("_medusa_vid"),// getUserId: () => authState?.customerId,debug: process.env.NODE_ENV !== "production",});
Tracking Search
Pass the query, attribution token from the search response, and optionally products / product details and the URI:
1234567await tracker.search({query: "wool jacket",attributionToken: searchResponse.attributionToken,uri: window.location.pathname,products: ["prod_1", "prod_2"],orderBy: "price asc",});
Tracking Product Views (PDP)
1234await tracker.detailPageView({productId: product.id,uri: window.location.pathname,});
Tracking Cart Actions
1234567891011121314151617// Add to cartawait tracker.addToCart({productId: item.variant.product_id,variantId: item.variant.id,quantity: item.quantity,cartId: cart.id,price: item.unit_price,currencyCode: cart.currency_code,});// Remove from cartawait tracker.removeFromCart({productId: item.variant.product_id,variantId: item.variant.id,quantity: item.quantity,cartId: cart.id,});
Tracking Browsing Pages
123456789101112131415// Home pageawait tracker.homePageView({ uri: "/" });// Category pageawait tracker.categoryPageView({category: "Jackets",uri: "/categories/jackets",});// Cart drawer or cart pageawait tracker.shoppingCartPageView({cartId: cart.id,items: cart.items.map((i) => ({ productId: i.product_id, quantity: i.quantity })),uri: "/cart",});
Tracking Purchases (Conversion)
1234567891011await tracker.purchaseComplete({orderId: order.id,revenue: order.total,currencyCode: order.currency_code,items: order.items.map((item) => ({productId: item.product_id,variantId: item.variant_id,quantity: item.quantity,price: item.unit_price,})),});
Real-Time Event Subscribers
- Copy to clipboard
order.placed:- Queries order items, customer ID, email, total, currency, and metadata.
- Prefers Copy to clipboard
order.metadata.visitor_id(or Copy to clipboardvisitorId) before falling back to Copy to clipboardcustomer_idor Copy to clipboardemail. - Maps line items to Copy to clipboard
productDetailswith quantity and writes the Copy to clipboardpurchase-completeevent to the Google Retail API. - Automatically resolves Copy to clipboard
AiUserEventsServiceusing configured module options if not registered in the root container.
- Copy to clipboard
product.created/ Copy to clipboardproduct.updated/ Copy to clipboardproduct.deleted:- Ingests or removes product documents with automatic debouncing and variant handling.
Admin UI: Option Mapping
Navigate to Settings > AI Commerce Search (Copy to clipboard/admin/settings/ai-search) in the Medusa Admin dashboard to map options like:
- Copy to clipboard
size-> Copy to clipboardsizes - Copy to clipboard
color-> Copy to clipboardcolorInfo - Copy to clipboard
brand-> Copy to clipboardbrands - Copy to clipboard
material-> Copy to clipboardmaterials - Copy to clipboard
pattern-> Copy to clipboardpatterns - Copy to clipboard
condition-> Copy to clipboardconditions - Custom attributes -> Copy to clipboard
attributes.<key>
Limitations
- Copy to clipboard
deleteAllDocumentsis not directly supported by Google Cloud Retail API without branch recreation. Deleting individual documents cascades variant deletion safely.
License
MIT © Farid Ghar
