Skip to content

Xata & Astro

Xata is a Serverless Data Platform that combines the features of a relational database, a search engine, and an analytics engine by exposing a single consistent REST API.

  • A Xata account with a created database. (You can use the sample database from the Web UI.)
  • An Access Token (XATA_TOKEN_API).
  • Your Database URL.

After you update and initialize the Xata CLI, you will have your API token in your .env file and database URL defined.

By the end of the setup, you should have:

# Xata branch that will be used
# if there's not a xata branch with
# the same name as your git branch

And the databaseURL defined:

"databaseUrl": "https://your-database-url"

To have IntelliSense and type safety for your environment variables, edit or create the file env.d.ts in your src/ directory:

interface ImportMetaEnv {
readonly XATA_API_KEY: string;
readonly XATA_BRANCH?: string;
interface ImportMeta {
readonly env: ImportMetaEnv;

Using the codegeneration from the Xata CLI and choosing the TypeScript option, generated an instance of the SDK for you, with types tailored to your database schema. Additionally, was added to your package.json.

Your Xata environment variables and database url were automatically pulled by the SDK instance, so there’s no more setup work needed.

Now, your project should have the following structure:

  • Directorysrc/
    • xata.ts
    • env.d.ts
  • .env
  • astro.config.mjs
  • package.json
  • .xatarc

To query your posts, import and use XataClient class in a .astro file. The example below queries the first 50 posts from Xata’s Sample Blog Database.

import { XataClient } from '../../xata';
const xata = new XataClient({
apiKey: import.meta.env.XATA_API_KEY,
branch: import.meta.env.XATA_BRANCH
const { records } = await xata.db.Posts.getPaginated({
pagination: {
size: 50
{ => (

It’s important to note the SDK needs to be regenerated everytime your schema changes. So, avoid making changes to the generated files the Xata CLI creates because once schema updates, your changes will be overwritten.

More backend service guides