🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
CMS & Integrations••By Komal Nakrani

Astro Database Options: 8 Databases That Work Well

The best Astro database options compared: Astro DB, Turso, Supabase, Neon, Cloudflare D1, SQLite and more, with code for build-time and on-demand queries.

#Astro#Database#Astro DB#Supabase#SQL

The best Astro database depends on when you query it. For data read at build time, almost anything works, including a local SQLite file. For data read or written per request, pick a database with an HTTP or serverless-friendly driver: Astro DB (libSQL), Turso, Supabase, Neon or Cloudflare D1 are the most common choices, and each pairs with an Astro adapter for on-demand routes.

Astro itself has no database layer you must use. Frontmatter and endpoints run JavaScript on the server, so any Node-compatible client library works. What changes the choice is your host, whether pages are static or on-demand, and whether you also need auth or storage from the same provider.

Key Takeaways

  • Static Astro sites query databases only during astro build; visitors never hit the database.
  • On-demand routes need an adapter and export const prerender = false, plus a database that handles short-lived serverless connections.
  • Astro DB is the integrated option: typed tables in db/config.ts, a local dev database and a libSQL remote in production.
  • Supabase and Neon give you Postgres; Turso and D1 give you SQLite at the edge.
  • Keep credentials in server-only environment variables with astro:env, never in client code.

Build time vs request time

Before choosing a database, decide where queries run.

Mode When the query runs What you need
Static (default) Once, during astro build Network access from your build machine
On-demand route On every request An adapter, prerender = false, a serverless-safe driver
Server island Per request, for one component An adapter and server:defer on the component
Action or endpoint When a form or fetch calls it An adapter for writes at runtime

A product catalogue that changes daily can stay static and rebuild on a schedule or webhook. Comments, carts, dashboards and form submissions need runtime queries. The Astro SSR guide explains adapters and on-demand rendering, and mixing static and on-demand pages shows how to combine them per route.

1. Astro DB

Astro DB (@astrojs/db) is Astro’s own SQL integration, built on libSQL. You define tables in TypeScript, get typed queries through Drizzle, and run a local database automatically in development.

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

const Comment = defineTable({
  columns: {
    id: column.number({ primaryKey: true }),
    postSlug: column.text(),
    author: column.text(),
    body: column.text(),
    createdAt: column.date({ default: new Date() }),
  },
});

export default defineDb({ tables: { Comment } });
---
// src/components/Comments.astro
import { db, Comment, eq } from 'astro:db';
const { slug } = Astro.props;
const comments = await db.select().from(Comment).where(eq(Comment.postSlug, slug));
---
<ul>{comments.map((c) => <li><strong>{c.author}</strong>: {c.body}</li>)}</ul>

For production, point it at a libSQL database (Turso or self-hosted) with ASTRO_DB_REMOTE_URL and ASTRO_DB_APP_TOKEN, push the schema with astro db push --remote, and build with astro build --remote. Astro’s hosted Studio service closed, so you bring your own libSQL host.

Good for: teams who want the most Astro-native setup with typed schemas and seed files.

2. Turso (libSQL)

Turso hosts libSQL, a fork of SQLite, with replicas in many regions and an HTTP-based client that works in serverless and edge functions. It is the usual remote for Astro DB, and you can also use it directly:

// src/lib/db.ts
import { createClient } from '@libsql/client';
import { TURSO_URL, TURSO_TOKEN } from 'astro:env/server';

export const db = createClient({ url: TURSO_URL, authToken: TURSO_TOKEN });
// src/pages/api/views.ts
import type { APIRoute } from 'astro';
import { db } from '../../lib/db';

export const prerender = false;

export const POST: APIRoute = async ({ request }) => {
  const { slug } = await request.json();
  await db.execute({ sql: 'UPDATE posts SET views = views + 1 WHERE slug = ?', args: [slug] });
  return new Response(null, { status: 204 });
};

Good for: read-heavy sites on edge hosts that want SQLite semantics and low latency.

3. Supabase

Supabase is Postgres with auth, storage, realtime and auto-generated APIs. The @supabase/supabase-js client talks over HTTP, which suits serverless functions, and row-level security policies let you expose some tables safely.

// src/lib/supabase.ts
import { createClient } from '@supabase/supabase-js';
import { SUPABASE_URL, SUPABASE_ANON_KEY } from 'astro:env/server';

export const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
---
// src/pages/jobs.astro
import { supabase } from '../lib/supabase';
const { data: jobs = [] } = await supabase.from('jobs').select('id, title, location').eq('open', true);
---
<ul>{jobs?.map((j) => <li>{j.title}, {j.location}</li>)}</ul>

For server-rendered auth, Supabase’s @supabase/ssr package handles cookies in middleware.

Good for: projects that need a database and user accounts from one provider.

4. Neon (serverless Postgres)

Neon is serverless Postgres with branching, so each preview deployment can get its own copy of the database. Its @neondatabase/serverless driver queries over HTTP or WebSockets, which avoids connection exhaustion in functions.

// src/lib/sql.ts
import { neon } from '@neondatabase/serverless';
import { DATABASE_URL } from 'astro:env/server';

export const sql = neon(DATABASE_URL);
---
// src/pages/changelog.astro
import { sql } from '../lib/sql';
const entries = await sql`SELECT version, summary FROM releases ORDER BY released_at DESC LIMIT 20`;
---
<ol>{entries.map((e) => <li>{e.version}: {e.summary}</li>)}</ol>

Good for: Postgres users on Vercel, Netlify or Cloudflare who want scale-to-zero and per-branch databases.

5. Cloudflare D1

D1 is Cloudflare’s SQLite database, bound directly to Workers. With the Cloudflare adapter, you declare the binding in your Wrangler config and query it from server code with no connection string or network hop beyond Cloudflare’s network.

// src/pages/api/subscribe.ts
import type { APIRoute } from 'astro';
import { env } from 'cloudflare:workers';

export const prerender = false;

export const POST: APIRoute = async ({ request }) => {
  const form = await request.formData();
  await env.DB.prepare('INSERT INTO subscribers (email) VALUES (?)')
    .bind(String(form.get('email')))
    .run();
  return new Response('Thanks', { status: 200 });
};

Good for: sites already deployed to Cloudflare that want a database with no extra vendor.

6. PostgreSQL or MySQL you already run

If your company has a Postgres or MySQL database, Astro can use it through the standard drivers (pg, postgres, mysql2) when you deploy with the Node.js adapter to a long-running server. Pooled connections work normally there. On serverless hosts, put a pooler in front (PgBouncer, or the provider’s pooled connection string) so each function does not open a new connection.

Hosted options like PlanetScale (MySQL and Postgres) and AWS RDS fit the same pattern.

Good for: existing infrastructure and teams with DBAs.

7. SQLite or JSON at build time

For static sites, the simplest database is a file. Read a SQLite file with better-sqlite3, or load JSON and CSV into a content collection with the file() loader, and Astro generates static pages from it:

// src/content.config.ts
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
import { file } from 'astro/loaders';

export const collections = {
  stores: defineCollection({
    loader: file('src/data/stores.json'),
    schema: z.object({ id: z.string(), city: z.string(), address: z.string() }),
  }),
};

There is nothing to host and nothing to secure at runtime. The content collections guide covers loaders in depth.

Good for: directories, catalogues and reference data that change on deploy.

8. Document databases: MongoDB and Firestore

MongoDB Atlas and Google Firestore both have Node.js SDKs that work in Astro server code. Firestore’s client fits real-time apps; MongoDB suits flexible document data. Both are better on a Node.js server than in edge functions, so check driver compatibility with your adapter.

Good for: teams already invested in those ecosystems.

Comparison table

Database Type Serverless/edge friendly Extras Best fit
Astro DB libSQL (SQLite) Yes Typed schema, seeding, local dev Astro-native projects
Turso libSQL (SQLite) Yes Global replicas Edge, read-heavy
Supabase Postgres Yes (HTTP client) Auth, storage, realtime Apps with accounts
Neon Postgres Yes (HTTP driver) Branching, scale to zero Preview-heavy teams
Cloudflare D1 SQLite Yes (bindings) No connection strings Cloudflare deploys
Self-run Postgres/MySQL SQL With a pooler Full control Existing infra
SQLite/JSON files Files Build time only Zero runtime Static sites
MongoDB / Firestore Document Mostly Node.js Flexible schema Existing users

ORMs and query builders

You do not need an ORM, but two are common in Astro projects:

  • Drizzle ORM is TypeScript-first and lightweight, works with Postgres, MySQL and SQLite drivers, and runs in edge environments. Astro DB uses Drizzle under the hood.
  • Prisma has a mature schema language and migrations. Check its current edge and serverless support for your host before choosing it.

Keep credentials server-side

Database URLs and tokens belong in server-only variables. Declare them with astro:env so they are validated at startup and cannot be imported into client code:

// astro.config.mjs
import { defineConfig, envField } from 'astro/config';

export default defineConfig({
  env: {
    schema: {
      DATABASE_URL: envField.string({ context: 'server', access: 'secret' }),
    },
  },
});

If a variable is missing, Astro stops with a clear error; the invalid environment variables fix explains it. The Astro environment variables docs cover the full API.

How to choose

  1. Static site with data that changes on deploy: JSON, CSV or SQLite at build time.
  2. Astro-only project needing runtime data: Astro DB with a Turso remote.
  3. Needs user accounts too: Supabase.
  4. Postgres team with preview deployments: Neon.
  5. Deploying to Cloudflare: D1.
  6. Company database already exists: the standard driver on the Node.js adapter, with pooling.

Most marketing sites, portfolios and blogs never need a runtime database at all. If that is your project, a static theme is the faster start: every Komal Astro theme builds to plain files with no server or database to maintain.

FAQ

Does Astro have a built-in database?

Astro offers Astro DB as an official integration (@astrojs/db), which you add with npx astro add db. It is optional. Astro works with any database that has a JavaScript client.

Can a static Astro site use a database?

Yes, at build time. Frontmatter queries run during astro build, and the results are written into static HTML. Visitors never touch the database. To show fresh data, rebuild on a schedule or webhook.

What is the best database for Astro on Vercel or Netlify?

A database with an HTTP or serverless driver avoids connection limits: Neon, Supabase, Turso or Astro DB with a libSQL remote all work well in serverless functions.

Can I use Prisma with Astro?

Yes, in server code such as frontmatter of on-demand pages, endpoints and actions. Check Prisma’s documentation for the runtime your adapter targets, especially for edge deployments.

Is Astro DB free?

The integration is free and open source. You pay for whichever libSQL host you connect in production, such as Turso, according to that provider’s plans.