Learn how you can use Turso as your unkey cache data store.
Unkey is a new way to build APIs faster. If you're looking for a solution that manages API keys for users, rate limiting, and usage analytics for APIs at scale, Unkey is a great choice.
Caching should be easy to implement, typesafe, and composable according to Unkey. That's why Unkey has a cache middleware library @unkey/cache
that can be used with any cache store, including Turso.
To add caching to your API, all you need to do is install the @unkey/cache
and @libsql/client
packages:
npm install @unkey/cache @libsql/client
Now inside your Turso database, execute the following SQL to create a cache
table:
CREATE TABLE IF NOT EXISTS cache (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
freshUntil INTEGER NOT NULL,
staleUntil INTEGER NOT NULL
);
Then back inside your application, configure the LibSQLStore
to use your @libsql/client
instance:
import { LibSQLStore } from '@unkey/cache/stores';
import { createClient } from '@libsql/client';
const client = createClient({
url: 'libsql://...',
authToken: '...',
});
const libsqlStore = new LibSQLStore({
client,
});
If you're working with Embedded Replicas, you can embed your cache right alongside your app code if your provider supports writing to write a file. This is a great way to reduce read latency and improve performance.
Configuring Embedded Replicas is easy. Just change the url
to file:local.db
and syncUrl
to your remote database:
const client = createClient({
url: 'file:local.db',
syncUrl: 'libsql://...',
authToken: '...',
});
Once you're ready, pass your libsqlStore
to the cache
and namespace:
import { Namespace, createCache } from '@unkey/cache';
import { LibSQLStore } from '@unkey/cache/stores';
const cache = createCache({
account: new Namespace<{ name: string }>(ctx, {
stores: [libsqlStore],
fresh: 60_000,
stale: 900_000,
}),
});
Now when using the cache in your application, it will use Turso as the store for your values:
await cache.account.set('key', { name: 'Iku!' });
const user = await cache.user.get('user_123');
If you're interested in learning more about Unkey, check out the following resources: