🔥 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 Turso Guide: libSQL Queries at Build Time and Runtime

Use Astro with Turso: create a libSQL database, query it with @libsql/client at build time or per request, write with Astro Actions, and add Drizzle or Astro DB.

#Astro#Turso#libSQL#Database#SQLite

To use Turso with Astro, create a database with the Turso CLI, copy its libsql:// URL and an auth token into your environment, and query it with createClient() from @libsql/client. Queries in page frontmatter or getStaticPaths() run at build time on a static site; with an adapter, the same client runs per request in endpoints, Actions and on-demand pages. Turso hosts libSQL, an open-source fork of SQLite, over HTTP.

This guide covers setup, reads, writes, local development, Drizzle and Astro DB on Astro 7.

Key Takeaways

  • Turso gives you SQLite-compatible databases you reach over HTTP, which suits serverless and edge functions.
  • Use @libsql/client in Node.js and @libsql/client/web on Cloudflare Workers and other fetch-only runtimes.
  • Always pass user input through args, never by building SQL strings.
  • Point the same code at file:local.db during development, so you don’t need the network.
  • Astro DB can use a Turso database as its remote, if you want typed tables managed by Astro.

Why Turso fits Astro

Astro sites are often static with a few dynamic routes: a contact form, a guestbook, a “views” counter, a small directory. Those need a database that’s cheap when idle and doesn’t fall over when a serverless function opens a new connection on every request. Turso answers both. Each request is an HTTP call, so there’s no connection pool to exhaust, and SQLite’s file-per-database model keeps small projects small.

Need Turso approach
Build-time data for static pages Query in getStaticPaths() or a content loader
Per-request reads and writes @libsql/client in an on-demand route or Action
Edge runtimes @libsql/client/web (HTTP only)
Local development file: URL pointing at a local SQLite file
Typed queries Drizzle ORM, or Astro DB with a Turso remote

It’s a good fit for read-heavy, small-to-medium data. For complex relational workloads with heavy concurrent writes, a Postgres host like Supabase or Neon may suit better. Our Astro database options guide compares them side by side.

Create a database with the Turso CLI

Install the CLI (see Turso’s docs for your platform), log in, and create a database:

turso auth login
turso db create astro-site
turso db show astro-site --url
turso db tokens create astro-site

show --url prints the libsql:// URL and tokens create prints an auth token. Put both in .env and in your host’s environment settings:

# .env
TURSO_DATABASE_URL=libsql://astro-site-yourname.turso.io
TURSO_AUTH_TOKEN=eyJhbGciOi...

Create a table from the interactive shell:

turso db shell astro-site
CREATE TABLE guestbook (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL,
  message TEXT NOT NULL,
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

Tokens can be scoped. Create a read-only token (--read-only) for build machines that only query, and keep the full-access token for the server that writes.

Connect with @libsql/client

npm install @libsql/client

Declare the variables with astro:env so a missing value fails the build early:

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

export default defineConfig({
  adapter: node({ mode: 'standalone' }),
  env: {
    schema: {
      TURSO_DATABASE_URL: envField.string({ context: 'server', access: 'secret' }),
      TURSO_AUTH_TOKEN: envField.string({ context: 'server', access: 'secret', optional: true }),
    },
  },
});

The token is optional so local file: URLs work without one. Then create a single client module:

// src/lib/turso.ts
import { createClient } from '@libsql/client';
import { TURSO_DATABASE_URL, TURSO_AUTH_TOKEN } from 'astro:env/server';

export const turso = createClient({
  url: TURSO_DATABASE_URL,
  authToken: TURSO_AUTH_TOKEN,
});

On Cloudflare Workers, import from @libsql/client/web instead. The default entry point includes native SQLite bindings for file: URLs that fetch-only runtimes can’t load. The environment variables guide explains astro:env in full.

Read data at build time

On a static site, a query in getStaticPaths() runs once during astro build and the results become HTML. Here’s a directory with one page per listing:

---
// src/pages/directory/[slug].astro
import { turso } from '../../lib/turso';
import BaseLayout from '../../layouts/BaseLayout.astro';

export async function getStaticPaths() {
  const { rows } = await turso.execute(
    'SELECT slug, name, city, description FROM listings WHERE published = 1 ORDER BY name',
  );
  return rows.map((row) => ({
    params: { slug: String(row.slug) },
    props: { name: String(row.name), city: String(row.city), description: String(row.description) },
  }));
}

const { name, city, description } = Astro.props;
---
<BaseLayout title={`${name}, ${city}`}>
  <h1>{name}</h1>
  <p>{city}</p>
  <p>{description}</p>
</BaseLayout>

execute() returns a ResultSet whose rows you can read by column name. Values come back as SQLite types, so convert them explicitly; integers may arrive as number or bigint depending on the intMode option. Rebuild the site when listings change, either from your admin tool or on a schedule. Our getStaticPaths guide covers params and props in detail.

Read and write per request

With an adapter, any page that sets prerender = false queries Turso on every request. A guestbook shows both halves. The write goes through an Astro Action:

// src/actions/index.ts
import { defineAction } from 'astro:actions';
import { z } from 'astro/zod';
import { turso } from '../lib/turso';

export const server = {
  sign: defineAction({
    accept: 'form',
    input: z.object({
      name: z.string().trim().min(1).max(60),
      message: z.string().trim().min(1).max(500),
    }),
    handler: async ({ name, message }) => {
      await turso.execute({
        sql: 'INSERT INTO guestbook (name, message) VALUES (?, ?)',
        args: [name, message],
      });
      return { ok: true };
    },
  }),
};

And the page reads the latest entries:

---
// src/pages/guestbook.astro
import { actions } from 'astro:actions';
import { turso } from '../lib/turso';

export const prerender = false;

const result = Astro.getActionResult(actions.sign);
const { rows } = await turso.execute(
  'SELECT name, message, created_at FROM guestbook ORDER BY id DESC LIMIT 50',
);
---
<h1>Guestbook</h1>
<form method="POST" action={actions.sign}>
  <label>Name <input name="name" required maxlength="60" /></label>
  <label>Message <textarea name="message" required maxlength="500"></textarea></label>
  <button>Sign</button>
  {result?.error && <p role="alert">Please check your entry.</p>}
</form>
<ul>
  {rows.map((r) => <li><strong>{String(r.name)}</strong>: {String(r.message)}</li>)}
</ul>

The ? placeholders and args array make the driver send values separately from the SQL, which is what prevents SQL injection. Named parameters (:name with an args object) work too. For several statements that must succeed together, use turso.batch([...], 'write'), which runs them in one transaction. The Astro Actions guide explains validation and error handling.

Local development without the network

libSQL reads plain SQLite files, so you can develop against a local file and switch to Turso by changing one variable:

# .env.development
TURSO_DATABASE_URL=file:local.db

Astro loads .env.development during astro dev, so the dev server uses local.db and production uses the libsql:// URL. You can also run turso dev --db-file local.db to start a local libSQL server that speaks the same HTTP protocol as the hosted service. Add local.db to .gitignore.

For Node servers that read far more than they write, libSQL also supports embedded replicas: set url to a local file: path and syncUrl to the Turso URL, and reads come from the local copy while writes go to the remote. That needs a persistent filesystem, so it fits a long-running Node server rather than serverless functions.

Typed queries with Drizzle or Astro DB

Raw SQL is fine for a few queries. For more, add a typed layer.

Drizzle ORM has a libSQL driver:

// src/lib/db.ts
import { drizzle } from 'drizzle-orm/libsql';
import { sqliteTable, integer, text } from 'drizzle-orm/sqlite-core';
import { turso } from './turso';

export const guestbook = sqliteTable('guestbook', {
  id: integer('id').primaryKey({ autoIncrement: true }),
  name: text('name').notNull(),
  message: text('message').notNull(),
  createdAt: text('created_at').notNull(),
});

export const db = drizzle(turso);

Then await db.select().from(guestbook).limit(50) returns typed rows, and drizzle-kit manages migrations.

Astro DB (@astrojs/db) is Astro’s own integration, built on libSQL and Drizzle. You define tables in db/config.ts, get a local database in development, and point production at a Turso database with ASTRO_DB_REMOTE_URL and ASTRO_DB_APP_TOKEN. Push the schema with astro db push --remote and build with astro build --remote. Choose it if you want the schema, seeding and types managed inside the Astro project; see the Astro DB docs.

Hosting notes

  • Static sites only need the database during the build. Add the URL and a read-only token to your CI or host build settings, and deploy anywhere.
  • Node, Netlify and Vercel adapters work with the default @libsql/client import.
  • Cloudflare adapter: import @libsql/client/web, and read secrets through astro:env or the runtime environment.
  • Latency: create the database in a region close to where your functions run. A function in one region querying a database on another continent adds a round trip to every request.

If you’re building a directory or listing site, a theme from the Technology category or Real Estate category gives you the listing and detail layouts, and Turso supplies the data behind them.

FAQ

Is Turso the same as SQLite?

Turso runs libSQL, an open-source fork of SQLite that keeps SQLite’s file format and SQL dialect and adds a network protocol, replication and other features. Most SQLite queries and schemas work unchanged, and @libsql/client can open plain SQLite files too.

Can I use Turso with a static Astro site?

Yes. Query Turso in page frontmatter, getStaticPaths() or a content loader, and the results are baked into static HTML at build time. You only need an adapter if pages must read fresh data or accept writes per request.

Which Turso client should I use on Cloudflare?

Import createClient from @libsql/client/web. It talks to Turso over HTTP with fetch and has no native dependencies, so it runs on Cloudflare Workers and other edge runtimes. It can’t open local file: databases.

Do I need Astro DB to use Turso?

No. @libsql/client works on its own, with or without Drizzle. Astro DB is an optional integration that adds a typed schema, seeding and a local dev database, and it can use a Turso database as its production remote.

How do I keep my Turso auth token safe in Astro?

Declare it with envField.string({ context: 'server', access: 'secret' }) so it’s only available in server code, store it in your host’s environment settings, and never import the Turso client into a client:* component or <script>. Use read-only tokens where writes aren’t needed.