DEV Community

Alex Spinov
Alex Spinov

Posted on

Astro DB Has a Free API That Gives You a SQL Database Built Into Your Astro Site

Astro DB is a managed SQL database integrated directly into Astro. Define your schema in TypeScript, query with Drizzle ORM syntax, deploy with your site.

Quick Setup

npx astro add db
Enter fullscreen mode Exit fullscreen mode

Define Schema

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

const Posts = defineTable({
  columns: {
    id: column.number({ primaryKey: true }),
    title: column.text(),
    content: column.text(),
    published: column.boolean({ default: false }),
    createdAt: column.date({ default: new Date() })
  }
})

export default defineDb({ tables: { Posts } })
Enter fullscreen mode Exit fullscreen mode

Query

// In any Astro component or API route
import { db, Posts, eq } from 'astro:db'

// Select
const allPosts = await db.select().from(Posts)
const post = await db.select().from(Posts).where(eq(Posts.id, 1))

// Insert
await db.insert(Posts).values({ title: 'Hello', content: 'World', published: true })

// Update
await db.update(Posts).set({ published: true }).where(eq(Posts.id, 1))
Enter fullscreen mode Exit fullscreen mode

Seed Data

// db/seed.ts
import { db, Posts } from 'astro:db'

export default async function() {
  await db.insert(Posts).values([
    { id: 1, title: 'First Post', content: 'Hello world', published: true },
    { id: 2, title: 'Draft', content: 'WIP', published: false }
  ])
}
Enter fullscreen mode Exit fullscreen mode

The Bottom Line

Astro DB removes the "which database?" decision for Astro sites. TypeScript schema, Drizzle queries, deploys with your site. Perfect for content sites that need dynamic data.


Need to automate data collection or build custom scrapers? Check out my Apify actors for ready-made tools, or email spinov001@gmail.com for custom solutions.

Top comments (0)