How to Use Astro DB for Data: A Practical Tutorial
Astro DB is a lightweight, SQLite-based database built specifically for Astro sites. It offers a simple, type-safe API for managing content without a heavy server. In this tutorial, you’ll learn how to set up Astro DB, define a schema, and perform basic CRUD operations on your data.
First, ensure you have Astro 4.0 or newer. Install the integration via your package manager: npm install @astrojs/db. Then add it to your astro.config.mjs with the Astro DB adapter.
Setting Up Astro DB in Your Project
Run npx astro db init to create a local database file (astro.db) and a db/config.ts file. This is where you’ll define tables and columns. For a production deployment, configure a remote SQLite provider like Turso.
Defining Your Data Schema
Inside db/config.ts, use the defineTable function to create a table. For example, create a users table:
import { defineTable, column } from 'astro:db';
export const users = defineTable({
columns: {
id: column.number({ primaryKey: true, autoIncrement: true }),
name: column.text(),
email: column.text({ unique: true }),
createdAt: column.date({ default: new Date() })
}
});
Astro DB uses TypeScript types built‑in, so your schema is automatically typed across your project.
Performing CRUD Operations
Import db from astro:db into any Astro component or endpoint. Use the insert method to add rows:
import { db, users } from 'astro:db';
await db.insert(users).values({ name: 'Alice', email: 'alice@example.com' });
Query with select:
const allUsers = await db.select().from(users);
Update or delete using update and delete with where conditions. All operations return promises and are fully typed.
Querying with Filters and Joins
Use eq, gt, like operators via and/or. Astro DB also supports simple joins between tables defined in the same config file. For example, join a posts table to users using db.select().from(posts).innerJoin(users, eq(posts.authorId, users.id)).
Conclusion
Astro DB offers a frictionless way to manage data inside your static or server‑rendered Astro sites. Start with a local SQLite file, then scale to a production database. With its tight integration and type safety, you can focus on building features rather than wiring up infrastructure.