Short links manager extension for Cloudflare D1
npm install @potonz/shortlinks-manager-cf-d1Cloudflare D1 backend for short links manager.
- Cloudflare D1 SQLite support for edge deployment
- Automatic table creation and indexing
- Perfect for Cloudflare Workers environment
- Built-in cache integration for high performance
- Lightweight and efficient SQLite operations
``bash`
bun add @potonz/shortlinks-manager-cf-d1
`typescript
import { createManager } from "@potonz/shortlinks-manager";
import { createD1Backend } from "@potonz/shortlinks-manager-cf-d1";
import { env } from "cloudflare:workers";
// Create backend with D1 binding
const backend = createD1Backend(env.DB);
// Initialize tables (run once during setup)
await backend.setupTables();
// Create manager
const manager = await createManager({
backend,
shortIdLength: 6,
onShortIdLengthUpdated: (newLength) => {
console.log(Short ID length updated to ${newLength});
},
});
// Create short link
const shortId = await manager.createShortLink("https://example.com");
console.log(Created short link: ${shortId});
// Resolve short link
const targetUrl = await manager.getTargetUrl(shortId);
console.log(Target URL: ${targetUrl});`
The backend automatically creates the following table:
`sql
CREATE TABLE IF NOT EXISTS sl_links_map (
short_id TEXT NOT NULL PRIMARY KEY,
target_url TEXT NOT NULL,
last_accessed_at INTEGER DEFAULT (strftime('%s', 'now')),
created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);
CREATE INDEX IF NOT EXISTS idx_sl_links_map_last_accessed_at
ON sl_links_map(last_accessed_at);
`
Creates a Cloudflare D1 backend instance.
Parameters:
- db - Cloudflare D1 database binding (typically from env.DB in Workers)
Returns: IShortLinksManagerBackend
Creates the required database tables and indexes. Should be called once during application initialization.
Implements all IShortLinksManagerBackend methods:
- getTargetUrl(shortId) - Get target URL by short IDcreateShortLink(shortId, targetUrl)
- - Create a new short linkcheckShortIdsExist(shortIds)
- - Check which short IDs already existupdateShortLinkLastAccessTime(shortId, time)
- - Update last accessed timestampcleanUnusedLinks(maxAge)
- - Remove links not accessed in maxAge daysremoveShortLink(shortId)
- - Remove a short link by ID
1. Configure D1 binding in wrangler.jsonc:
`jsonc`
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "your-worker-name",
"main": "src/index.ts",
"compatibility_date": "2025-12-25",
"d1_databases": [
{
"binding": "DB",
"database_id": "your-database-id",
"database_name": "shortlinks"
}
]
}
2. Create D1 database:
`bash`
wrangler d1 create shortlinks
3. Deploy with Wrangler:
`bash`
wrangler deploy
Tests run against a local D1-compatible SQLite database.
To run tests locally:
`bash``
bun test packages/shortlinks-manager-cf-d1
MIT