InfluxDB Client for Node.js and Browsers
This package, `influx`, provides a client library for interacting with InfluxDB 1.x time-series databases from Node.js and browser environments. The current stable version is 5.12.0. Releases are frequent, with several minor versions and bug fixes released annually, indicating active maintenance for the 1.x series. Key differentiators include its full support across Node.js and browsers, a simple API for common InfluxDB operations, and its focus on performance, capable of processing millions of rows per second with zero external dependencies. It's crucial to note that this library is specifically for InfluxDB v1.x; users of InfluxDB v2.x should use the official `@influxdata/influxdb-client-js` package.
Common errors
-
Error: 'InfluxDB: authentication failed' or 'Authorization header required'
cause Incorrect credentials provided, or the InfluxDB server expects authentication in a different format than the client is sending. Common after `influx` v5.11.0's change to Basic Auth.fixDouble-check your `username` and `password` client options. Ensure your InfluxDB 1.x server is configured for Basic Auth. If using `influx` < 5.11.0 and upgrading, be aware of the authentication method change. -
TypeError: InfluxDB is not a constructor
cause This error typically occurs when trying to use CommonJS `require` syntax incorrectly with a package designed for ES Modules or when the default export is being imported instead of a named export.fixFor ES Modules/TypeScript, use `import { InfluxDB } from 'influx';`. If you must use CommonJS, ensure your `require` statement correctly accesses the named export: `const { InfluxDB } = require('influx');` or `const InfluxDB = require('influx').InfluxDB;`. -
InfluxDB 'Error: Cannot create database "mydb", already exists.'
cause The `createDatabase` method was called for a database that already exists on the InfluxDB server.fixBefore attempting to create a database, use `influx.getDatabaseNames()` to check if the database exists. Only call `createDatabase(name)` if the database name is not present in the returned list.
Warnings
- breaking Starting with version 5.11.0, the client defaults to sending InfluxDB authentication credentials via a Basic Auth header instead of including them in the URL or query string. This is a security enhancement but may break existing applications if your InfluxDB setup expects credentials differently or if you were previously relying on credentials being exposed in the URL.
- gotcha This `influx` client library is explicitly designed and maintained for InfluxDB **1.x** series. It is not compatible with InfluxDB **2.x** or later versions. Using this library with an InfluxDB 2.x instance will result in connection errors, query failures, or unexpected behavior.
- gotcha Versions of `influx` prior to 5.9.7 had a bug where timestamp conversions could be subject to floating-point errors, potentially leading to inaccurate timestamps for written data points or discrepancies in query results, particularly with large integer timestamps.
- gotcha Prior to version 5.9.1, there were issues with incorrect encoding when using placeholders or bind parameters in InfluxDB queries, which could lead to malformed queries or failed data insertion/retrieval.
Install
-
npm install influx -
yarn add influx -
pnpm add influx
Imports
- InfluxDB
const InfluxDB = require('influx');import { InfluxDB } from 'influx'; - FieldType
import FieldType from 'influx/FieldType';
import { FieldType } from 'influx'; - IPoint
import { IPoint } from 'influx';import type { IPoint, IClusterConfig } from 'influx';
Quickstart
import { InfluxDB, FieldType, IPoint } from 'influx';
async function run() {
const host = process.env.INFLUXDB_HOST ?? 'localhost';
const port = parseInt(process.env.INFLUXDB_PORT ?? '8086', 10);
const username = process.env.INFLUXDB_USERNAME ?? 'admin';
const password = process.env.INFLUXDB_PASSWORD ?? 'admin';
const database = process.env.INFLUXDB_DATABASE ?? 'mydb';
const influx = new InfluxDB({
host: host,
port: port,
database: database,
username: username,
password: password,
schema: [
{
measurement: 'cpu_load_short',
fields: {
value: FieldType.FLOAT,
host: FieldType.STRING,
},
tags: ['host']
}
]
});
// Ensure the database exists
try {
const dbs = await influx.getDatabaseNames();
if (!dbs.includes(database)) {
await influx.createDatabase(database);
console.log(`Database '${database}' created.`);
} else {
console.log(`Database '${database}' already exists.`);
}
} catch (error) {
console.error('Error checking/creating database:', error);
process.exit(1);
}
// Write data
const points: IPoint[] = [
{
measurement: 'cpu_load_short',
tags: { host: 'server01' },
fields: { value: 0.64, region: 'us-west' }
}
];
await influx.writePoints(points);
console.log('Data written successfully.');
// Query data
const results = await influx.query(`
SELECT * FROM cpu_load_short WHERE host = 'server01' ORDER BY time DESC LIMIT 5
`);
console.log('Query results:', results);
// Example of using AbortSignal (v5.12.0 feature)
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 1000); // Abort after 1 second
try {
const abortableResults = await influx.query('SELECT * FROM cpu_load_short', {
abortSignal: controller.signal
});
console.log('Abortable query results:', abortableResults);
} catch (err: any) {
if (err.name === 'AbortError') {
console.log('Query aborted successfully.');
} else {
console.error('Abortable query failed:', err.message);
}
} finally {
clearTimeout(timeoutId);
}
}
run().catch(console.error);