Connect to Cassandra with Node.js sample code


The Node.js runtime environment can be used to connect your JavaScript web applications to your Cassandra database. In this article, we will introduce how to connect to a Cassandra cluster using Node.js.

We will start by installing Node.js and the DataStax Node.js Cassandra driver, and then provide simple demo code for connecting the remote server (Cassandra) and the local program.

Download Node.js

Go to and choose an appropriate version to download.

Install Node.js

Follow the instructions to install.

Install the DataStax Node.js driver for Apache Cassandra

Run the following command in your terminal:

npm install cassandra-driver

This command will create a “node_modules” folder and a JSON file called “package-lock.json”. For more information about the driver, visit the DataStax Node.js for Apache Cassandra GitHub page.

Populate the cluster with sample data

For this example, we will be creating some sample data. To connect to your instaclustr Cassandra cluster database using the CQL shell, see the support article Connecting to Instaclustr Using Cqlsh. If the connection is successful, you will see the “iccassandra@cqlsh>” prompt.

In the CQL shell, type in the following queries:

To check that the database has been properly populated, run the command:

The output should be:

Create a Node.js file

Create a file “my_node_example.js”, and open it in a text editor of your choice. This file will need to reference the cassandra-driver file in the node_modules folder, so for easy access we saved my_node_example.js into node_modules.  If you saved the file elsewhere, be sure to reference the correct location of cassandra-driver.

Input Sample Code

In the my_node_example.js file, copy in the following code. Note that in the DataStax Node.js driver, clusters are referred to as “clients”.

Replace ‘Public IP’ with the public IP addresses used by your cluster. Also replace ‘Username’ and ‘Password’ with your cluster’s authentication settings. To obtain your cluster’s username and password settings, go to > Log In > Cluster Details > Connection Info > Default Credentials for Password Authentication.

Run the Sample Code

To run the my_node_example.js file, type into a separate terminal window (not the one running the CQL shell):

node my_node_example.js

You should obtain the following results. Note that the outputs may not be in the same order, due to the asynchronous nature of NodeJS.

Site by Swell Design Group