Overview
Icon for AI Commerce Search

AI Commerce Search

Google Vertex AI retail 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 clipboardPOST /store/ai-search/search)
    • Store Events (Copy to clipboardPOST /store/ai-search/events)
    • Store Recommendations (Copy to clipboardPOST /store/ai-search/recommendations)
    • Admin Options Mapping (Copy to clipboardGET & Copy to clipboardPOST /admin/ai-search/options-mapping)
    • Admin Bulk Ingest (Copy to clipboardPOST /admin/ai-search/catalog/import)
  • Storefront Client SDK (Copy to clipboardmedusa-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 clipboardparent_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 clipboardColor, 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:

npm install medusa-ai-commerce-search

For your storefront (Next.js, Remix, Astro, or vanilla JS), install the companion client tracker:

npm 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:

npx medusa-ai-commerce-search setup

What the Setup Wizard Automates:

  1. Google Cloud Authentication: Detects your active Copy to clipboardgcloud account or guides you through logging in with Copy to clipboardgcloud auth login.
  2. 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.
  3. Billing Verification & Linkage: Inspects project billing status and links an active Google Cloud Billing account (Copy to clipboardgcloud billing projects link).
  4. API Enablement: Automatically enables Copy to clipboardretail.googleapis.com and Copy to clipboardserviceusage.googleapis.com.
  5. Dedicated Service Account: Creates a dedicated service account Copy to clipboardmedusa-retail-search and grants it Copy to clipboardroles/retail.admin, with automated retries and exponential backoff to handle Google Cloud IAM eventual consistency and replication delays.
  6. Credential Export & Security: Exports the service account key JSON to Copy to clipboard./gcp-retail-key.json with strict file permissions (Copy to clipboard0600) and automatically adds it to Copy to clipboard.gitignore.
  7. Environment Configuration: Safely appends or updates required variables in your Copy to clipboard.env:
    • Copy to clipboardGCP_RETAIL_PROJECT_ID: Your target Google Cloud project ID.
    • Copy to clipboardGCP_RETAIL_KEY_PATH: Path to your exported credentials key JSON.
  8. 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 clipboardbranches/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:

npx 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:

npx 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:

  1. Automated Setup (Recommended): Run Copy to clipboardnpx medusa-ai-commerce-search setup as described above to automate credentials and project setup.
  2. Application Default Credentials (ADC): When running in Google Cloud or with Copy to clipboardGOOGLE_APPLICATION_CREDENTIALS configured, Copy to clipboardprojectId and Copy to clipboardquotaProjectId are automatically forwarded to Retail API clients.
  3. Service Account Key File: Specify Copy to clipboardkeyFilename: process.env.GCP_RETAIL_KEY_PATH || "./gcp-retail-key.json".
  4. 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:

  1. Open the Google Cloud Console.
  2. Create or select a Google Cloud project and ensure billing is enabled.
  3. Enable the Retail API under APIs & Services > Library.
  4. Navigate to IAM & Admin > Service Accounts, create a service account named Copy to clipboardmedusa-retail-search, and assign the Copy to clipboardRetail Admin (Copy to clipboardroles/retail.admin) role.
  5. Create and download a JSON key for the service account.
  6. Save the key file to your Medusa project root as Copy to clipboardgcp-retail-key.json (ensure it is added to Copy to clipboard.gitignore).
  7. Add Copy to clipboardGCP_RETAIL_PROJECT_ID and Copy to clipboardGCP_RETAIL_KEY_PATH to your Copy to clipboard.env file.

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):

import { 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:

npx medusa exec ./node_modules/medusa-ai-commerce-search/dist/scripts/import-catalog.js

This workflow:

  • Queries Medusa products using full category hierarchies (Copy to clipboardcategories.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 clipboardimportProducts with 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:

{
"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 clipboardpageToken: Continuation token (Copy to clipboardnextPageToken from a previous search response) to fetch the next page of results (accepted at the top level or inside Copy to clipboardoptions).
  • Copy to clipboardoffset / Copy to clipboardpageSize: Top-level pagination alternatives to Copy to clipboardoptions.offset / Copy to clipboardoptions.skip and Copy to clipboardoptions.limit / Copy to clipboardoptions.take.
  • Copy to clipboardorderBy: 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 clipboardqueryExpansionSpec: Object specification for query expansion (e.g., Copy to clipboard{ condition: "AUTO" }).
  • Copy to clipboardqueryExpansionCondition: Query expansion condition string (e.g., Copy to clipboard"AUTO", Copy to clipboard"DISABLED"), mapped to Copy to clipboard{ condition: queryExpansionCondition }.
  • Copy to clipboardenableQueryExpansion: When Copy to clipboardtrue, automatically enables Copy to clipboard{ condition: "AUTO" }.

Response Body:

{
"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:

{
"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 clipboardsearch
  • Copy to clipboarddetail-page-view
  • Copy to clipboardadd-to-cart
  • Copy to clipboardremove-from-cart
  • Copy to clipboardcategory-page-view
  • Copy to clipboardhome-page-view
  • Copy to clipboardshopping-cart-page-view
  • Copy to clipboardpurchase-complete

Store Recommendations (Copy to clipboardPOST /store/ai-search/recommendations)

Fetches personalized product recommendations for a serving configuration.

Request Body:

{
"servingConfig": "recommendations",
"userEvent": {
"eventType": "shopping-cart-page-view",
"visitorId": "visitor_xyz",
"productDetails": [
{
"product": { "id": "prod_123" }
}
]
}
}

Response Body:

{
"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 clipboardGET /admin/ai-search/options-mapping: Returns Copy to clipboard{ mapping: { "color": "colorInfo", "size": "sizes" }, available_options: ["color", "size"] }.
  • Copy to clipboardPOST /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

import { 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",
});

Pass the query, attribution token from the search response, and optionally products / product details and the URI:

await tracker.search({
query: "wool jacket",
attributionToken: searchResponse.attributionToken,
uri: window.location.pathname,
products: ["prod_1", "prod_2"],
orderBy: "price asc",
});

Tracking Product Views (PDP)

await tracker.detailPageView({
productId: product.id,
uri: window.location.pathname,
});

Tracking Cart Actions

// Add to cart
await 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 cart
await tracker.removeFromCart({
productId: item.variant.product_id,
variantId: item.variant.id,
quantity: item.quantity,
cartId: cart.id,
});

Tracking Browsing Pages

// Home page
await tracker.homePageView({ uri: "/" });
// Category page
await tracker.categoryPageView({
category: "Jackets",
uri: "/categories/jackets",
});
// Cart drawer or cart page
await tracker.shoppingCartPageView({
cartId: cart.id,
items: cart.items.map((i) => ({ productId: i.product_id, quantity: i.quantity })),
uri: "/cart",
});

Tracking Purchases (Conversion)

await 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

  1. Copy to clipboardorder.placed:
    • Queries order items, customer ID, email, total, currency, and metadata.
    • Prefers Copy to clipboardorder.metadata.visitor_id (or Copy to clipboardvisitorId) before falling back to Copy to clipboardcustomer_id or Copy to clipboardemail.
    • Maps line items to Copy to clipboardproductDetails with quantity and writes the Copy to clipboardpurchase-complete event to the Google Retail API.
    • Automatically resolves Copy to clipboardAiUserEventsService using configured module options if not registered in the root container.
  2. Copy to clipboardproduct.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 clipboardsize -> Copy to clipboardsizes
  • Copy to clipboardcolor -> Copy to clipboardcolorInfo
  • Copy to clipboardbrand -> Copy to clipboardbrands
  • Copy to clipboardmaterial -> Copy to clipboardmaterials
  • Copy to clipboardpattern -> Copy to clipboardpatterns
  • Copy to clipboardcondition -> Copy to clipboardconditions
  • Custom attributes -> Copy to clipboardattributes.<key>

Limitations

  • Copy to clipboarddeleteAllDocuments is not directly supported by Google Cloud Retail API without branch recreation. Deleting individual documents cascades variant deletion safely.

License

MIT © Farid Ghar

You may also like

Browse all integrations

Build your own

Develop your own custom integration

Build your own integration with our API to speed up your processes. Make your integration available via npm for it to be shared in our Library with the broader Medusa community.

gift card interface

Ready to build your custom commerce setup?