Up and Running with Turso
Turso is a modern, hosted SQLite database (built on libSQL) that’s lightweight, fast, and easy to connect. This lab walks you through getting started with Turso inside a Next.js app. By the end, you’ll have a working database connection with minimal setup.
Why Turso?
- SQLite everywhere → local dev feels the same as production.
- Cloud syncing → Turso makes SQLite multi-region and production-ready.
- Simple API → a few lines of code to query.
This is perfect if you just want a small, reliable database without heavy server setup.
Prereqs
- Node.js 18+
- A Next.js project (
npx create-next-app@latest my-app
) - Turso account + CLI (we’ll extend into CLI usage in the next lab)
1) Install dependencies
npm install @turso/client
2) Create a Turso database
From your terminal (using the CLI):
turso db create my-next-db
Get the URL and auth token:
turso db show my-next-db
turso db tokens create my-next-db
You’ll see output like:
DB URL: libsql://my-next-db.turso.io
Auth Token: <your-secret-token>
3) Connect inside Next.js
Create a helper under lib/db.ts
:
// lib/db.ts
import { createClient } from "@turso/client";
const url = process.env.TURSO_DB_URL as string;
const authToken = process.env.TURSO_DB_AUTH_TOKEN as string;
export const db = createClient({ url, authToken });
Update .env.local
:
TURSO_DB_URL="libsql://my-next-db.turso.io"
TURSO_DB_AUTH_TOKEN="secret_token_here"
4) Run your first query
Example API route: pages/api/users.ts
// pages/api/users.ts
import type { NextApiRequest, NextApiResponse } from "next";
import { db } from "../../lib/db";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const result = await db.execute("SELECT 1+1 as two");
res.status(200).json(result.rows);
}
Visit: http://localhost:3000/api/users
You should see: [{"two":2}]
5) Create a table and insert
await db.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)");
await db.execute("INSERT INTO users (name) VALUES (?)", ["Ada Lovelace"]);
const rows = await db.execute("SELECT * FROM users");
console.log(rows);
6) Notes
- Turso queries are SQL — everything you know from SQLite applies.
- You don’t need migrations at this stage, just raw SQL.
- Later, you can add schema migrations and edge deployments.