Skip to content

Commit 148b56d

Browse files
authored
Add examples of using Turso Cloud encryption (#207)
2 parents ff83c17 + c882aa0 commit 148b56d

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Example: Connecting to an encrypted Turso Cloud database
2+
//
3+
// This example shows how to connect to a Turso Cloud database with
4+
// remote encryption using libsql-js.
5+
//
6+
// Documentation: https://docs.turso.tech/cloud/encryption
7+
//
8+
// Usage:
9+
//
10+
// export LIBSQL_URL="libsql://your-db.turso.io"
11+
// export LIBSQL_AUTH_TOKEN="your-token"
12+
// export LIBSQL_ENCRYPTION_KEY="encryption key in base64 format"
13+
// node cloud-encryption
14+
//
15+
// The encryption key must be encoded in base64 format.
16+
17+
import Database from "libsql";
18+
19+
const url = process.env.LIBSQL_URL;
20+
const authToken = process.env.LIBSQL_AUTH_TOKEN;
21+
const encryptionKey = process.env.LIBSQL_ENCRYPTION_KEY;
22+
23+
const opts = {
24+
authToken: authToken,
25+
remoteEncryptionKey: encryptionKey,
26+
};
27+
28+
const db = new Database(url, opts);
29+
30+
db.exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)");
31+
db.exec("INSERT OR REPLACE INTO users (id, name, email) VALUES (1, 'Alice', 'alice@example.org')");
32+
db.exec("INSERT OR REPLACE INTO users (id, name, email) VALUES (2, 'Bob', 'bob@example.com')");
33+
34+
const row = db.prepare("SELECT * FROM users WHERE id = ?").get(1);
35+
console.log(`Name: ${row.name}, email: ${row.email}`);
36+
37+
db.close();

examples/sync/example.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,22 @@ if (!url) {
88
const authToken = process.env.LIBSQL_AUTH_TOKEN;
99

1010
const options = { syncUrl: url, authToken: authToken };
11+
12+
// Sync also supports Turso Cloud encryption.
13+
//
14+
// Documentation: https://docs.turso.tech/cloud/encryption
15+
//
16+
//
17+
// export LIBSQL_ENCRYPTION_KEY="encryption key in base64 format"
18+
//
19+
// The encryption key must be encoded in base64 format.
20+
21+
const encryptionKey = process.env.LIBSQL_ENCRYPTION_KEY;
22+
23+
if (encryptionKey) {
24+
options.remoteEncryptionKey = encryptionKey;
25+
}
26+
1127
const db = new Database("hello.db", options);
1228

1329
db.sync();

0 commit comments

Comments
 (0)