| endpoint | _connection |
|---|---|
| lang | javascript |
| es_version | 9.3 |
| client | @elastic/elasticsearch@9.3.0 |
Use the Client class from @elastic/elasticsearch to create a
client. The simplest approach uses basic authentication with a
username and password:
const { Client } = require("@elastic/elasticsearch");
const client = new Client({
node: "http://localhost:9200",
auth: {
username: "elastic",
password: "your-password",
},
});
const info = await client.info();
console.log(`Connected to ${info.cluster_name} (v${info.version.number})`);Install the client with npm:
npm install @elastic/elasticsearch@9.3.0For production use, API keys are preferred over username/password. Pass the base64-encoded API key directly:
const client = new Client({
node: "http://localhost:9200",
auth: {
apiKey: "your-base64-api-key",
},
});Or use an object with id and api_key if you have them
separately:
const client = new Client({
node: "http://localhost:9200",
auth: {
apiKey: {
id: "key-id",
api_key: "key-secret",
},
},
});Configure timeouts, retries, and TLS for production deployments:
const { Client } = require("@elastic/elasticsearch");
const { readFileSync } = require("fs");
const client = new Client({
node: "https://my-cluster.example.com:9243",
auth: { apiKey: "your-base64-api-key" },
requestTimeout: 30000,
maxRetries: 3,
tls: {
ca: readFileSync("/path/to/ca.crt"),
},
});To verify the connection is working:
const alive = await client.ping();
console.log(alive ? "Connected" : "Connection failed");