Skip to main content

Native Resources

Declare and use Cloudflare-native storage resources (KV, D1, Vectorize) directly from your EdgeBase project. These are user-defined resources, completely isolated from EdgeBase's internal bindings.

For detailed API usage, see the Native Resources API Reference.

Overview

Native resources are declared in edgebase.config.ts and automatically provisioned when you deploy. They provide direct access to Cloudflare's storage primitives for use cases that go beyond EdgeBase's built-in Durable Object collections.

ResourceWhat It IsBest For
KVGlobal key-value storeCaching, sessions, feature flags
D1SQLite databaseAnalytics, logs, relational queries
VectorizeVector search indexSemantic search, RAG, recommendations

All native resource APIs require a Service Key (X-EdgeBase-Service-Key header). They are not accessible from client SDKs.

Language Coverage

KV, D1, and Vectorize are available from all Admin SDKs.

Auto-Provisioning

When you run npx edgebase deploy, EdgeBase automatically creates any declared resources that do not already exist:

  • KV: wrangler kv namespace create
  • D1: wrangler d1 create
  • Vectorize: Creates an index with the specified dimensions and metric

Re-deploys are safe. Existing resources are reused without modification.

A temporary wrangler.toml is generated with the required bindings during deployment. Your source wrangler.toml is never modified.

Internal vs. User Resources

EdgeBase uses its own internal KV and D1 bindings for system purposes. Today that includes OAuth state in KV plus two internal D1 databases: AUTH_DB for auth state and CONTROL_DB for plugin/control-plane metadata. User-defined native resources are completely separate Wrangler bindings. There is no way to access internal resources through the native resource APIs, and no risk of collision.


KV Storage

A globally distributed key-value store for caching, session data, and configuration.

Config

edgebase.config.ts
import { defineConfig } from '@edgebase/shared';

export default defineConfig({
kv: {
cache: { binding: 'CACHE_KV' },
sessions: { binding: 'SESSIONS_KV' },
},
});

This declares two KV namespaces: cache and sessions, each with an explicit Wrangler binding name.

Access Rules

KV namespaces support optional read and write rules for access control:

edgebase.config.ts
export default defineConfig({
kv: {
cache: {
binding: 'CACHE_KV',
rules: {
read(auth) {
return auth !== null
},
write(auth) {
return auth !== null && auth.role === 'admin'
},
},
},
},
});
RuleOperationsSignature
readget, list(auth: AuthContext | null) => boolean
writeset, delete(auth: AuthContext | null) => boolean

Without rules defined, KV access falls back to Service Key validation only. See Service Keys for scoped access (kv:namespace:cache:read, kv:namespace:cache:write).

REST API

POST /api/kv/:namespace
Headers: X-EdgeBase-Service-Key: <key>

Get a value:

{ "action": "get", "key": "user:123" }

Set a value (with optional TTL in seconds):

{ "action": "set", "key": "user:123", "value": "cached-data", "ttl": 300 }

Delete a key:

{ "action": "delete", "key": "user:123" }

List keys:

{ "action": "list", "prefix": "user:", "limit": 100 }

SDK

import { createAdminClient } from '@edgebase/admin';

const admin = createAdminClient('https://your-app.example.com', {
serviceKey: process.env.EDGEBASE_SERVICE_KEY!,
});

await admin.kv('cache').set('user:123', 'cached-data', { ttl: 300 });
const value = await admin.kv('cache').get('user:123');
const keys = await admin.kv('cache').list({ prefix: 'user:' });

D1 Database

A full SQL database built on SQLite. Unlike the built-in Durable Object collections, D1 is a standalone database with no per-instance isolation, making it suitable for cross-cutting data like analytics and logs.

Config

edgebase.config.ts
import { defineConfig } from '@edgebase/shared';

export default defineConfig({
d1: ['analytics'],
});

REST API

POST /api/d1/:database
Headers: X-EdgeBase-Service-Key: <key>
{
"query": "SELECT event, COUNT(*) as cnt FROM events WHERE ts > ? GROUP BY event",
"params": ["2026-01-01"]
}

SDK

import { createAdminClient } from '@edgebase/admin';

const admin = createAdminClient('https://your-app.example.com', {
serviceKey: process.env.EDGEBASE_SERVICE_KEY!,
});

const rows = await admin.d1('analytics').exec(
'SELECT event, COUNT(*) as cnt FROM events WHERE ts > ? GROUP BY event',
['2026-01-01']
);

D1 supports all standard SQL operations including DDL (CREATE TABLE, ALTER TABLE), DML, and aggregations.

D1 Consistency

D1 uses eventual consistency by default. Read-your-own-writes is not guaranteed without the Sessions API. Design your application accordingly.


Vectorize

A vector search index for building semantic search, retrieval-augmented generation (RAG), and recommendation features.

Config

edgebase.config.ts
import { defineConfig } from '@edgebase/shared';

export default defineConfig({
vectorize: [{
name: 'embeddings',
dimensions: 1536,
metric: 'cosine',
}],
});
FieldRequiredDescription
nameYesThe index name, used in API calls and SDK methods
dimensionsYesVector dimensionality (must match your embedding model output)
metricYesDistance metric: cosine, euclidean, or dot-product

REST API

POST /api/vectorize/:index
Headers: X-EdgeBase-Service-Key: <key>

Search:

{
"action": "search",
"vector": [0.1, 0.2, 0.3],
"topK": 10,
"filter": { "category": "docs" }
}

Upsert vectors:

{
"action": "upsert",
"vectors": [
{ "id": "doc-1", "values": [0.1, 0.2, 0.3], "metadata": { "title": "Hello" } }
]
}

Delete vectors:

{ "action": "delete", "ids": ["doc-1", "doc-2"] }

SDK

import { createAdminClient } from '@edgebase/admin';

const admin = createAdminClient('https://your-app.example.com', {
serviceKey: process.env.EDGEBASE_SERVICE_KEY!,
});

await admin.vector('embeddings').upsert([
{ id: 'doc-1', values: [0.1, 0.2], metadata: { title: 'Hello' } },
]);
const matches = await admin.vector('embeddings').search([0.1, 0.2], { topK: 10 });

Use Cases

  • Semantic search: Embed documents and search by meaning instead of keywords
  • Retrieval workflows: Retrieve relevant context for semantic search and ranked lookup flows
  • Recommendations: Find similar items based on user behavior or item attributes
Edge Only

Vectorize is only available on Cloudflare Edge. In local and Docker environments, all Vectorize calls return stub responses with _stub: true and a console warning. This allows development to proceed without errors.


Access from App Functions

Inside App Functions, native resources are available through context.admin:

// functions/recommend.ts
import { defineFunction } from '@edgebase/shared';

export default defineFunction({
trigger: { type: 'http', method: 'GET', path: '/recommendations' },
handler: async ({ admin, auth }) => {
// Check cache first
const cacheKey = `recs:${auth.id}`;
const cached = await admin.kv('cache').get(cacheKey);
if (cached) return JSON.parse(cached);

// Query analytics for user behavior
const events = await admin.d1('analytics').exec(
'SELECT item_id, COUNT(*) as views FROM events WHERE user_id = ? GROUP BY item_id ORDER BY views DESC LIMIT 5',
[auth.id]
);

// Find similar items via vector search
const embedding = await generateEmbedding(events.rows);
const similar = await admin.vector('embeddings').search(embedding, { topK: 10 });

// Cache the result
const result = similar.matches;
await admin.kv('cache').set(cacheKey, JSON.stringify(result), { ttl: 600 });

return result;
},
});

Security

  • Allowlist: Only resources declared in edgebase.config.ts are accessible. Requests to undeclared names return 404.
  • Service Key required: All native resource routes require a valid Service Key. Missing key returns 403, invalid key returns 401.
  • Scoped keys: Use scoped Service Keys for fine-grained access control (e.g., kv:namespace:cache:read, d1:database:analytics:exec, vectorize:index:embeddings:query).
  • Isolation: User-defined resources are completely separate from EdgeBase's internal KV and D1 bindings.

Environment Compatibility

ResourceEdgeDockerNode.js (edgebase dev)
KVNativeMiniflare emulationMiniflare emulation
D1NativeMiniflare emulationMiniflare emulation
VectorizeNativeStub responsesStub responses