Skip to main content

Turso

This guide discusses the concepts behind using Prisma ORM and Turso, explains the commonalities and differences between Turso and other database providers, and leads you through the process for configuring your application to integrate with Turso.

Prisma ORM support for Turso is currently in Early Access. We would appreciate your feedback in this GitHub discussion.

What is Turso?

Turso is an edge-hosted, distributed database that's based on libSQL, an open-source and open-contribution fork of SQLite, enabling you to bring data closer to your application and minimize query latency. Turso can also be hosted on a remote server.

warning

Support for Turso is available in Early Access from Prisma ORM versions 5.4.2 and later.

Commonalities with other database providers

libSQL is 100% compatible with SQLite. libSQL extends SQLite and adds the following features and capabilities:

  • Support for replication
  • Support for automated backups
  • Ability to embed Turso as part of other programs such as the Linux kernel
  • Supports user-defined functions
  • Support for asynchronous I/O

To learn more about the differences between libSQL and how it is different from SQLite, see libSQL Manifesto.

Many aspects of using Prisma ORM with Turso are just like using Prisma ORM with any other relational database. You can still:

Differences to consider

There are a number of differences between Turso and SQLite to consider. You should be aware of the following when deciding to use Turso and Prisma ORM:

  • Remote and embedded SQLite databases. libSQL uses HTTP to connect to the remote SQLite database. libSQL also supports remote database replicas and embedded replicas. Embedded replicas enable you to replicate your primary database inside your application.
  • Making schema changes. Since libSQL uses HTTP to connect to the remote database, this makes it incompatible with Prisma Migrate. However, you can use prisma migrate diff to create a schema migration and then apply the changes to your database using Turso's CLI.

How to connect and query a Turso database

The subsequent section covers how you can create a Turso database, retrieve your database credentials and connect to your database.

How to provision a database and retrieve database credentials

info

Ensure that you have the Turso CLI installed to manage your databases.

If you don't have an existing database, you can provision a database by running the following command:

turso db create turso-prisma-db

The above command will create a database in the closest region to your location.

Run the following command to retrieve your database's connection string:

turso db show turso-prisma-db

Next, create an authentication token that will allow you to connect to the database:

turso db tokens create turso-prisma-db

Update your .env file with the authentication token and connection string:

.env
TURSO_AUTH_TOKEN="eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9..."
TURSO_DATABASE_URL="libsql://turso-prisma-db-user.turso.io"

How to connect to a Turso database

To get started, enable the driverAdapters Preview feature flag:

generator client {
provider = "prisma-client-js"
previewFeatures = ["driverAdapters"]
}

datasource db {
provider = "sqlite"
url = "file:./dev.db" // will be ignored
}

Generate Prisma Client:

npx prisma generate

Install the Prisma ORM driver adapter for libSQL packages:

npm install @prisma/adapter-libsql

Update your Prisma Client instance:

import { PrismaClient } from '@prisma/client'
import { PrismaLibSQL } from '@prisma/adapter-libsql'

const adapter = new PrismaLibSQL({
url: `${process.env.TURSO_DATABASE_URL}`,
authToken: `${process.env.TURSO_AUTH_TOKEN}`,
})
const prisma = new PrismaClient({ adapter })

You can use Prisma Client as you normally would with full type-safety in your project.

Using Prisma Migrate via a driver adapter in prisma.config.ts (Early Access)

As of v6.6.0 and with a prisma.config.ts file, you can use prisma db push to make changes to your database schema.

warning

This functionality has been introduced in Early Access in v6.6.0 and supports the following commands:

  • prisma db push
  • prisma db pull
  • prisma migrate diff

Other commands like prisma migrate dev and prisma migrate deploy will be added soon.

1. Install the LibSQL driver adapter

Run this command in your terminal:

npm install @prisma/adapter-libsql

2. Set environment variables

In order to set up the LibSQL adapter, you'll need to add a few secrets to a .env file:

  • LIBSQL_DATABASE_URL: The connection URL of your Turso database instance.
  • LIBSQL_DATABASE_TOKEN: The token of your Turso database instance.

You can then add these to your .env file or use them directly if they are stored in a different secret store:

.env
LIBSQL_DATABASE_URL="..."
LIBSQL_DATABASE_TOKEN="..."

3. Set up Prisma Config file

Make sure that you have a prisma.config.ts file for your project. Then, set up the migration driver adapter to use PrismaLibSQL:

prisma.config.ts
import path from 'node:path'
import { defineConfig } from 'prisma/config'
import { PrismaLibSQL } from '@prisma/adapter-libsql'

// import your .env file
import 'dotenv/config'

type Env = {
LIBSQL_DATABASE_URL: string
LIBSQL_DATABASE_TOKEN: string
}

export default defineConfig<Env>({
earlyAccess: true,
schema: path.join('prisma', 'schema.prisma'),

migrate: {
async adapter(env) {
return new PrismaLibSQL({
url: env.LIBSQL_DATABASE_URL,
authToken: env.LIBSQL_DATABASE_TOKEN,
})
}
}
})

4. Migrate your database

Prisma Migrate now will run migrations against your remote Turso database based on the configuration provided in prisma.config.ts.

To create your first migration with this workflow, run the following command:

npx prisma db push

Embedded Turso database replicas

Turso supports embedded replicas. Turso's embedded replicas enable you to have a copy of your primary, remote database inside your application. Embedded replicas behave similarly to a local SQLite database. Database queries are faster because your database is inside your application.

How embedded database replicas work

When your app initially establishes a connection to your database, the primary database will fulfill the query:

Embedded Replica: First remote read

Turso will (1) create an embedded replica inside your application and (2) copy data from your primary database to the replica so it is locally available:

Embedded Replica: Remote DB Copy

The embedded replica will fulfill subsequent read queries. The libSQL client provides a sync() method which you can invoke to ensure the embedded replica's data remains fresh.

Embedded Replica: Local DB reads

With embedded replicas, this setup guarantees a responsive application, because the data will be readily available locally and faster to access.

Like a read replica setup you may be familiar with, write operations are forwarded to the primary remote database and executed before being propagated to all embedded replicas.

Embedded Replica: Write operation propagation

  1. Write operations propagation are forwarded to the database.
  2. Database responds to the server with the updates from 1.
  3. Write operations are propagated to the database replica.

Your application's data needs will determine how often you should synchronize data between your remote database and embedded database replica. For example, you can use either middleware functions (e.g. Express and Fastify) or a cron job to synchronize the data.

How to synchronize data between your remote database and embedded replica

To get started using embedded replicas with Prisma ORM, add the sync() method from libSQL in your application. The example below shows how you can synchronize data using Express middleware.

import express from 'express'
const app = express()

// ... the rest of your application code
app.use(async (req, res, next) => {
await libsql.sync()
next()
})

app.listen(3000, () => console.log(`Server ready at http://localhost:3000`))

It could be also implemented as a Prisma Client extension. The below example shows auto-syncing after create, update or delete operation is performed.

const prisma = new PrismaClient().$extends({
query: {
$allModels: {
async $allOperations({ operation, model, args, query }) {
const result = await query(args)

// Synchronize the embedded replica after any write operation
if (['create', 'update', 'delete'].includes(operation)) {
await libsql.sync()
}

return result
}
}
}
})