• Glossary
  • Support
  • Downloads
  • DataStax Home
Get Live Help
Expand All
Collapse All

DataStax Astra DB Serverless Documentation

    • Overview
      • Release notes
      • Astra DB FAQs
      • Astra DB glossary
      • Get support
    • Getting Started
      • Grant a user access
      • Load and retrieve data
        • Use DSBulk to load data
        • Use Data Loader in Astra Portal
      • Connect a driver
      • Build sample apps
      • Use integrations
        • Connect with DataGrip
        • Connect with DBSchema
        • Connect with JanusGraph
        • Connect with Strapi
    • Planning
      • Plan options
      • Database regions
    • Securing
      • Security highlights
      • Security guidelines
      • Default user permissions
      • Change your password
      • Reset your password
      • Authentication and Authorization
      • Astra DB Plugin for HashiCorp Vault
    • Connecting
      • Connecting private endpoints
        • AWS Private Link
        • Azure Private Link
        • GCP Private Endpoints
        • Connecting custom DNS
      • Connecting Change Data Capture (CDC)
      • Connecting CQL console
      • Connect the Spark Cassandra Connector to Astra
      • Drivers for Astra DB
        • Connecting C++ driver
        • Connecting C# driver
        • Connecting Java driver
        • Connecting Node.js driver
        • Connecting Python driver
        • Drivers retry policies
      • Connecting Legacy drivers
      • Get Secure Connect Bundle
    • Migrating
      • FAQs
      • Preliminary steps
        • Feasibility checks
        • Deployment and infrastructure considerations
        • Create target environment for migration
        • Understand rollback options
      • Phase 1: Deploy ZDM Proxy and connect client applications
        • Set up the ZDM Automation with ZDM Utility
        • Deploy the ZDM Proxy and monitoring
          • Configure Transport Layer Security
        • Connect client applications to ZDM Proxy
        • Manage your ZDM Proxy instances
      • Phase 2: Migrate and validate data
      • Phase 3: Enable asynchronous dual reads
      • Phase 4: Change read routing to Target
      • Phase 5: Connect client applications directly to Target
      • Troubleshooting
        • Troubleshooting tips
        • Troubleshooting scenarios
      • Additional resources
        • Glossary
        • Contribution guidelines
        • Release Notes
    • Managing
      • Managing your organization
        • User permissions
        • Pricing and billing
        • Audit Logs
        • Bring Your Own Key
          • BYOK AWS Astra DB console
          • BYOK GCP Astra DB console
          • BYOK AWS DevOps API
          • BYOK GCP DevOps API
        • Configuring SSO
          • Configure SSO for Microsoft Azure AD
          • Configure SSO for Okta
          • Configure SSO for OneLogin
      • Managing your database
        • Create your database
        • View your databases
        • Database statuses
        • Use DSBulk to load data
        • Use Data Loader in Astra Portal
        • Monitor your databases
        • Export metrics to third party
          • Export metrics via Astra Portal
          • Export metrics via DevOps API
        • Manage access lists
        • Manage multiple keyspaces
        • Using multiple regions
        • Terminate your database
      • Managing with DevOps API
        • Managing database lifecycle
        • Managing roles
        • Managing users
        • Managing tokens
        • Managing BYOK AWS
        • Managing BYOK GCP
        • Managing access list
        • Managing multiple regions
        • Get private endpoints
        • AWS PrivateLink
        • Azure PrivateLink
        • GCP Private Service
    • Astra CLI
    • DataStax Astra Block
      • FAQs
      • About NFTs
      • DataStax Astra Block for Ethereum quickstart
    • Developing with Stargate APIs
      • Develop with REST
      • Develop with Document
      • Develop with GraphQL
        • Develop with GraphQL (CQL-first)
        • Develop with GraphQL (Schema-first)
      • Develop with gRPC
        • gRPC Rust client
        • gRPC Go client
        • gRPC Node.js client
        • gRPC Java client
      • Develop with CQL
      • Tooling Resources
      • Node.js Document API client
      • Node.js REST API client
    • Stargate QuickStarts
      • Document API QuickStart
      • REST API QuickStart
      • GraphQL API CQL-first QuickStart
    • API References
      • DevOps REST API v2
      • Stargate Document API v2
      • Stargate REST API v2
  • DataStax Astra DB Serverless Documentation
  • Connecting
  • Drivers for Astra DB
  • Connecting Node.js driver

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.

DataStax recommends using the unified DataStax driver. See this blog post for more information. You can also use the DataStax Enterprise (DSE) drivers, which exposes the same API for connecting to Cassandra databases.

Connecting with Node.js cloud-native driver

Prerequisites

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

  • Create a keyspace

  • Create a table for your keyspace (optional): REST

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 legacy 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

Downloading secure connect bundle

To connect to your Astra DB database using the drivers, download the secure database bundle from the DataStax Astra Portal that contains the connection credentials.

  1. Open a browser, navigate to Astra DB, and log in.

  1. From your Dashboard page, select your database.

  1. On the Overview page, select Connect.

  1. In the Select a Method section, select Drivers and then Legacy from the dropdown menu to select your driver type from the list to load language-specific instructions.

    Java and Node.js are available as legacy and cloud native drivers.

    If you have multiple regions, select the region you want to connect to from the dropdown menu for instructions.

    The bundle URL is the same for all languages.

  1. Click Download Bundle.

    If you have multiple regions, you will have the option to download a bundle for each region from the expanded Download Bundle drop-down menu.

The secure-connect-database_name.zip file downloads, which contains the security certificates and credentials for your database.

Sharing secure connect bundle

Although teammates can access your Astra DB database, it will not 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.

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.

Migrating Node.js driver

Complete the following procedure to migrate your existing DataStax Node.js driver to a version that is capable of connecting to Astra DB databases created using DataStax Astra DB.

  1. Install the DataStax Node.js driver:

    • DataStax Node.js driver for Apache Cassandra

    • DSE driver

    npm install cassandra-driver
    npm install dse-driver
  1. In your existing DataStax Node.js driver code, modify the connection code to use the Astra DB API. 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.

    • DataStax Node.js driver for Apache Cassandra

    • DSE Node.js driver

    const { Client } = require('cassandra-driver');
    const client = new Client({
        cloud: { secureConnectBundle: 'path/to/secure-connect-database_name.zip' },
        credentials: { username: 'clientId', password: 'clientSecret' }
      });
    const dse = require('dse-driver');
    
    const client = new Client({
        cloud: { secureConnectBundle: 'path/to/secure-connect-database_name.zip' },
        credentials: { username: 'clientId', password: 'clientSecret' }
      });
  1. Run your Node.js script to connect to your Astra DB database:

node my_node.js_driver.js

If successful, the code builds, compiles, and connects to your Cassandra database.

Connecting Java driver Connecting Python driver

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

© DataStax | Privacy policy | Terms of use

DataStax, Titan, and TitanDB are registered trademarks of DataStax, Inc. and its subsidiaries in the United States and/or other countries.

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.

landing_page landingpage