Node.js connecting
Authentication
This client supports both table-based and JWT-based authentication to Stargate.
For table-based auth, use the StargateTableBasedToken
class:
// Stargate OSS configuration for locally hosted docker image
const auth_endpoint = "http://localhost:8081/v1/auth";
const username = "cassandra";
const password = "cassandra";
const stargate_uri = "localhost:8090";
// Set up the authentication
// For Stargate OSS: Create a table based auth token Stargate/Cassandra
// authentication using the default C* username and password
const credentials = new StargateTableBasedToken(
{authEndpoint: auth_endpoint,
username: username,
password: password
}
);
// Uncomment if you need to check the credentials
// console.log(credentials);
For JWT-based auth, use the StargateBearerToken
class and pass your token in directly:
// Astra DB configuration
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);
Creating a client
If you’re connecting to Stargate through insecure gRPC credentials, you must manually generate metadata for each call For a local Stargate instance, for instance, the following client code will fetch an auth token with a REST call:
// Create the gRPC client
// For Stargate OSS: passing it the address of the gRPC endpoint
const stargateClient = new StargateClient(stargate_uri, grpc.credentials.createInsecure());
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")
// For Stargate OSS: generate authentication metadata that is passed in the executeQuery and executeBatch statements
const authenticationMetadata = await credentials.generateMetadata({service_url: auth_endpoint});
This is because the Node gRPC implementation does not allow composing insecure credentials. However, if you’re using secure gRPC credentials, you can include the token metadata generator when constructing the client. For a connection to a remote Stargate instance like Astra automatically generate on every call to the client:
const bearerToken = new StargateBearerToken('my-token');
const credentials = grpc.credentials.combineChannelCredentials(
grpc.credentials.createSsl(), StargateBearerToken
);
const stargateClient = new StargateClient(grpcEndpoint, credentials);
const promisifiedClient = promisifyStargateClient(stargateClient);
// No need to pass metadata;
// the credentials passed to the client constructor will do that for us
await promisifiedClient.executeQuery(query);