Node.js driver quickstart

DataStax recommends the Data API and clients for Serverless (Vector) databases. You can use the Data API to perform CQL operations on your table data in Serverless (Vector) databases.

DataStax recommends drivers only for Serverless (Non-Vector) databases, legacy applications that rely on a driver, or for CQL functions that aren’t supported by the Data API. For more information, see Compare connection methods.

To use the DataStax Node.js driver, you need to install the driver and its dependencies, and then connect the driver to your Astra DB Serverless database. Once connected, you can write scripts that use the driver to run commands against your database.

This quickstart explains how to use the Node.js driver to connect to a Serverless (Vector) database, create a table, create an vector-compatible index, load data with vector embeddings, and perform a similarity search. It also includes instructions to migrate an existing DataStax Node.js driver to a version that supports Astra DB.

Prerequisites

  1. Create a database.

  2. Set the following environment variables:

    • ASTRA_DB_ID: The database ID

    • ASTRA_DB_REGION: A region where your database is deployed and where you want to connect to the database, such as us-east-2

    • ASTRA_DB_KEYSPACE: A keyspace in your database, such as default_keyspace

    • ASTRA_DB_APPLICATION_TOKEN: An application token with the Database Administrator role.

      The token.json has the following format:

      {
        "clientId": "CLIENT_ID",
        "secret": "CLIENT_SECRET",
        "token": "APPLICATION_TOKEN"
      }

      For driver authentication, you can use either clientId and secret or the literal string token and the AstraCS token value. If you are on an older driver version that doesn’t support the token option, then you might need to use clientId and secret. For more information, see Token details.

  3. Download your database’s Secure Connect Bundle (SCB).

  4. Install Node.js LTS version with npm.

Install the Node.js driver

  1. Install the DataStax Node.js driver:

    npm install cassandra-driver

    Make sure you use a driver version that is compatible with Astra DB. For more information, see DataStax driver matrix.

Connect the Node.js driver

  1. In the root of your Node.js project, create a connect-database.js file:

    cd nodejsProject
    touch connect-database.js
  2. Copy the following connection code into the connect-database.js file, and then replace PATH_TO_SCB with the absolute path to your database’s Secure Connect Bundle (SCB) (secure-connect-DATABASE_NAME.zip):

    connect-database.js
    const cassandra = require('cassandra-driver');
    
    const cloud = { secureConnectBundle: "**PATH_TO_SCB**" };
    const authProvider = new cassandra.auth.PlainTextAuthProvider('token', process.env['ASTRA_DB_APPLICATION_TOKEN']);
    const client = new cassandra.Client({ cloud, authProvider });
    
    async function run() {
        await client.connect();
    
        // ...
    }

    This code creates a Client instance to connect to your Astra DB database, through which you can run commands against your database.

  3. Save and then run connect-database.js with the Node.js runtime to test the connection:

    node connect-database.js

Run commands with the Node.js driver

After you connect to the database, you can use the driver to perform operations on your database.

Create a table and vector index

The following code creates a table named vector_test with columns for an integer id, text, and a 5-dimensional vector. Then, it creates a custom index on the vector column using dot product similarity function for efficient vector searches.

// ...

const keyspace = 'default_keyspace';
const v_dimension = 5;

await client.execute(`
  CREATE TABLE IF NOT EXISTS ${keyspace}.vector_test (id INT PRIMARY KEY,
  text TEXT, vector VECTOR<FLOAT,${v_dimension}>);
`);

await client.execute(`
    CREATE CUSTOM INDEX IF NOT EXISTS idx_vector_test
    ON ${keyspace}.vector_test
        (vector) USING 'StorageAttachedIndex' WITH OPTIONS =
        {'similarity_function' : 'cosine'};
`);

// ...

Load data

The following code loads some rows with embeddings into the vector_test table.

// ...

const text_blocks = [
    { id: 1, text: 'Chat bot integrated sneakers that talk to you', vector: [0.1, 0.15, 0.3, 0.12, 0.05] },
    { id: 2, text: 'An AI quilt to help you sleep forever', vector: [0.45, 0.09, 0.01, 0.2, 0.11] },
    { id: 3, text: 'A deep learning display that controls your mood', vector: [0.1, 0.05, 0.08, 0.3, 0.6] },
];

for (let block of text_blocks) {
    const {id, text, vector} = block;
    await client.execute(
        `INSERT INTO ${keyspace}.vector_test (id, text, vector) VALUES (${id}, '${text}', [${vector}])`
    );
}

// ...

The following code performs a similarity search to find rows that are close to a specific vector embedding.

// ...

  const ann_query = `
    SELECT id, text, similarity_cosine(vector, [0.15, 0.1, 0.1, 0.35, 0.55]) as sim
    FROM ${keyspace}.vector_test
    ORDER BY vector ANN OF [0.15, 0.1, 0.1, 0.35, 0.55] LIMIT 2
  `;

  const result = await client.execute(ann_query);
  result.rows.forEach(row => {
    console.log(`[${row.id}] "${row.text}" (sim: ${row.sim.toFixed(4)})`);
  });

  await client.shutdown();
}

run().catch(console.error);

Migrate the Node.js driver

If necessary, you can migrate an earlier DataStax Node.js driver to a version that supports Astra DB.

  1. Complete the prerequisites.

  2. Install the latest Node.js driver.

  3. In your existing DataStax Node.js driver code, modify the connection code to use the SCB credentials. For more information, see Connect the Node.js driver.

    const { Client } = require('cassandra-driver');
    const client = new Client({
        cloud: { secureConnectBundle: 'PATH_TO_SCB' },
        credentials: { username: 'clientId', password: 'secret' }
      });
  4. Run your Node.js script.

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2025 DataStax | Privacy policy | Terms of use

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: +1 (650) 389-6000, info@datastax.com