Turso
Turso ↗ is an edge-hosted, distributed database based on libSQL ↗, an open-source fork of SQLite. Turso was designed to minimize query latency for applications where queries comes from anywhere in the world.
Database Integrations allow you to connect to a database from your Worker by getting the right configuration from your database provider and adding it as secrets to your Worker.
Set up an integration with Turso
To set up an integration with Turso:
- You need to install Turso CLI to create and populate a database. Use one of the following two commands in your terminal to install the Turso CLI:
Next, run the following command to make sure the Turso CLI is installed:
- Before you create your first Turso database, you have to authenticate with your GitHub account by running:
After you have authenticated, you can create a database using the command turso db create <DATABASE_NAME>
. Turso will create a database and automatically choose a location closest to you.
With the first database created, you can now connect to it directly and execute SQL queries against it.
-
Copy the following SQL query into the shell you just opened:
-
Add the Turso database integration to your Worker:
- Log in to the Cloudflare dashboard ↗ and select your account.
- In Account Home, select Workers & Pages.
- In Overview, select your Worker.
- Select Integrations > Turso.
- Follow the setup flow, selecting the database created in step 1.
-
In your Worker, install the Turso client library:
- The following example shows how to make a query to your Turso database in a Worker. The credentials needed to connect to Turso have been automatically added as secrets to your Worker through the integration.
- The libSQL client library import
@libsql/client/web
must be imported exactly as shown when working with Cloudflare Workers. The non-web import will not work in the Workers environment. - The
Env
interface contains the environment variable and secret defined when you added the Turso integration in step 4. - The
Env
interface also caches the libSQL client object and router, which was created on the first request to the Worker. - The Worker uses
buildLibsqlClient
to query theelements
database and returns the response as a JSON object.
With your environment configured and your code ready, you can now test your Worker locally before you deploy.
To learn more about Turso, refer to Turso’s official documentation ↗.