by Theo V.

A community-driven Node.js client for OpenSearch clusters, providing a safe, typed API to create indices, index documents, and run searches via HTTP REST endpoints.
This block provides the official OpenSearch JavaScript/TypeScript client (@opensearch-project/opensearch), enabling Node.js applications to communicate with an OpenSearch cluster over HTTP. It exposes a typed API surface covering core document operations, index management, search, and plugin-specific APIs (ML, KNN, ISM, etc.). The typical buyer is a backend developer building search, analytics, or data pipeline features against a self-hosted or AWS-managed OpenSearch cluster.
index.js - CommonJS entry point; exports Client, Transport, ConnectionPool, Connection, Serializer, errors, eventsindex.mjs - ESM re-export of the same symbols for native ES module consumersindex.d.ts - TypeScript type declarations for the entire public APIlib/ - Core runtime: Client, Transport, Connection, Serializer, pool implementations, AWS SigV4 signerapi/ - Auto-generated API method implementations organized by namespace (_core, indices, cluster, ml, knn, etc.)api_generator/ - Source templates and scripts used to regenerate api/ from the OpenSearch API specguides/ - Short markdown guides for specific features (auth, SSL, index lifecycle, etc.)samples/ - Runnable Node.js sample scripts demonstrating common workflowsscripts/ - Maintenance and build scripts (license headers, API generation)package.json - Package manifest; declares aws4, debug, hpagent, json11, ms, secure-json-parse as runtime depsnpm install @opensearch-project/opensearch@3.6.0
npm install aws4 # required for AWS SigV4 signing
npm install debug # internal debug logging
npm install hpagent # HTTP/HTTPS proxy agent support
npm install json11 # extended JSON parsing
npm install ms # millisecond time parsing
npm install secure-json-parse # safe JSON.parse against prototype pollution
Spin up an isolated sandbox and run it server-side — no local setup.
Tetrees AI Review of this version
This JavaScript, TypeScript cli / script completed archive review with strong static results. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Pipeline avcp-2026-08-04.1 · SHA-256 35b4ef6b01c2ed81…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Reviewed Aug 4, 2026
Push this product straight into your AI IDE, web builder or cloud IDE.
Connect Tetrees to a compatible AI IDE, list products you own, and request the verified ZIP without exposing seller upload controls.
No reviews yet.
Sign in to join the discussion
Loading discussion…
No native build steps, pod installs, or Android linking are required. This is a pure Node.js package.
source/ directory into your project, e.g. vendor/opensearch-js/.tsconfig.json:{
"compilerOptions": {
"paths": {
"@opensearch-project/opensearch": ["./vendor/opensearch-js/index.js"]
}
}
}
OPENSEARCH_URL=https://localhost:9200
OPENSEARCH_USERNAME=admin
OPENSEARCH_PASSWORD=admin
# For AWS-managed OpenSearch:
AWS_REGION=us-east-1
"esModuleInterop": true and "resolveJsonModule": true are set in tsconfig.json.index.mjs or use the exports field in package.json (resolved automatically by Node.js 12+).import { Client } from '@opensearch-project/opensearch';
const client = new Client({
node: string | string[] | NodeOptions | NodeOptions[];
auth?: { username: string; password: string } | { apiKey: string };
ssl?: { rejectUnauthorized?: boolean; ca?: string | Buffer };
maxRetries?: number;
requestTimeout?: number;
sniffOnStart?: boolean;
});
The primary entry point. Instantiate once and reuse across the application. Exposes all API namespaces as properties (e.g., client.index(), client.search(), client.indices.create()). Emits lifecycle events via the events constants.
import { Transport } from '@opensearch-project/opensearch';
class Transport {
request(
params: { method: string; path: string; querystring?: object; body?: object },
options?: TransportRequestOptions,
callback?: Function
): Promise<ApiResponse>;
}
Handles the low-level HTTP request lifecycle: retries, sniffing, serialization, and connection selection. Pass a custom Transport subclass to Client constructor to intercept or modify all requests.
import { ConnectionPool } from '@opensearch-project/opensearch';
class ConnectionPool {
addConnection(url: string | object): Connection;
removeConnection(connection: Connection): ConnectionPool;
getConnection(options?: { filter?: Function; selector?: Function }): Connection | null;
update(nodes: object[]): ConnectionPool;
}
Manages the pool of live Connection instances. Use directly when building custom load-balancing logic or integrating with service discovery. CloudConnectionPool is a subclass tuned for Elastic Cloud endpoints; it is included but rarely needed for OpenSearch.
import { errors } from '@opensearch-project/opensearch';
// Available error classes:
errors.ConfigurationError // bad client config
errors.ConnectionError // network-level failure
errors.TimeoutError // request timed out
errors.ResponseError // non-2xx HTTP response (contains .meta with statusCode, body)
errors.SerializationError // JSON serialization failed
errors.DeserializationError // JSON deserialization failed
errors.NoLivingConnectionsError
errors.NotCompatibleError
Import individual error classes to write targeted catch blocks and distinguish network failures from cluster-level errors.
Connect to a local OpenSearch node, create an index, index a document, and run a match query.
import { Client } from '@opensearch-project/opensearch';
const client = new Client({
node: process.env.OPENSEARCH_URL ?? 'https://localhost:9200',
auth: {
username: process.env.OPENSEARCH_USERNAME ?? 'admin',
password: process.env.OPENSEARCH_PASSWORD ?? 'admin',
},
ssl: { rejectUnauthorized: false },
});
async function main() {
// Create index
await client.indices.create({
index: 'products',
body: {
mappings: {
properties: {
name: { type: 'text' },
price: { type: 'float' },
},
},
},
});
// Index a document
await client.index({
index: 'products',
id: '1',
body: { name: 'Widget', price: 9.99 },
refresh: 'wait_for',
});
// Search
const response = await client.search({
index: 'products',
body: { query: { match: { name: 'widget' } } },
});
console.log(response.body.hits.hits);
// Delete index
await client.indices.delete({ index: 'products' });
}
main().catch(console.error);
Use AwsSigv4Signer from lib/aws to sign requests with AWS credentials before they are sent.
import { Client } from '@opensearch-project/opensearch';
import { AwsSigv4Signer } from '@opensearch-project/opensearch/lib/aws';
import { defaultProvider } from '@aws-sdk/credential-provider-node';
const client = new Client({
...AwsSigv4Signer({
region: process.env.AWS_REGION ?? 'us-east-1',
service: 'es', // use 'aoss' for Serverless
getCredentials: defaultProvider(),
}),
node: `https://${process.env.OPENSEARCH_DOMAIN_ENDPOINT}`,
});
async function listIndices() {
const { body } = await client.cat.indices({ format: 'json' });
console.log(body);
}
listIndices().catch(console.error);
Distinguish between a missing document (404 ResponseError) and a network-level failure (ConnectionError).
import { Client, errors } from '@opensearch-project/opensearch';
const client = new Client({
node: process.env.OPENSEARCH_URL ?? 'https://localhost:9200',
auth: { username: 'admin', password: 'admin' },
ssl: { rejectUnauthorized: false },
});
async function getDocument(index: string, id: string) {
try {
const { body } = await client.get({ index, id });
return body._source;
} catch (err) {
if (err instanceof errors.ResponseError && err.meta.statusCode === 404) {
console.warn(`Document ${id} not found in ${index}`);
return null;
}
if (err instanceof errors.ConnectionError) {
console.error('Cannot reach OpenSearch cluster:', err.message);
throw err;
}
throw err;
}
}
getDocument('products', 'missing-id').then(console.log);
index.js - CommonJS barrel; re-exports Client, Transport, ConnectionPool, Connection, Serializer, errors, events.index.mjs - ESM barrel; re-exports the same symbols for "type": "module" projects.index.d.ts - Aggregated TypeScript declarations; the primary type source for IDE autocompletion.lib/Client.js - Client class definition; mounts all API namespaces and manages Transport lifecycle.lib/Transport.js - HTTP request dispatch, retry logic, sniffing scheduler.lib/Connection.js - Single node HTTP/HTTPS connection wrapper built on Node.js http/https.lib/Serializer.js - JSON serialization/deserialization with secure-json-parse and json11.lib/errors.js - All error class definitions exported under errors.lib/pool/ - BaseConnectionPool, ConnectionPool, CloudConnectionPool for node lifecycle management.lib/aws/ - AwsSigv4Signer and AwsSigv4SignerError for AWS IAM authentication.api/ - Auto-generated per-namespace API files (_core, indices, cluster, ml, knn, ism, etc.).api_generator/ - Mustache templates and Node.js scripts to regenerate api/ from the OpenSearch spec.guides/ - Focused markdown guides for SSL, authentication, index templates, bulk operations, etc.samples/ - Self-contained Node.js scripts that demonstrate end-to-end workflows.scripts/ - CI and developer tooling (license header injection, API spec download).package.json - Package metadata, entry points, and runtime dependency declarations.ssl: { rejectUnauthorized: false } in the Client constructor or supply ssl.ca with the CA bundle.service mismatch: Amazon OpenSearch Service uses 'es'; Amazon OpenSearch Serverless uses 'aoss'. Using the wrong value returns 403 Forbidden.index.mjs re-exports from index.js via a default import; if bundlers complain about dual-package hazard, pin to one entry point and set "esModuleInterop": true in tsconfig.json.ResponseError body access: The HTTP response body is at err.meta.body, not err.body. Check err.meta.statusCode for the HTTP status code.sniffOnStart: true and sniffInterval: 30000 so the pool re-discovers nodes automatically.client.helpers.bulk() (available on Client) to avoid manually constructing the body.I have vendored the OpenSearch JavaScript client source from @opensearch-project/opensearch@3.6.0
into the directory `source/` of my project. I also have USAGE.md in the same location.
Please help me integrate the OpenSearch client into my existing Node.js/TypeScript project by:
1. Reading USAGE.md and source/index.js to understand available exports.
2. Creating a singleton client module (e.g., `src/lib/opensearchClient.ts`) that instantiates
`Client` from `source/index.js` using environment variables for the node URL and credentials.
3. Adding typed helper functions for: indexing a document, fetching a document by ID,
running a search query, and deleting an index.
4. Wrapping all calls in try/catch blocks that distinguish `errors.ResponseError` (cluster errors)
from `errors.ConnectionError` (network failures) using the `errors` export from `source/index.js`.
5. If my cluster is on AWS, applying `AwsSigv4Signer` from `source/lib/aws/index.js` using
`@aws-sdk/credential-provider-node`.
6. Writing a brief Jest test file that mocks `Transport#request` and verifies my helper functions.
Do not invent any API methods. Only use exports visible in source/index.js and source/lib/aws/index.js.
Show all import paths explicitly. Ask me for my cluster URL and auth method before writing code.
This source is licensed under the Apache License, Version 2.0. See source/LICENSE.txt for the full text. Portions are derived from the original elasticsearch-js client, also Apache 2.0 licensed; see source/NOTICE.txt for attribution details.
Upstream package: @opensearch-project/opensearch - GitHub: opensearch-project/opensearch-js.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
The full install guide and integration prompts unlock after purchase.
Automation, Utilities & Developer Tools
Free