Use key-value and SQL storage from a function
Each distribution can have two stores that only its function runtimes use:
- Key-value (
env.kv) — string values by key, with versions for safe concurrent writes, expiry, and counters. Good for sessions, rate limits, vote counts and flags. - SQL (
env.sql) — one SQLite database per distribution. Good for anything you want to query: sign-ups, comments, orders, a small CRM.
Visitors never reach either store directly. A visitor calls an /_api endpoint, the function runs, and the function reads or writes the store. Nothing on this page changes the live site's files or deployments.
Access is a store grant on the distribution, set outside the function source. Handler code cannot create, change, or bypass it. Store grants, keys, and SQL are not managed in the web console yet. Use an agent, the CLI, or the API. Creating and invoking the function itself stays with the agent.
This page assumes a distribution with at least one compiled function runtime. If not, start with Add an endpoint. Throughout, that distribution is acme-marketing (d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38) and the handler script is 01JBQZ8XKT4A9WN2CDEFGH5RM7.
1. Grant the function a store
Pick the store (kv or sql) and a mode: read or read-write. Optionally name scripts with their own read or write access; without a list, every function on the distribution gets the mode. Mode none removes the grant and keeps the data.
On acme-marketing, give every function read-write access to the key-value store.edge api PUT /v1/distributions/d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38/store-grants --input - <<'EOF'
{"store":"kv","mode":"read-write"}
EOFcurl -X PUT "https://api.edge.deca-dev.com/v1/distributions/d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38/store-grants" \
-H "Authorization: Bearer $EDGE_TOKEN" \
-H "Content-Type: application/json" \
-d '{"store":"kv","mode":"read-write"}'To limit one script, name it. The body field is scripts, for example [{"script_id":"01JBQZ8XKT4A9WN2CDEFGH5RM7","access":"write"}] with "store":"sql".
This calls edge_store_grant_set. The first sql grant also creates the distribution's database (database_created: true). The change reaches visitor requests after the runtime update it starts, usually within a few seconds; edge_function_invoke sees it at once.
2. Create your tables (SQL only)
Create the schema before a route depends on it. Several statements in one request run as one transaction: all of them or none.
On acme-marketing, create a SQL table signups with id integer primary key,
email text unique not null, and created_at text default current_timestamp.edge api POST /v1/distributions/d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38/sql --input - <<'EOF'
{"statements":[{"sql":"CREATE TABLE signups (id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL, created_at TEXT DEFAULT current_timestamp)"}]}
EOFcurl -X POST "https://api.edge.deca-dev.com/v1/distributions/d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38/sql" \
-H "Authorization: Bearer $EDGE_TOKEN" \
-H "Content-Type: application/json" \
-d '{"statements":[{"sql":"CREATE TABLE signups (id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL, created_at TEXT DEFAULT current_timestamp)"}]}'This calls edge_sql_execute. A statement that writes needs function.write. To look at the schema later, ask for SELECT name, sql FROM sqlite_schema.
3. Call env.kv and env.sql from the handler
The handler's second argument, env, carries the distribution's stores: env.kv and env.sql, next to env.document. A refused call throws an error with a .code (Python raises KvError or SqlError).
function handler(request, env) {
if (request.method === 'POST') {
const { email } = JSON.parse(request.body || '{}');
try {
env.sql.query('INSERT INTO signups (email) VALUES (?)', [email]);
} catch (error) {
if (error.code === 'sql_error') return { statusCode: 409, body: 'already signed up' };
throw error;
}
const { value } = env.kv.incr('signups:total');
return { statusCode: 201, body: JSON.stringify({ total: value }) };
}
const { rows } = env.sql.query('SELECT email, created_at FROM signups ORDER BY id DESC LIMIT 20');
return { statusCode: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify(rows) };
}Key-value calls:
| Method | Returns |
|---|---|
get(key) | {value, version}; throws not_found |
getMany(keys) | {items} for up to 25 keys; missing keys are left out |
put(key, value, {ttl, ifVersion, ifAbsent}) | {version}. ifVersion writes only if nobody changed the key; ifAbsent only if it does not exist |
incr(key, by, {ttl}) | {value, version}; creates the key at by |
delete(key, {ifVersion}) | {deleted} |
list(prefix, {cursor, limit}) | {keys, cursor}, up to 100 keys per page |
Values are strings, so store JSON with JSON.stringify. ttl is in seconds (60 seconds to one year); an expired key reads as missing at once.
SQL calls:
| Method | Returns |
|---|---|
query(sql, params) | {columns, rows, rows_affected, last_insert_rowid} |
batch([{sql, params}, …]) | {results}; up to 20 statements in one transaction |
Use ? placeholders for values, never string concatenation. A grant with mode read allows only SELECT, VALUES, EXPLAIN and WITH … SELECT.
All stores share eight host calls per invocation (data objects, KV and SQL together). getMany and batch count as one call each, so prefer them when you need several keys or statements.
A function that fetches runs again
A function that calls an outside URL is run again from the start after each fetch, so store calls made before the fetch run again too. Write after fetching, or make the write safe to repeat: ifVersion or ifAbsent for KV, a unique constraint or INSERT OR IGNORE for SQL.
4. Test it before you map a route
Invoke function 01JBQZ8XKT4A9WN2CDEFGH5RM7 on acme-marketing with a POST
body {"email":"ana@example.com"} and show the response.Invoking a function has no HTTP route. The agent runs edge_function_invoke. It uses the same grants and stores as a visitor request. Then map the route as in Add an endpoint.
5. Inspect the data
On acme-marketing, show the 10 newest rows in signups and the value of
the KV key signups:total.edge api POST /v1/distributions/d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38/sql --input - <<'EOF'
{"statements":[{"sql":"SELECT email, created_at FROM signups ORDER BY id DESC LIMIT 10"}]}
EOF
edge api GET /v1/distributions/d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38/kv/signups:totalcurl -X POST "https://api.edge.deca-dev.com/v1/distributions/d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38/sql" \
-H "Authorization: Bearer $EDGE_TOKEN" \
-H "Content-Type: application/json" \
-d '{"statements":[{"sql":"SELECT email, created_at FROM signups ORDER BY id DESC LIMIT 10"}]}'
curl "https://api.edge.deca-dev.com/v1/distributions/d3f7a1c4-90b2-4e6a-8f15-6c2b7e0a9d38/kv/signups:total" \
-H "Authorization: Bearer $EDGE_TOKEN"This calls edge_sql_execute and edge_kv_get. edge_kv_list lists keys by prefix, edge_kv_put and edge_kv_delete change them, and edge_store_grant_get shows the current grants.
Destroying the distribution deletes its functions, its key-value data, and its SQL database.
Next
- Limits — value size, key count, rows per call, database size
- Read and write data objects from a function — JSON documents visitors can also read
- Function runtimes — sandbox caps and outbound HTTPS