Install and use the Meilisearch JavaScript Client
mainmeilisearch package is the official JavaScript client for Meilisearch. It is designed to work in both Node.js and browser environments and provides full TypeScript support for type safety.repository·main·Indexed 21 days ago
https://github.com/meilisearch/meilisearch-jsThe official API client for interacting with the Meilisearch search engine from JavaScript environments, including Node.js and the browser. Version 0.60.0 provides full TypeScript support and features for managing search indexes, performing typo-tolerant searches with filters and highlighting, and handling batch operations. It includes specialized support for React Native and Deno, as well as experimental ChatWorkspace features for streaming chat completions.
meilisearch package is the official JavaScript client for Meilisearch. It is designed to work in both Node.js and browser environments and provides full TypeScript support for type safety.To use the SDK, import Meilisearch and instantiate it with a host and an apiKey. You can use either CommonJS require or ES modules import syntax.
const { Meilisearch } = require("meilisearch");
// Or if you are in a ES environment
import { Meilisearch } from "meilisearch";
const client = new Meilisearch({
host: "http://127.0.0.1:7700",
apiKey: "masterKey",
});The Meilisearch JavaScript playground is a vanilla JavaScript project powered by Vite. To run the playground locally for development, use pnpm to install dependencies and start the development server.
pnpm install
pnpm devmeilisearch-js in a React Native project, you must install the react-native-url-polyfill package to ensure URL compatibility.Install the meilisearch package via npm to use the official Meilisearch API client in your JavaScript project.
Note: Node.js LTS and Maintenance versions are officially supported and tested. While other runtimes like Deno and Bun are not explicitly tested, they may work.
npm i meilisearchThe TaskClient class is used to interact with Meilisearch's task API. It allows you to retrieve task statuses, fetch task documents, and manage the lifecycle of asynchronous operations (like adding documents or updating settings) that Meilisearch processes in the background.
Key capabilities include:
uid or list multiple tasks.waitForTask or waitForTasks to poll the Meilisearch API until a task reaches a terminal state (not enqueued or processing).When initializing TaskClient, you can provide WaitOptions to set default timeout and interval values for polling operations.
import { TaskClient } from './task.js';
// Assuming httpRequest is already configured
const taskClient = new TaskClient(httpRequest, {
timeout: 10_000,
interval: 100
});Tenant tokens use TokenSearchRules to restrict what a user can search. This can be defined in two ways:
TokenIndexRules (which contain an optional filter).TokenIndexRules structure:
filter: An optional Filter applied to the index.TokenSearchRules type definition:
export type TokenSearchRules = Record<string, TokenIndexRules | null> | string[];A search request returns a SearchResponse<T>, which contains the results and metadata.
Fields include:
hits: An array of Hit<T> objects containing the actual documents.processingTimeMs: Time taken to process the query.query: The original query string.facetDistribution: A mapping of facet values to their counts.facetStats: Statistics for facets (min/max values).totalHits: Total number of matching documents (if using finite pagination).totalPages: Total number of pages (if using finite pagination).// Example response shape
const response: SearchResponse<MyDocument> = {
hits: [{ id: 1, title: 'Result' }],
processingTimeMs: 5,
query: 'term',
totalHits: 100,
hitsPerPage: 10,
page: 0,
totalPages: 10
};When an operation returns an EnqueuedTaskPromise (like cancelTasks or deleteTasks), you can call .waitTask(options?) directly on that promise. This is a convenient way to await the completion of the task that was just enqueued without manually managing the uid or using taskClient.waitForTask() separately.
// Example of using the convenience .waitTask() method
const enqueuedTaskPromise = taskClient.cancelTasks({ /* params */ });
// The promise is augmented with the waitTask method
const task = await enqueuedTaskPromise.waitTask({ timeout: 10000 });
console.log('Task completed:', task.status);When you perform an asynchronous operation in Meilisearch (like adding documents), the client returns an EnqueuedTaskPromise. This is a Promise that resolves to an EnqueuedTask, but it also includes a special .waitTask() method.
Calling .waitTask() will poll the Meilisearch server until the task reaches a terminal state (succeeded, failed, or canceled), at which point it resolves to a full Task object containing details and errors.
// The returned promise from an async operation
const enqueuedTask = await client.addDocuments('movies', documents);
// Await the actual completion of the task
const task = await enqueuedTask.waitTask({ timeout: 10000 });
if (task.error) {
console.error('Task failed:', task.error);
} else {
console.log('Task succeeded:', task.uid);
}If Meilisearch is behind a proxy, you can customize the request behavior via the Meilisearch constructor.
Custom Headers and Credentials:
Use requestConfig to pass headers or set credentials (e.g., 'include').
Custom HTTP Client:
Provide an httpClient function to use a different library like axios. The function receives url and opts (containing body, headers, and method) and must return the response data.
// Custom request config
const client: Meilisearch = new Meilisearch({
host: "http://localhost:3000/api/meilisearch/proxy",
requestConfig: {
headers: {
Authorization: AUTH_TOKEN,
},
// OR
credentials: "include",
},
});
// Custom http client
const client: Meilisearch = new Meilisearch({
host: "http://localhost:3000/api/meilisearch/proxy",
httpClient: async (url, opts) => {
const response = await $axios.request({
url,
data: opts?.body,
headers: opts?.headers,
method: (opts?.method?.toLocaleUpperCase() as Method) ?? "GET",
});
return response.data;
},
});The overrides array allows you to apply different rules, plugins, or settings to specific file patterns. Each override object can contain:
files: A glob pattern matching the files to which the override applies.rules: A set of rules specific to these files.jsPlugins: JavaScript plugins to load (e.g., eslint-plugin-tsdoc).plugins: Additional plugins (e.g., vitest).overrides: [
{
files: ["src/**/*.ts"],
jsPlugins: ["eslint-plugin-tsdoc"],
rules: {
"tsdoc/syntax": "error",
},
},
{
files: ["tests/**/*.test.ts"],
plugins: ["vitest"],
rules: {
"vitest/expect-expect": "error",
},
}
]