Typesense
Typesense search with hybrid AI search
medusa-plugin-typesense
A full-featured Typesense Search, Vector/Hybrid AI Discovery, Merchandising, and Custom Entity Indexing Plugin for Medusa v2 (Copy to clipboard^2.21.0).
Built specifically for Medusa Copy to clipboard2.21+ with a Dual Architecture:
- Standalone Typesense Module, Workflows, Subscribers, REST APIs & Admin UI (Copy to clipboard
/app/typesense): Zero-downtime collection alias rebuilds, Multi-way & One-way Synonyms, Curations/Overrides (pinning, hiding, promo banners, scheduled windows), Stopwords, Vector/Hybrid search, Conversational RAG, Search Analytics, Custom Entities indexing, and Hydrated Storefront APIs. - Native Medusa Copy to clipboard
2.21Search Module Provider (Copy to clipboardmedusa-plugin-typesense/providers/typesense) & Index Factories (Copy to clipboardmedusa-plugin-typesense/indexes): Plugs directly into Copy to clipboard@medusajs/medusa/searchwith Copy to clipboarddefineProductSearchIndex, Copy to clipboarddefineCategorySearchIndex, Copy to clipboarddefineCollectionSearchIndex, and Copy to clipboarddefineCustomSearchIndex.
Table of Contents
- Features
- Compatibility
- Architecture
- Installation
- Configuration (Copy to clipboard
medusa-config.ts)- Environment Variables (Copy to clipboard
.env) - Full Configuration Reference
- Environment Variables (Copy to clipboard
- Medusa 2.21 Native Search Index Factories (Copy to clipboard
src/search/) - Built-In Schemas & Custom Entities
- Built-In Entities (Copy to clipboard
products, Copy to clipboardcategories, Copy to clipboardcollections) - Indexing Custom Entities (Copy to clipboard
brands, Copy to clipboardvendors, Copy to clipboardreviews, etc.)
- Built-In Entities (Copy to clipboard
- Vector, Semantic & Hybrid AI Search
- Multi-Language & Localization
- Merchandising: Synonyms, Curations & Stopwords
- Storefront API Reference (Copy to clipboard
/store/typesense/*)- Hydrated Product Search (Copy to clipboard
GET / POST /store/typesense/products) - Hydrated Category & Collection Search
- Federated Multi-Entity Search (Copy to clipboard
POST /store/typesense/search) - Structured Filter DSL
- Scoped InstantSearch Key (Copy to clipboard
GET /store/typesense/token) - Conversational RAG Search (Copy to clipboard
POST /store/typesense/chat) - Search Analytics Tracking (Copy to clipboard
POST /store/typesense/analytics)
- Hydrated Product Search (Copy to clipboard
- Admin API Reference (Copy to clipboard
/admin/typesense/*) - Admin UI Dashboard & Product Widget
- Workflows & Programmatic Usage
- Security & Multi-Tenant Guarantees
- Development & Testing
- License
Features
- Typo-Tolerant Full-Text Search — Prefix matching, configurable field weights (Copy to clipboard
query_by_weights), custom token separators (Copy to clipboard-, Copy to clipboard_, Copy to clipboard/), highlighting (Copy to clipboard<mark>), snippets, and result grouping (Copy to clipboardgroup_by). - Faceted & Disjunctive Search — Value facets, numeric range facets (Copy to clipboard
min_price), statistical facets (Copy to clipboardmin, Copy to clipboardmax, Copy to clipboardavg, Copy to clipboardsum), and automatic disjunctive faceting batched into a single Typesense Copy to clipboardmulti_searchrequest. - Vector, Semantic & Hybrid AI Search — Supports Typesense built-in local ONNX models (Copy to clipboard
ts/all-MiniLM-L6-v2, Copy to clipboardts/e5-small, Copy to clipboardts/multilingual-e5-small— no external API keys required), OpenAI/external embedders (Copy to clipboardopenai/text-embedding-3-small), or custom Copy to clipboardfloat[]vectors with configurable Copy to clipboardalpharank fusion (Copy to clipboard0.0keyword to Copy to clipboard1.0semantic). - Conversational Search (RAG) — Multi-turn natural-language shopping assistant powered by Typesense Conversation Models (Copy to clipboard
POST /store/typesense/chat). - Built-in & Custom Entity Indexing — Out-of-the-box schemas and transformers for Copy to clipboard
products, Copy to clipboardcategories, and Copy to clipboardcollections, plus first-class support for custom entities (Copy to clipboardbrands, Copy to clipboardvendors, Copy to clipboardreviews, Copy to clipboardarticles, etc.) via Copy to clipboardcustomEntitiesconfig, runtime Admin UI registration, or Copy to clipboarddefineCustomSearchIndex(). - Multi-Language / Localization — Per-locale collections (Copy to clipboard
medusa_products_en, Copy to clipboardmedusa_products_es) with Typesense field-level locale tokenization (Copy to clipboardja, Copy to clipboardzh, Copy to clipboardko, Copy to clipboardde, Copy to clipboardfr, Copy to clipboardes, etc.) and automatic translation resolution. - Zero-Downtime Alias Reindexing — Builds a fresh timestamped physical collection (Copy to clipboard
medusa_products_v_1791000000), migrates existing Synonyms and Curations/Overrides, imports documents in batches, atomically swaps the collection alias (Copy to clipboardmedusa_products), and prunes old physical collections. - Merchandising Studio — Manage Multi-way & One-way Synonyms, Curations/Overrides (pin products to exact positions, exclude products, custom filter/sort rules, attach promo banner metadata, schedule active date windows), and Stopwords Sets via Admin UI and REST APIs.
- Hydrated Storefront Endpoints — Copy to clipboard
/store/typesense/products, Copy to clipboard/store/typesense/categories, and Copy to clipboard/store/typesense/collectionscombine Typesense search speed with Medusa's Copy to clipboardquery.graphto return live Copy to clipboardcalculated_price, tax, Copy to clipboardvariants.inventory_quantity, and automatic Copy to clipboardsales_channel_idscoping. - Scoped Search-Only API Keys for InstantSearch — Copy to clipboard
GET /store/typesense/tokengenerates short-lived HMAC-signed Typesense Scoped Search Keys with embedded Copy to clipboardstatus:=publishedand Copy to clipboardsales_channel_idsrestrictions for safe Copy to clipboardtypesense-instantsearch-adapterusage in storefronts. - Search Analytics & Telemetry — Tracks search queries, hit counts, execution latency, zero-result queries, click-through rate (CTR), and conversion rate in PostgreSQL (Copy to clipboard
mpt_search_analytics). - Admin Dashboard & Product Widget — Full Admin UI at Copy to clipboard
/app/typesense(Overview, Collections & Custom Entities, Merchandising Studio, AI Search Playground, Search Analytics) plus a Product Detail sidebar widget (Copy to clipboardproduct.details.side.after).
Compatibility
Package Version Medusa Typesense Server Node.js Copy to clipboardmedusa-plugin-typesense Copy to clipboard^1.0.0 Copy to clipboard^2.21.0 (Copy to clipboard2.21.2 tested) Copy to clipboard>= 26.0 (Copy to clipboard27.x – 29.x recommended) Copy to clipboard>= 20.19.0 || >= 22.12.0
Architecture
1234567891011121314151617181920flowchart TBsubgraph Medusa["Medusa v2.21 Host Application"]NativeSearch["@medusajs/medusa/search Module"]Sub["Event Subscribers & Nightly Cron Job"]WF["Workflows (Rollback & Zero-Downtime Reindex)"]StoreAPI["Store REST APIs (/store/typesense/*)"]AdminAPI["Admin REST APIs (/admin/typesense/*)"]AdminUI["Admin UI (/app/typesense + Product Widget)"]endsubgraph Plugin["medusa-plugin-typesense"]Provider["TypesenseSearchProviderService\n(medusa-plugin-typesense/providers/typesense)"]Indexes["Index Factories\n(medusa-plugin-typesense/indexes)"]Module["TypesenseModuleService\n(medusa-plugin-typesense/modules/typesense)"]Filter["Safe Filter Compiler & Scoped Key Generator"]endsubgraph TS["Typesense Cluster"]Aliases["Collection Aliases\n({prefix}_products, {prefix}_{entity}_{locale})"]Embeddings["Vector / Hybrid Search & Conversational RAG"]
Installation
12345npm install medusa-plugin-typesense typesense# oryarn add medusa-plugin-typesense typesense# orpnpm add medusa-plugin-typesense typesense
Configuration (Copy to clipboardmedusa-config.ts)
Environment Variables (Copy to clipboard.env)
1234TYPESENSE_HOST=http://127.0.0.1:8108TYPESENSE_API_KEY=xyz_admin_api_keyTYPESENSE_SEARCH_ONLY_API_KEY=xyz_search_only_api_keyTYPESENSE_COLLECTION_PREFIX=medusa
Registering the Plugin & Modules
You can use the Standalone Typesense Module, the Native Medusa 2.21 Search Provider, or both together:
1234567891011121314151617181920import { defineConfig, Modules } from "@medusajs/framework/utils"export default defineConfig({plugins: [{resolve: "medusa-plugin-typesense",options: {},},],modules: [// 1. Standalone Typesense Module// Powers /store/typesense/*, /admin/typesense/*, Admin UI (/app/typesense),// Event Subscribers, Workflows, Merchandising, Analytics & Zero-Downtime Alias Sync{resolve: "medusa-plugin-typesense/modules/typesense",options: {host: process.env.TYPESENSE_HOST || "http://127.0.0.1:8108",apiKey: process.env.TYPESENSE_API_KEY!,searchOnlyApiKey: process.env.TYPESENSE_SEARCH_ONLY_API_KEY,collectionPrefix: process.env.TYPESENSE_COLLECTION_PREFIX || "medusa",
Run database migrations to create the Copy to clipboardmpt_sync_job, Copy to clipboardmpt_entity_config, and Copy to clipboardmpt_search_analytics tables:
1npx medusa db:migrate
Full Configuration Reference
Option Type Default Description Copy to clipboardhost Copy to clipboardstring Copy to clipboard"http://127.0.0.1:8108" Primary Typesense URL (Copy to clipboardhttp(s)://host:port) or hostname Copy to clipboardport Copy to clipboardnumber Copy to clipboard8108 / Copy to clipboard443 Typesense port if not specified in Copy to clipboardhost Copy to clipboardprotocol Copy to clipboard"http" | "https" Copy to clipboard"http" Protocol if not specified in Copy to clipboardhost Copy to clipboardnodes Copy to clipboardTypesenseNodeConfig[] Copy to clipboardundefined Multi-node High Availability cluster array (Copy to clipboard[{ host, port, protocol }]) Copy to clipboardapiKey Copy to clipboardstring Required Server-side Typesense Admin API Key (never exposed to clients) Copy to clipboardsearchOnlyApiKey Copy to clipboardstring Copy to clipboardundefined Search-only parent key used to sign HMAC Scoped Keys in Copy to clipboard/store/typesense/token Copy to clipboardconnectionTimeoutSeconds Copy to clipboardnumber Copy to clipboard10 Client request timeout in seconds Copy to clipboardretryIntervalSeconds Copy to clipboardnumber Copy to clipboard1 Delay between retries across cluster nodes Copy to clipboardnumRetries Copy to clipboardnumber Copy to clipboard3 Number of automatic retries on transient errors Copy to clipboardcollectionPrefix Copy to clipboardstring Copy to clipboard"medusa" Prefix for collection aliases (Copy to clipboard{prefix}_{entity}) Copy to clipboardbatchSize Copy to clipboardnumber Copy to clipboard250 Number of documents per JSONL import chunk Copy to clipboardautoIndex Copy to clipboardboolean Copy to clipboardtrue Automatically index changes on Medusa Copy to clipboardproduct.*, Copy to clipboardproduct-category.*, Copy to clipboardproduct-collection.* events Copy to clipboardzeroDowntimeSwap Copy to clipboardboolean Copy to clipboardtrue Build Copy to clipboard{alias}_v_{timestamp} physical collection and atomically flip alias Copy to clipboarddefaultLocale Copy to clipboardstring Copy to clipboard"en" Default locale code Copy to clipboardlocales Copy to clipboardstring[] Copy to clipboard["en"] All active locales to index (creates Copy to clipboard{prefix}_{entity}_{locale} when Copy to clipboard> 1 or non-default) Copy to clipboardembedder Copy to clipboardTypesenseEmbedderConfig Copy to clipboard{ enabled: false } Global default vector embedder configuration Copy to clipboardconversationModelId Copy to clipboardstring Copy to clipboardundefined Default Typesense Conversation Model ID for Copy to clipboard/store/typesense/chat Copy to clipboardscopedKeyDefaultTtlSeconds Copy to clipboardnumber Copy to clipboard3600 Default TTL (in seconds) for scoped search tokens (capped at Copy to clipboard86400) Copy to clipboardanalytics Copy to clipboard{ enabled?: boolean, retentionDays?: number } Copy to clipboard{ enabled: true, retentionDays: 90 } Search analytics logging configuration Copy to clipboardentities Copy to clipboardPartial<Record<BuiltInEntityName, Partial<TypesenseEntityConfig>>> Copy to clipboard{} Override schemas, Copy to clipboardqueryBy, Copy to clipboardfacetBy, or Copy to clipboardtransformer for built-in Copy to clipboardproducts, Copy to clipboardcategories, or Copy to clipboardcollections Copy to clipboardcustomEntities Copy to clipboardRecord<string, Partial<TypesenseEntityConfig>> Copy to clipboard{} Register custom Medusa module entities (e.g., Copy to clipboardbrands, Copy to clipboardvendors, Copy to clipboardreviews)
Medusa 2.21 Native Search Index Factories (Copy to clipboardsrc/search/)
When using Medusa Copy to clipboard2.21's native Copy to clipboard@medusajs/medusa/search module (Copy to clipboardModules.SEARCH), create index definitions inside your Medusa app's Copy to clipboardsrc/search/ directory using the factories exported from Copy to clipboardmedusa-plugin-typesense/indexes:
1234567// src/search/products.tsimport { defineProductSearchIndex } from "medusa-plugin-typesense/indexes"export default defineProductSearchIndex({enableEmbedding: false,embeddingModel: "ts/all-MiniLM-L6-v2",})
1234// src/search/categories.tsimport { defineCategorySearchIndex } from "medusa-plugin-typesense/indexes"export default defineCategorySearchIndex()
1234// src/search/collections.tsimport { defineCollectionSearchIndex } from "medusa-plugin-typesense/indexes"export default defineCollectionSearchIndex()
1234567891011121314// src/search/brands.ts (Custom Entity Index)import { defineCustomSearchIndex } from "medusa-plugin-typesense/indexes"export default defineCustomSearchIndex({name: "brands",entity: "brand",graphFields: ["id", "name", "slug", "description", "is_active", "created_at"],customSchemaFields: [{ name: "name", type: "string", sort: true },{ name: "slug", type: "string", facet: true },{ name: "description", type: "string", optional: true },{ name: "is_active", type: "bool", facet: true },],})
Built-In Schemas & Custom Entities
Built-In Entities (Copy to clipboardproducts, Copy to clipboardcategories, Copy to clipboardcollections)
- Copy to clipboard
products(Copy to clipboardmedusa_products):- Full-text fields (Copy to clipboard
queryBy): Copy to clipboardtitle(weight Copy to clipboard5), Copy to clipboardsubtitle(Copy to clipboard4), Copy to clipboardvariant_titles(Copy to clipboard3), Copy to clipboardvariant_skus(Copy to clipboard4), Copy to clipboardbrand(Copy to clipboard3), Copy to clipboardcategory_names(Copy to clipboard3), Copy to clipboardtags(Copy to clipboard3), Copy to clipboardcollection_titles(Copy to clipboard2), Copy to clipboarddescription(Copy to clipboard2), Copy to clipboardhandle(Copy to clipboard2). - Facet fields (Copy to clipboard
facetBy): Copy to clipboardstatus, Copy to clipboardcategory_ids, Copy to clipboardcategory_handles, Copy to clipboardcategory_names, Copy to clipboardcollection_ids, Copy to clipboardcollection_handles, Copy to clipboardcollection_titles, Copy to clipboardtags, Copy to clipboardtype_id, Copy to clipboardtype_value, Copy to clipboardoption_values, Copy to clipboardin_stock, Copy to clipboardsales_channel_ids, Copy to clipboardcurrencies, Copy to clipboardbrand, Copy to clipboardis_giftcard, Copy to clipboarddiscountable. - Sortable numeric fields: Copy to clipboard
min_price, Copy to clipboardmax_price, Copy to clipboardinventory_quantity, Copy to clipboardvariant_count, Copy to clipboardpopularity_score, Copy to clipboardsales_count, Copy to clipboardrating_average, Copy to clipboardcreated_at_ts, Copy to clipboardupdated_at_ts. - Storefront security filter: Copy to clipboard
status:=published+ active Copy to clipboardsales_channel_ids.
- Full-text fields (Copy to clipboard
- Copy to clipboard
categories(Copy to clipboardmedusa_categories):- Full-text fields (Copy to clipboard
queryBy): Copy to clipboardname(Copy to clipboard5), Copy to clipboardhandle(Copy to clipboard3), Copy to clipboarddescription(Copy to clipboard2), Copy to clipboardbreadcrumb_names(Copy to clipboard2). - Facet fields (Copy to clipboard
facetBy): Copy to clipboardparent_category_id, Copy to clipboardancestor_ids, Copy to clipboardis_active, Copy to clipboardis_internal, Copy to clipboarddepth. - Storefront security filter: Copy to clipboard
is_active:=true && is_internal:=false.
- Full-text fields (Copy to clipboard
- Copy to clipboard
collections(Copy to clipboardmedusa_collections):- Full-text fields (Copy to clipboard
queryBy): Copy to clipboardtitle(Copy to clipboard5), Copy to clipboardhandle(Copy to clipboard3). - Sortable fields: Copy to clipboard
product_count, Copy to clipboardcreated_at_ts, Copy to clipboardupdated_at_ts.
- Full-text fields (Copy to clipboard
Indexing Custom Entities (Copy to clipboardbrands, Copy to clipboardvendors, Copy to clipboardreviews, etc.)
You can index any custom Medusa module entity in three ways:
Method 1: Static Configuration in Copy to clipboardmedusa-config.ts
1234567891011121314151617181920customEntities: {reviews: {graphEntity: "product_review",graphFields: ["id","title","content","rating","product_id","customer_name","status","created_at",],fields: [{ name: "id", type: "string" },{ name: "title", type: "string", sort: true },{ name: "content", type: "string" },{ name: "rating", type: "int32", facet: true, sort: true },{ name: "product_id", type: "string", facet: true },{ name: "customer_name", type: "string", optional: true },
Method 2: Dynamic Runtime Registration via Admin API or Admin UI
Use the Collections & Custom Entities tab in Copy to clipboard/app/typesense or Copy to clipboardPOST /admin/typesense/entities:
1234567891011curl -X POST "http://localhost:9000/admin/typesense/entities" \-H "Authorization: Bearer <admin_jwt>" \-H "Content-Type: application/json" \-d '{"entity": "vendors","graphEntity": "vendor","graphFields": ["id", "name", "handle", "description", "country_code", "is_verified", "created_at"],"queryBy": ["name", "handle", "description"],"facetBy": ["country_code", "is_verified"],"storefrontFilterConstraint": "is_verified:=true"}'
Method 3: Syncing Custom Entities from Your Custom Subscribers
1234567891011121314151617181920import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"import { syncEntitiesToTypesenseWorkflow } from "medusa-plugin-typesense/workflows"export default async function brandEventsHandler({event,container,}: SubscriberArgs<{ id: string }>) {await syncEntitiesToTypesenseWorkflow(container).run({input: {entity: "brands",ids: [event.data.id],fullRebuild: false,triggeredBy: `subscriber:${event.name}`,},})}export const config: SubscriberConfig = {event: ["brand.created", "brand.updated"],}
Vector, Semantic & Hybrid AI Search
Copy to clipboardmedusa-plugin-typesense supports three vector embedding strategies:
- Typesense Built-in Local ONNX Models (Zero External API Keys):
123456embedder: {enabled: true,model_name: "ts/all-MiniLM-L6-v2", // or "ts/e5-small", "ts/multilingual-e5-small"field_name: "embedding",embed_from: ["title", "subtitle", "description", "brand", "category_names", "tags"],}
- External Embedding Providers (OpenAI / PaLM / Vertex AI):
1234567embedder: {enabled: true,model_name: "openai/text-embedding-3-small",api_key: process.env.OPENAI_API_KEY,field_name: "embedding",embed_from: ["title", "description", "category_names", "tags"],}
- Custom Pre-Computed Vectors (Copy to clipboard
float[]):
12345embedder: {enabled: true,field_name: "embedding",num_dim: 1536,}
When querying Copy to clipboard/store/typesense/products, Copy to clipboard/store/typesense/search, or Copy to clipboard/admin/typesense/playground, specify:
- Copy to clipboard
mode: "keyword"— Pure lexical BM25/typo-tolerant search. - Copy to clipboard
mode: "semantic"— Pure vector nearest-neighbor search (Copy to clipboardkneighbors, optional Copy to clipboarddistance_threshold). - Copy to clipboard
mode: "hybrid"— Combines lexical and vector search using rank fusion (Copy to clipboardalpha: 0.3weights 70% keyword + 30% vector similarity).
Multi-Language & Localization
Configure multiple locales in Copy to clipboardmedusa-config.ts:
12defaultLocale: "en",locales: ["en", "es", "de", "ja"],
- Each locale gets an isolated collection alias (Copy to clipboard
medusa_products_en, Copy to clipboardmedusa_products_es, Copy to clipboardmedusa_products_de, Copy to clipboardmedusa_products_ja). - Text fields automatically apply Typesense's language-specific tokenizer (Copy to clipboard
locale: "ja", Copy to clipboard"de", etc.). - Transformers automatically resolve localized field values from Copy to clipboard
record.translations[locale]or Copy to clipboardrecord.metadata.translations[locale]before falling back to the base fields. - Pass Copy to clipboard
"locale": "es"(or Copy to clipboard?locale=es) in Storefront and Admin API requests to query that locale's index.
Merchandising: Synonyms, Curations & Stopwords
Manage merchandising rules from the Merchandising Studio tab at Copy to clipboard/app/typesense or via Copy to clipboard/admin/typesense/*:
1. Multi-Way & One-Way Synonyms
- Multi-Way Synonym (omit Copy to clipboard
root): Searching any term matches all others (Copy to clipboard["sneakers", "trainers", "running shoes", "kicks"]). - One-Way Synonym (specify Copy to clipboard
root): Searching Copy to clipboard" blazer "also matches Copy to clipboard"sport coat"and Copy to clipboard"suit jacket", but searching Copy to clipboard"suit jacket"does not expand back.
2. Curations / Overrides
- Pin Documents (Copy to clipboard
includes): Pin specific product IDs to exact 1-based positions (Copy to clipboardposition: 1, Copy to clipboardposition: 2) when a query matches (Copy to clipboardmatch: "exact" | "contains"). - Hide Documents (Copy to clipboard
excludes): Exclude specific product IDs from appearing for a query. - Dynamic Filter & Sort Injection: Automatically apply Copy to clipboard
filter_by(e.g., Copy to clipboardin_stock:=true) or Copy to clipboardsort_by(Copy to clipboardpopularity_score:desc) when a shopper searches a curated keyword. - Promo Banner Metadata (Copy to clipboard
metadata): Attach JSON metadata (e.g., Copy to clipboard{ "banner_url": "/summer-sale.jpg", "cta_link": "/collections/summer" }) returned in Copy to clipboardcustom_metadataon storefront responses. - Scheduled Windows: Set Copy to clipboard
effective_from_tsand Copy to clipboardeffective_to_tsUnix timestamps for time-boxed campaigns.
3. Stopwords Sets
Define locale-specific stopword sets (e.g., Copy to clipboard["the", "a", "an", "of", "for"]) that can be applied to queries via Copy to clipboardstopwords.
Storefront API Reference (Copy to clipboard/store/typesense/*)
All storefront endpoints automatically resolve the Publishable API Key (Copy to clipboardx-publishable-api-key) to its associated Copy to clipboardsales_channel_ids and enforce Copy to clipboardstatus:=published (or the entity's Copy to clipboardstorefrontFilterConstraint).
1. Hydrated Product Search (Copy to clipboardGET / Copy to clipboardPOST /store/typesense/products)
Combines Typesense search with Medusa's Copy to clipboardquery.graph to return full Medusa product objects with live Copy to clipboardcalculated_price and Copy to clipboardvariants.inventory_quantity, ordered by Typesense relevance rank.
1234567891011121314151617181920curl -X POST "http://localhost:9000/store/typesense/products" \-H "x-publishable-api-key: pk_01..." \-H "Content-Type: application/json" \-d '{"q": "merino runner","mode": "hybrid","alpha": 0.3,"filters": {"in_stock": true,"category_handles": ["shoes", "trail"]},"facets": ["category_names", "option_values", "brand", "in_stock"],"range_facets": [{"field": "min_price","ranges": [{ "label": "under_100", "from": 0, "to": 10000 },{ "label": "100_to_250", "from": 10000, "to": 25000 }]}
Response:
1234567891011121314151617181920{"hits": [{"id": "prod_01...","title": "Merino Wool Runner","handle": "merino-wool-runner","variants": [{"id": "variant_01...","sku": "MWR-BLK-42","inventory_quantity": 18,"calculated_price": {"calculated_amount": 12000,"currency_code": "usd"}}],"_typesense": {"highlights": [{
2. Hydrated Category & Collection Search
- Copy to clipboard
GET/ Copy to clipboardPOST /store/typesense/categories - Copy to clipboard
GET/ Copy to clipboardPOST /store/typesense/collections
3. Federated Multi-Entity Search (Copy to clipboardPOST /store/typesense/search)
Search across Copy to clipboardproducts, Copy to clipboardcategories, Copy to clipboardcollections, and any custom entities (Copy to clipboardbrands, Copy to clipboardvendors, Copy to clipboardreviews) in a single HTTP request:
12345678910curl -X POST "http://localhost:9000/store/typesense/search" \-H "x-publishable-api-key: pk_01..." \-H "Content-Type: application/json" \-d '{"queries": [{ "entity": "products", "q": "winter jacket", "mode": "hybrid", "limit": 8 },{ "entity": "categories", "q": "winter jacket", "limit": 4 },{ "entity": "brands", "q": "winter jacket", "limit": 4 }]}'
4. Structured Filter DSL
All search endpoints accept a structured Copy to clipboardfilters object that is validated against the entity's schema allowlist and compiled into escaped Typesense Copy to clipboardfilter_by syntax:
12345678{"filters": {"in_stock": true,"category_handles": { "$in": ["shoes", "boots"] },"min_price": { "$gte": 5000, "$lte": 25000 },"$or": [{ "brand": "Allbirds" }, { "tags": ["sustainable", "merino"] }]}}
Supported operators: Copy to clipboard$eq, Copy to clipboard$ne, Copy to clipboard$in, Copy to clipboard$nin, Copy to clipboard$gt, Copy to clipboard$gte, Copy to clipboard$lt, Copy to clipboard$lte, Copy to clipboard$range (Copy to clipboard[min, max]), Copy to clipboard$and, Copy to clipboard$or.
5. Scoped InstantSearch Key (Copy to clipboardGET /store/typesense/token)
Generates a short-lived HMAC-signed Typesense Scoped Search-Only API Key with embedded Copy to clipboardstatus:=published and Copy to clipboardsales_channel_ids constraints so your storefront can query Typesense directly via Copy to clipboardtypesense-instantsearch-adapter:
1234567891011121314151617181920// Example: Next.js Storefront with react-instantsearch & typesense-instantsearch-adapterimport TypesenseInstantSearchAdapter from "typesense-instantsearch-adapter"import {InstantSearch,SearchBox,Hits,RefinementList,} from "react-instantsearch"export async function createStorefrontSearchClient(medusaUrl: string,publishableKey: string) {const res = await fetch(`${medusaUrl}/store/typesense/token?entity=products&ttl_seconds=3600`,{headers: { "x-publishable-api-key": publishableKey },})const tokenData = await res.json()
6. Conversational RAG Search (Copy to clipboardPOST /store/typesense/chat)
12345678curl -X POST "http://localhost:9000/store/typesense/chat" \-H "x-publishable-api-key: pk_01..." \-H "Content-Type: application/json" \-d '{"q": "Which waterproof trail running shoes do you recommend for cold weather?","entity": "products","conversation_id": "conv_optional_existing_id"}'
7. Search Analytics Tracking (Copy to clipboardPOST /store/typesense/analytics)
123456789curl -X POST "http://localhost:9000/store/typesense/analytics" \-H "x-publishable-api-key: pk_01..." \-H "Content-Type: application/json" \-d '{"event_type": "click","query": "merino runner","entity": "products","document_id": "prod_01..."}'
Admin API Reference (Copy to clipboard/admin/typesense/*)
All Admin endpoints require standard Medusa Admin authentication (session cookie, bearer JWT, or secret API key).
Method & Path Description Copy to clipboardGET /admin/typesense/health Cluster health, collection/alias metrics, and recent sync jobs Copy to clipboardGET /admin/typesense/collections List all entity collections, active aliases, and document counts Copy to clipboardPOST /admin/typesense/collections Trigger zero-downtime reindex across all enabled entities Copy to clipboardPOST /admin/typesense/collections/:entity/sync Trigger zero-downtime rebuild (Copy to clipboardfullRebuild: true) or incremental sync (Copy to clipboardids: [...]) for Copy to clipboard:entity Copy to clipboardGET /admin/typesense/entities List built-in and custom entity index configurations Copy to clipboardPOST /admin/typesense/entities Register a new custom entity or update an existing entity config Copy to clipboardDELETE /admin/typesense/entities/:entity Remove a custom entity configuration (and optionally drop its collection) Copy to clipboardGET / POST /admin/typesense/synonyms/:entity List or upsert multi-way / one-way synonyms Copy to clipboardDELETE /admin/typesense/synonyms/:entity/:id Delete a synonym rule Copy to clipboardGET / POST /admin/typesense/curations/:entity List or upsert curations/overrides (pinning, hiding, promo banners) Copy to clipboardDELETE /admin/typesense/curations/:entity/:id Delete a curation rule Copy to clipboardGET / POST /admin/typesense/stopwords List or upsert stopword sets Copy to clipboardDELETE /admin/typesense/stopwords/:id Delete a stopword set Copy to clipboardPOST /admin/typesense/playground Execute Admin Search Playground queries with full telemetry & highlight inspection Copy to clipboardGET /admin/typesense/analytics Retrieve popular queries, zero-result queries, CTR, conversion rate & latency Copy to clipboardGET / POST / DELETE /admin/typesense/documents/:entity/:id Inspect raw indexed JSON document, trigger single-item re-sync, or delete from index
Admin UI Dashboard & Product Widget
- Typesense Search Dashboard (Copy to clipboard
/app/typesense):- Overview & Sync Jobs: Live cluster health indicator, total indexed documents, zero-downtime "Reindex All" button, and sync job history table (Copy to clipboard
completed, Copy to clipboardrunning, Copy to clipboardfailedwith duration and synced/deleted counts). - Collections & Custom Entities: Inspect every built-in and custom entity's collection alias, physical versioned collection, Copy to clipboard
queryBy& Copy to clipboardfacetByconfiguration, trigger per-entity rebuilds, and register new custom Medusa entities via a modal drawer. - Merchandising Studio: Create and delete Multi-way / One-way Synonyms, Curations/Overrides (pinned IDs, excluded IDs, match type), and Stopwords Sets.
- AI Search Playground: Test Copy to clipboard
Keyword, Copy to clipboardSemantic, and Copy to clipboardHybridsearch modes with an interactive Copy to clipboardalphablending slider, live latency/hit badges, safe Copy to clipboard<mark>highlight previews, and raw JSON inspection. - Search Analytics: View total searches, average latency, click-through rate (CTR), conversion rate, top queries, and zero-result queries (with a 1-click shortcut to create a Synonym for any zero-result query).
- Overview & Sync Jobs: Live cluster health indicator, total indexed documents, zero-downtime "Reindex All" button, and sync job history table (Copy to clipboard
- Product Detail Widget (Copy to clipboard
product.details.side.after):- Embedded directly on every Medusa Admin Product page to display whether the product is indexed in Typesense, its indexed prices/SKUs/facets, a collapsible JSON document viewer, and a 1-click "Re-sync Now" button.
Workflows & Programmatic Usage
Invoking Workflows
1234567891011121314151617181920import {syncEntitiesToTypesenseWorkflow,upsertTypesenseDocumentsWorkflow,deleteTypesenseDocumentsWorkflow,} from "medusa-plugin-typesense/workflows"// Full zero-downtime rebuild of products in English and Spanishawait syncEntitiesToTypesenseWorkflow(container).run({input: {entity: "products",fullRebuild: true,locale: "en",triggeredBy: "manual",},})// Upsert custom documents directlyawait upsertTypesenseDocumentsWorkflow(container).run({input: {entity: "brands",
Resolving Copy to clipboardTypesenseModuleService Directly
12345678import {TYPESENSE_MODULE,type TypesenseModuleService,} from "medusa-plugin-typesense"const typesenseService =container.resolve<TypesenseModuleService>(TYPESENSE_MODULE)const health = await typesenseService.checkHealth()
Security & Multi-Tenant Guarantees
- Admin Key Isolation: Copy to clipboard
apiKeynever leaves the server. Storefront clients using InstantSearch receive short-lived HMAC-signed Scoped Search Keys (Copy to clipboardGET /store/typesense/token) capped at Copy to clipboard86400s(Copy to clipboard24h) with embedded Copy to clipboardfilter_byconstraints. - Filter Injection Prevention: Copy to clipboard
compileTypesenseFilter()in Copy to clipboardsrc/modules/typesense/utils/filter-compiler.tsvalidates all user-supplied filter field names against the entity schema's allowlist, escapes all string values inside backticks (Copy to clipboard`...`), and wraps mandatory storefront constraints (Copy to clipboardstatus:=published && sales_channel_ids:=[...]) in outer parentheses so user Copy to clipboard$orclauses cannot bypass tenant or visibility boundaries. - Strict Input Validation: Every Copy to clipboard
/store/typesense/*and Copy to clipboard/admin/typesense/*route is protected by Zod validation schemas in Copy to clipboardsrc/api/validators.ts. - Safe Highlighting in Admin UI: Search result Copy to clipboard
<mark>highlights are tokenized into safe React JSX nodes without Copy to clipboarddangerouslySetInnerHTML.
Development & Testing
12345678# Typechecknpm run typecheck# Run unit & security test suitenpm test# Build Medusa v2 plugin (server + admin extensions)npm run build
License
MIT © Jose Luis
