Warning
This example pertains to astra-db-ts
version 2.0.0 and later.
Previous versions of astra-db-ts
need the events
polyfill to work in the browser.
See the v1.x browser example for more information.
astra-db-ts
is designed foremost as a server-side library, but it may also work in the browser if so desired.
However, keep in mind, that doing so is insecure, and is better implemented with an actual server-side application.
However, you may need to set up a CORS proxy (like cors-anywhere) to forward requests to the Data API.
This is a simple example of how we can interact with an Astra database in a browser environment. It will list out all the collections in a given database.
- Ensure you have an existing Astra Database running at astra.datastax.com.
- You'll need an API key and a database endpoint URL to get started.
-
Clone this repository to your local machine.
-
Run
npm install
to install the required dependencies. -
Copy the
.env.example
file to.env
and fill in the required values. -
Visit https://cors-anywhere.herokuapp.com/corsdemo to temporarily enable access to the demo server.
-
Run
npm run dev
to start the local development server. -
Visit
http://localhost:5173
in your browser to see the example in action.
-
Create a new project as you please.
-
Install
@datastax/astra-db-ts
by runningnpm i @datastax/astra-db-ts
. -
Set up a CORS proxy to forward requests to the Data API. You can use something like cors-anywhere, corsproxy.io, or any other CORS proxy of your choice.
-
When doing
client.db()
, prefix the endpoint URL with the CORS proxy URL as appropriate. -
You should be able to use
@datastax/astra-db-ts
in your project as normal now.
Please be very careful about not hard-coding credentials or sensitive data in your client-side code.
import { DataAPIClient } from '@datastax/astra-db-ts';
const client = new DataAPIClient(prompt('Enter your AstraDB API key: '));
const db = client.db(`${import.meta.env.CORS_PROXY_URL}${import.meta.env.ASTRA_DB_ENDPOINT}`);
const app = document.querySelector<HTMLDivElement>('#app')!;
app.innerHTML = '<p>Loading...</p>';
db.listCollections().then((collections) => {
app.innerHTML = `<code>${JSON.stringify(collections, null, 2)}</code>`;
});