Nuxt Typesense

TypeScript usage examples

Search products from a server route

Use the proxied /api/typesense routes in Nuxt server code or from client-side fetch calls.

const results = await $fetch('/api/typesense/documents/products/search', {
  method: 'POST',
  body: {
    q: 'laptop',
    queryBy: 'name,description,tags',
    filterBy: 'inStock:=true && category:=Electronics',
    perPage: 10,
  },
})

return results

Use the generated TypeScript API client

The module exposes typed API clients for server-side usage.

export default defineEventHandler(async () => {
  const config = useRuntimeConfig()
  const { documentsApi, collectionsApi } = useTypesenseServerApi(
    config.typesense.url,
    config.typesense.apiKey,
  )

  const collections = await collectionsApi.getCollections()
  const products = await documentsApi.searchCollection({
    collectionName: 'products',
    searchParameters: {
      q: 'headphones',
      queryBy: 'name,description',
      filterBy: 'inStock:=true',
      perPage: 12,
    },
  })

  return { collections, products }
})

Create a collection with schema metadata

Configure field-level typing and faceting before importing content.

await $fetch('/api/typesense/collections', {
  method: 'POST',
  body: {
    name: 'products',
    fields: [
      { name: 'id', type: 'string' },
      { name: 'name', type: 'string' },
      { name: 'category', type: 'string', facet: true },
      { name: 'price', type: 'float', facet: true },
      { name: 'inStock', type: 'bool', facet: true },
      { name: 'tags', type: 'string[]', facet: true },
    ],
    defaultSortingField: 'price',
  },
})

Filter and facet a search query

Use TypeScript-friendly camelCase names for request params.

const results = await $fetch('/api/typesense/documents/products/search', {
  method: 'POST',
  body: {
    q: '*',
    queryBy: 'name,description,tags',
    facetBy: 'category,brand,inStock',
    filterBy: 'price:<100 && rating:>=4.5',
    sortBy: 'price:asc',
    perPage: 20,
  },
})

const electronics = results.facet_counts?.find(
  facet => facet.field_name === 'category',
)

Client-side composables

Use browser composables in client mode with a search-only API key.

const { searchCollection, collectionInfos } = useTypesenseDocuments()
const { documentsApi } = useTypesenseApi()

const products = await searchCollection('products', {
  q: 'wireless',
  queryBy: 'name,description',
  filterBy: 'inStock:=true',
  perPage: 8,
})

const collections = await collectionInfos()
const health = await documentsApi.searchCollection({
  collectionName: 'products',
  searchParameters: { q: '*', queryBy: 'name', perPage: 5 },
})