DEV Community

Alex Spinov
Alex Spinov

Posted on

Astro DB Has a Free API You've Never Heard Of

Astro DB is a fully managed SQL database designed for Astro websites. It gives you a type-safe database with zero configuration — define your schema in TypeScript, deploy, and query with full type safety.

What Makes Astro DB Special?

  • Zero config — works out of the box with Astro
  • Type-safe — schema and queries fully typed
  • LibSQL — powered by Turso's distributed SQLite
  • Free tier — included with Astro Studio
  • Local dev — SQLite in development, LibSQL in production

The Hidden API: Type-Safe Schema

// db/config.ts
import { defineDb, defineTable, column } from 'astro:db';

const Post = defineTable({
  columns: {
    id: column.number({ primaryKey: true, autoIncrement: true }),
    title: column.text(),
    slug: column.text({ unique: true }),
    content: column.text(),
    published: column.boolean({ default: false }),
    authorId: column.number({ references: () => User.columns.id }),
    createdAt: column.date({ default: new Date() })
  }
});

const User = defineTable({
  columns: {
    id: column.number({ primaryKey: true, autoIncrement: true }),
    name: column.text(),
    email: column.text({ unique: true })
  }
});

export default defineDb({ tables: { Post, User } });
Enter fullscreen mode Exit fullscreen mode

Query API — Drizzle ORM Built-in

// src/pages/posts/[slug].astro
import { db, Post, User, eq } from 'astro:db';

// Type-safe queries
const posts = await db.select()
  .from(Post)
  .where(eq(Post.published, true))
  .orderBy(Post.createdAt)
  .limit(10);

// Joins
const postsWithAuthors = await db.select()
  .from(Post)
  .innerJoin(User, eq(Post.authorId, User.id))
  .where(eq(Post.published, true));

// Insert
await db.insert(Post).values({
  title: 'My New Post',
  slug: 'my-new-post',
  content: 'Hello World',
  authorId: 1
});
Enter fullscreen mode Exit fullscreen mode

Seed Data API

// db/seed.ts
import { db, User, Post } from 'astro:db';

export default async function() {
  await db.insert(User).values([
    { name: 'Alice', email: 'alice@example.com' },
    { name: 'Bob', email: 'bob@example.com' }
  ]);

  await db.insert(Post).values([
    { title: 'First Post', slug: 'first', content: 'Hello!', authorId: 1, published: true }
  ]);
}
Enter fullscreen mode Exit fullscreen mode

Quick Start

npx astro add db
npx astro db push   # Create tables
npx astro db seed   # Seed data
npx astro dev       # Start developing
Enter fullscreen mode Exit fullscreen mode

Why Astro Developers Love It

A developer shared: "I needed a blog with a CMS feel but git-based simplicity. Astro DB gave me a type-safe database with zero config. The local SQLite for dev, distributed LibSQL for prod setup is genius."


Building content sites? Email spinov001@gmail.com or check my tools.

How do you handle data in static sites? Astro DB vs MDX vs CMS?

Top comments (0)