DataStax Node.js driver

Before using the DataStax driver, review the Best practices for DataStax drivers to understand the rules and recommendations for improving performance and minimizing resource utilization in applications that use a DataStax driver.

If possible, upgrade to the latest native driver.

For more details about supported software, see the DataStax Support Policy.

Upgrade your driver to a compatible version to connect to DataStax Astra DB databases. For more information, see the DataStax Driver Matrix.

Connecting with Node.js Cloud driver

Prerequisites

  • Generate a Bearer Token and select Database Administrator for the role.

  • Create a keyspace

  • Create a table for your keyspace.

Connecting the driver

  1. Install stargate-grpc-node-client using either npm or yarn:

    • npm

    • yarn

    npm i @stargate-oss/stargate-grpc-node-client
    yarn add @stargate-oss/stargate-grpc-node-client
  1. While running Stargate on Astra DB, download a bearer token from the Astra DB dashboard and add that token to the connection portion of the script.

    The Bearer Token to use in the header of API calls is same as your database’s application token. It starts with an AstraCS: prefix, followed by a generated alphanumeric string. You can generate this token in your Astra DB console. Copy the token value, and paste it into your API call to authenticate with Astra DB resources.

    // Astra DB configuration
    // replace with values from the Astra DB dashboard
    const astra_uri = "{astra-base-url}-{astra-region}.apps.astra.datastax.com:443";
    const bearer_token = "AstraCS:xxxxxxx";
    
    // Set up the authentication
    // For Astra DB: Enter a bearer token for Astra, downloaded from the Astra DB dashboard
    const bearerToken = new StargateBearerToken(bearer_token);
    const credentials = grpc.credentials.combineChannelCredentials(
      grpc.credentials.createSsl(), bearerToken);
    
    // Uncomment if you need to check the credentials
    //console.log(credentials);

    For a connection to a remote Stargate instance like Astra automatically generate on every call to the client:

    // Create the gRPC client
    // For Astra DB: passing the credentials created above
    const stargateClient = new StargateClient(astra_uri, credentials);
    
    console.log("made client");
    
    // Create a promisified version of the client, so we don't need to use callbacks
    const promisifiedClient = promisifyStargateClient(stargateClient);
    
    console.log("promisified client")

Connecting with Node.js Native driver

Prerequisites

  • Create your database and set your environment variables to save time developing on your database. There are four environment variables, three of which are on the Astra dashboard (database id, region, and keyspace), and one that you must create (token). For more, see Create your database.

  • Download and install a current Node.js LTS version with npm.

  • Client ID and Client Secret by creating your application token for your username and password.

Working with secure connect bundle

This page explains how to use the secure connect bundle for Astra DB Classic.

If you want to use the secure connect bundle with Astra DB Serverless, see the Astra DB Serverless documentation.

Downloading secure connect bundle

To get the necessary security credentials and certificates for connecting drivers to your Astra DB database, you’ll need to download the secure connect bundle from the DataStax Astra Portal.

  1. Open your Astra Portal and select your database.

  2. On the Overview page, select Connect.

  3. In the Database Essentials section, click Get Bundle.

  4. In the Secure Connect Bundle Download dialog box, use the Select a region dropdown menu to select the region for which you want to download the bundle. If you have multiple regions, you can download a bundle for each region.

    If you’ve enabled VPC peering, you can also Download External Secure Connect Bundle for use within your VPC peering. VPC peering is only available on Classic databases.

  5. After selecting a region, various options for downloading the bundle appear. To download the bundle to your local computer, click Download Secure Bundle.

    The secure connect bundle downloads as a ZIP file named secure-connect-<database_name>.zip.

    Expiration of download link

    For added security, the download link for the secure connect bundle expires after five minutes. Once the download link expires, you’ll need to repeat the steps above to regenerate a new download link.

    Note that the secure connect bundle itself never expires.

Sharing secure connect bundle

Although teammates can access your Astra DB database, it doesn’t display in their list of available databases under My Databases in Astra Portal.

After you create an Astra DB database, you can grant access to other members of your team by providing them with the database credentials and connection details for your database.

Be careful when sharing connection details. Providing this information to another user grants them access to your Astra DB database and ownership capabilities, such as making modifications to the database.

For security, delete downloaded connection credentials after sending them to your teammate.

Secure connect bundle contents

The Secure Connect Bundle (SCB) contains the following files:

File Contents

ca.crt

DataStax’s Certificate Authority public certificate

cert

A certificate, unique to the specific SCB

key

A private key, unique to the specific SCB

cert.pfx

A PFX formatted archive containing the certificate and the private key

config.json

A configuration file with information on how to securely connect to the Astra DB instance associated with the SCB

cqlshrc

A CQLSH profile containing CQL shell session settings

identity.jks

A Java keystore file containing the aforementioned cert & key files

trustStore.jks

A Java keystore file containing the aforementioned ca.crt

Connecting the driver

  1. Install the DataStax Node.js driver:

    npm install cassandra-driver
  2. Create a connect-database.js file in the main directory for your Node.js project.

    cd nodejsProject
    touch connect-database.js
  3. Copy the following connection code into the connect-database.js file.

    Include the absolute path to the secure connect bundle for your Cassandra database (secure-connect-DATABASE_NAME.zip) in the secureConnectBundle parameter, as shown in the following examples.

    'use strict'
    const { Client } = require('cassandra-driver');
  4. After the Client class, add the following code to connect-database.js. This code creates a Client instance to connect to your Astra DB database, runs a CQL query, and prints the output to the console.

    async function run() {
      const client = new Client({
        cloud: { secureConnectBundle: 'path/to/secure-connect-DATABASE_NAME.zip' },
        credentials: { username: 'clientId', password: 'clientSecret' }
      });
    
      await client.connect();
    
      // Execute a query
      const rs = await client.execute('SELECT * FROM system.local');
      console.log(Hello from cluster: ${rs.first()['cluster_name']});
    
      await client.shutdown();
    }
    
    // Run the async function
    run();
  5. Save and close the connect-database.js file.

  6. Run the connect-database.js example with the Node.js runtime:

    node connect-database.js

    The console output displays the cluster_name value from the system.local table.

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2024 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