12k
All articles

Build a Web App With Turso

Build a TypeScript notes API with Turso and @tursodatabase/serverless. Create a database, connect securely, add CRUD routes, and verify remote SQL writes.

OpenReplay Team
OpenReplay Team
Build a Web App With Turso

To build a web app with Turso, create a database with the Turso CLI, install @tursodatabase/serverless, call connect() with your database URL and auth token, and run SQL with conn.prepare(sql) followed by await stmt.all() or await stmt.get().

Many Turso tutorials are built around @libsql/client and Drizzle, so their code doesn’t match the @tursodatabase/serverless driver that Turso now offers for remote access.

This guide uses one package from start to finish. It takes you from the CLI to a working Node server with list, create and delete routes, and ends with a check that the rows actually reached the remote database.

Key Takeaways

  • @tursodatabase/serverless talks to Turso Cloud using only fetch, so it has no native dependencies and runs in Node.js, serverless functions and edge runtimes.
  • turso db show --url <name> prints the database URL, and turso db tokens create <name> prints the auth token.
  • In @tursodatabase/serverless, you don’t await connect(). The statement methods get(), all() and run() return promises.
  • Pass user input as ? placeholders with an array of values, such as stmt.run([id]). Never concatenate it into the SQL string.
  • Drizzle and Prisma still need @libsql/client, because @tursodatabase/serverless doesn’t support ORMs yet.

What You’ll Build

You’ll build a small notes API: a Node server written in TypeScript with three routes (GET /notes, POST /notes and DELETE /notes/:id), backed by a remote Turso database. Turso is a SQLite-compatible database written in Rust, and its evolution from SQLite fork to full rewrite explains why the package names changed.

Before you start, you need Node.js, npm and the Turso CLI. The CLI must be installed and logged in with turso auth signup or turso auth login, as described in the Turso quickstart.

How Do You Create a Turso Database and Get Credentials?

The Turso CLI creates the database and gives you the two credentials your app needs. Run these three commands:

turso db create notes-app --tursodb
turso db show --url notes-app
turso db tokens create notes-app

The --tursodb flag creates the database on the Turso engine. Without the flag, the CLI creates a libSQL database. Turso-engine databases on Turso Cloud are in early preview. The second command prints the database URL and the third prints an auth token. Copy both, because the next step needs them.

Store Credentials in .env

Keep both values in a .env file at the project root, using the variable names from the Turso TypeScript quickstart:

TURSO_DATABASE_URL=<url-from-turso-db-show>
TURSO_AUTH_TOKEN=<token-from-turso-db-tokens-create>

Then keep the file out of version control:

echo ".env" >> .gitignore

The token authenticates every request to your database, so treat it as you would a password. Anyone who has it can read and write your data.

Connect From TypeScript With @tursodatabase/serverless

@tursodatabase/serverless is Turso’s driver for apps that reach a remote database over the network. It needs only fetch, so the same code runs in Node servers, Docker containers and edge runtimes. Set up the project:

npm init -y
npm pkg set type=module
npm install @tursodatabase/serverless express dotenv
npm install -D tsx typescript @types/express

Create db.ts:

import "dotenv/config";
import { connect } from "@tursodatabase/serverless";

const url = process.env.TURSO_DATABASE_URL;
const authToken = process.env.TURSO_AUTH_TOKEN;

if (!url || !authToken) {
  throw new Error("Set TURSO_DATABASE_URL and TURSO_AUTH_TOKEN in .env");
}

export const conn = connect({ url, authToken });

In @tursodatabase/serverless, connect() is not awaited. If either variable is missing, the module throws at import time, so the server fails immediately instead of failing on the first request.

If you already have code written against the @libsql/client API, import createClient from @tursodatabase/serverless/compat instead. ORMs are a different case: Drizzle and Prisma still require @libsql/client.

Turso’s three JavaScript packages each cover a different case:

PackageUse it for
@tursodatabase/serverlessRemote access from servers, serverless functions and edge runtimes
@tursodatabase/databaseLocal, embedded databases
@libsql/clientLegacy libSQL code and ORM support

Create the Notes Table

With @tursodatabase/serverless, run DDL once at startup with conn.exec(). The schema below uses an INTEGER PRIMARY KEY and plain TEXT columns, which are standard SQLite patterns (see the overview of modern SQLite features for what else the dialect supports). If you edit the statement, you can tidy it with the SQL formatter.

CREATE TABLE IF NOT EXISTS notes (
  id INTEGER PRIMARY KEY,
  body TEXT NOT NULL,
  created_at TEXT NOT NULL
);

The app writes created_at itself as an ISO string. This keeps the timestamp independent of engine-specific column defaults.

Add the Routes

Each Express route prepares a statement with conn.prepare(), binds values through ? placeholders and awaits one statement method. The Turso JavaScript API reference documents exec(), all(), get() and run(). Create server.ts:

import express from "express";
import { conn } from "./db.ts";

await conn.exec(`
  CREATE TABLE IF NOT EXISTS notes (
    id INTEGER PRIMARY KEY,
    body TEXT NOT NULL,
    created_at TEXT NOT NULL
  )
`);

const app = express();
app.use(express.json());

app.get("/notes", async (_req, res) => {
  try {
    const stmt = await conn.prepare(
      "SELECT id, body, created_at FROM notes ORDER BY id DESC"
    );
    res.json(await stmt.all());
  } catch {
    res.status(500).json({ error: "Could not load notes" });
  }
});

The list route returns every note, newest first.

app.post("/notes", async (req, res) => {
  const body = req.body?.body;
  if (typeof body !== "string" || body.trim() === "") {
    res.status(400).json({ error: "body is required" });
    return;
  }
  try {
    const stmt = await conn.prepare(
      "INSERT INTO notes (body, created_at) VALUES (?, ?) RETURNING id, body, created_at"
    );
    const note = await stmt.get([body.trim(), new Date().toISOString()]);
    res.status(201).json(note);
  } catch {
    res.status(500).json({ error: "Could not create note" });
  }
});

User input reaches the database only as bound values in the array passed to get(), never as part of the SQL string, which blocks SQL injection. The Turso engine supports RETURNING, so the insert sends back the new row in the same round trip. Await each write before starting another one on the same connection.

app.delete("/notes/:id", async (req, res) => {
  const id = Number(req.params.id);
  if (!Number.isInteger(id)) {
    res.status(400).json({ error: "Invalid id" });
    return;
  }
  try {
    const stmt = await conn.prepare("DELETE FROM notes WHERE id = ?");
    const result = await stmt.run([id]);
    if (result.changes === 0) {
      res.status(404).json({ error: "Note not found" });
      return;
    }
    res.status(204).end();
  } catch {
    res.status(500).json({ error: "Could not delete note" });
  }
});

app.listen(3000, () => console.log("Listening on http://localhost:3000"));

run() returns { changes, lastInsertRowid }. If changes is zero, no row matched the id, so the route responds with a 404 rather than a misleading 204. All three handlers return generic error messages so raw database errors never reach the client.

Run It and Check the Rows With turso db shell

Start the server, send requests with curl, then query the remote database directly from the CLI:

npx tsx server.ts

In a second terminal:

curl -X POST -H "Content-Type: application/json" -d '{"body":"first note"}' localhost:3000/notes
curl -X POST -H "Content-Type: application/json" -d '{"body":"second note"}' localhost:3000/notes
curl localhost:3000/notes
curl -X DELETE localhost:3000/notes/1

Then open the shell:

turso db shell notes-app
SELECT * FROM notes;

On a fresh database, the query returns one row, the second note, because the app deleted the first. turso db shell opens an interactive SQL prompt connected to the remote database. Querying from there confirms that your app’s writes actually reached Turso Cloud, not just an in-process cache or a mocked layer.

Conclusion

To build against a Turso database you need one package, two env vars and the statement methods all(), get() and run(). Keep every query on @tursodatabase/serverless and bind every user value through ? placeholders. As a next step, add a PATCH /notes/:id route using the same prepare() and run() pattern, and check changes there too so it returns 404 for missing notes.

FAQs

Does @tursodatabase/serverless work with a libSQL database created without --tursodb?

Turso's docs say to match the driver to the database engine. Use @tursodatabase/serverless for Turso databases created with turso db create --tursodb, and use @libsql/client for libSQL databases, which the CLI creates when you leave the flag out. If you already have a libSQL database on Turso Cloud, connect to it with @libsql/client and import from @libsql/client/web in serverless and edge runtimes.

How do I run several writes atomically with @tursodatabase/serverless?

Pass the statements to conn.batch() with a transaction mode. Without a mode, batch() is not transactional: each statement autocommits, so a failure partway through leaves the earlier statements committed. With a mode, the driver wraps the batch in BEGIN and COMMIT, rolls back on failure, and sends the whole batch as one request. Do not put BEGIN, COMMIT or ROLLBACK inside the batched statements yourself.

Does conn.prepare() make a network request in the serverless driver?

Yes. In @tursodatabase/serverless, prepare() makes a round trip to Turso Cloud because the Statement object needs column metadata. That means prepare() followed by run(), get() or all() costs two requests. Recent builds of the driver add connection-level methods with bind parameter support, such as conn.run(sql, ...params), which execute in a single round trip. Check the API reference for the version you have installed.

What is the difference between exec() and run() in @tursodatabase/serverless?

exec(sql) runs SQL without returning rows and takes only the SQL string, so it suits DDL such as CREATE TABLE at startup. run() executes a prepared statement with bound values and returns an object with changes (the number of rows modified) and lastInsertRowid (the rowid of the last inserted row). Use run() for INSERT, UPDATE and DELETE whenever user input is involved.

DevTools for the frontend

Gain Debugging Superpowers

Unleash the power of session replay to reproduce bugs, track slowdowns and uncover frustrations in your app. Get complete visibility into your frontend with OpenReplay — the most advanced open-source session replay tool for developers.

Star on GitHub12k

We use cookies to improve your experience. By using our site, you accept cookies.