astra-db-ts
works natively with Next.js. Just some minor special action is necessary if you need to use
HTTP/2. See examples/http2-when-minified
for more information about using HTTP/2 with Next.js.
This is a simple example of how it can be used to interact with an Astra database; it'll simply list out all the collections in a given database.
Check out the Non-standard environment support section
in the main README.md
for more information common between non-standard environments.
- Make sure you have an existing Astra Database running @ 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. -
Run
npm run dev
to start the local development server. -
Visit
http://localhost:3000
in your browser to see the example in action.
-
Use the typical
npx create-next-app@latest
to create a new Next.js project. -
Install
@datastax/astra-db-ts
by runningnpm i @datastax/astra-db-ts
. -
If you're using the (default)
nodejs
runtime, be sure to sethttpOptions.client
to'fetch'
in theDataAPIClient
-
You should be able to use
@datastax/astra-db-ts
in your project as normal now.
import { DataAPIClient } from '@datastax/astra-db-ts';
// Creates the client. Because the code is minified (when ran), astra-db-ts will default to using
// `fetch` as the HTTP client. If you need HTTP/2, please see `examples/http2-when-minified` for more
// information on how to use HTTP/2 with Next.js
const client = new DataAPIClient(process.env.ASTRA_DB_TOKEN!);
const db = client.db(process.env.ASTRA_DB_ENDPOINT!);
// You may use the edge runtime as normal as well. HTTP/2 is not supported here, at all.
// export const runtime = 'edge';
// Simple example which (attempts to) list all the collections in the database
export async function GET(_: Request) {
try {
const collections = await db.listCollections();
return new Response(JSON.stringify(collections), {
headers: { 'Content-Type': 'application/json' },
});
} catch (error: any) {
return new Response(JSON.stringify({ error: error.message }), {
headers: { 'Content-Type': 'application/json' },
status: 500,
});
}
}