Skip to content
WebShield Docs

Functions

Functions on WebShield's own runtime, compatible with the Workers API — wrangler.jsonc, Durable Objects, D1, KV and cron. Deploys, D1 migrations, KV imports, returning data to a point in time, your own domain behind the WAF.

A function is a small program that answers HTTP requests and runs on a schedule. It runs on our own runtime, compatible with the Workers API — the open standard for serverless functions: the same fetch handler, the same Durable Objects, D1, KV and queue bindings. The code runs not in someone else’s cloud, but on our servers, so every request to a function gets the same protection as a request to an app — the WAF, rate limits, bans and bot protection if you turned it on.

A function lives in a project under Services → Apps: when adding one, choose Function. It is in beta.

  • fetch (HTTP requests) and scheduled (scheduled jobs) handlers;
  • Durable Objects — objects with their own state and SQLite;
  • a D1 database — serverless SQLite;
  • a KV store — key-value storage;
  • queues;
  • variables: vars from the config plus the variables set in the dashboard.

Containers and Sandbox are not supported.

A function is a directory with the code and a wrangler.jsonc file that declares bindings, variables and the schedule. A minimal layout looks like this:

.
├── wrangler.jsonc # function configuration
├── package.json # optional: dependencies and a build script
├── src/index.js # the function code (JavaScript or TypeScript)
└── migrations/ # D1 migrations, if you have a database

The entry point is an exported fetch handler that takes a request and returns a response. The shortest possible function:

export default {
async fetch(request, env) {
return Response.json({ hello: "world" });
},
};

wrangler.jsonc describes the function: its name, where its code is, which resources (databases, stores, objects) it can reach and when to wake it. The format is JSON with comments allowed — hence .jsonc. A full example:

{
"name": "demo-fn",
"main": "dist/index.js",
"compatibility_date": "2026-01-01",
"durable_objects": { "bindings": [{ "name": "COUNTER", "class_name": "Counter" }] },
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Counter"] }],
"d1_databases": [{ "binding": "DB", "database_name": "app-db", "database_id": "00000000-0000-0000-0000-000000000001" }],
"kv_namespaces": [{ "binding": "CACHE", "id": "cache" }],
"triggers": { "crons": ["*/5 * * * *"] },
"vars": { "GREETING": "from-config" }
}

Field by field:

  • name — the function name; main — the file exporting fetch and scheduled. If package.json declares a build script, it runs on deploy and main points at the built file (in the example, dist/index.js).
  • compatibility_date — the runtime behavior version the code is built against. Set any recent date and leave it alone.
  • durable_objects — Durable Object classes; migrations — the versions of their SQLite schemas. More below.
  • d1_databases — D1 databases: binding is the variable name in code (env.DB), database_name is the name for the CLI commands, database_id is a unique database identifier.
  • kv_namespaces — KV namespaces: binding is the variable name (env.CACHE), id is the name for the CLI commands.
  • triggers.crons — the cron schedule; it invokes scheduled.
  • vars — values available in code as env.<name>; dashboard variables go on top.

A binding is the bridge between config and code: whatever you declare in wrangler.jsonc, the function receives in env as a variable. No connection strings, no addresses — just a name.

A Durable Object is an object with its own state that lives in a single instance at any moment and keeps its data in its own SQLite database. You address it by name: all requests with the same name reach the same instance, so the state never spreads across nodes or disappears on a restart.

It fits anything that needs one source of truth: a counter, a shopping cart, a chat room, a lock, a poll. If you just need “put — get” without state, use KV; if you need tables and SQL, use D1.

In wrangler.jsonc an object is declared with two entries: the class and the schema version.

{
"durable_objects": { "bindings": [{ "name": "COUNTER", "class_name": "Counter" }] },
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Counter"] }]
}

new_sqlite_classes lists the classes whose SQLite schema just appeared: add a new class here, and bump tag whenever the schema changes.

The object itself is a plain class with three methods:

export class Counter {
constructor(state, env) {
this.state = state;
this.env = env;
}
async fetch(request) {
const n = ((await this.state.storage.get("n")) ?? 0) + 1;
await this.state.storage.put("n", n);
return Response.json({ n });
}
async alarm() {
// Fires from state.storage.setAlarm(moment).
await this.env.CACHE.put("alarm:last", new Date().toISOString());
}
}
  • state.storage — the object’s storage: get/put/delete/list, plus its own SQLite through state.storage.sql.
  • alarm() — called at the moment set by state.storage.setAlarm(<timestamp>). It is the way to schedule work “in N minutes” with no external timers.

To call the object, get its handle by name and send it a request:

export default {
async fetch(request, env) {
const url = new URL(request.url);
const id = env.COUNTER.idFromName(url.searchParams.get("name") ?? "default");
return env.COUNTER.get(id).fetch(request);
},
};

idFromName turns a name into the object’s address, get returns a handle, and .fetch(request) forwards the request to the object. The same name always leads to the same object.

cron is a schedule on which the function runs the scheduled handler on its own, with no incoming request. The schedule uses the standard five-field crontab format:

* * * * *
│ │ │ │ └── day of week (0–6, 0 = Sunday)
│ │ │ └──── month (1–12)
│ │ └────── day of month (1–31)
│ └──────── hour (0–23)
└────────── minute (0–59)

In the config it is a list under triggers.crons:

{ "triggers": { "crons": ["*/5 * * * *", "0 3 * * *"] } }

*/5 * * * * — every five minutes, 0 3 * * * — every day at 03:00.

The handler receives an event with the scheduled time:

export default {
async scheduled(event, env) {
await env.CACHE.put("cron:last", event.scheduledTime.toISOString());
console.log(`cron ${event.cron}`);
},
};

Schedules run for a sleeping function too: we wake it on time (see Sleep).

D1 is a serverless SQLite database — the familiar tables, columns, indexes and SQL. From outside it is reached with the CLI: migrations from the migrations/ directory, arbitrary SQL, data imports. In code the database is available as env.<binding>.

await env.DB.prepare("INSERT INTO notes (body) VALUES (?1)").bind("text").run();
const { results } = await env.DB.prepare("SELECT * FROM notes").all();

The full description — migrations, queries, imports and limits — is on the D1 database page.

KV (key-value) is a fast store where a string value sits under a string key. It is ideal for caches, sessions, settings and any other “put — read” data. It is not meant for complex queries or relations between records — use D1 for that.

await env.CACHE.put("greeting", "hello");
const value = await env.CACHE.get("greeting"); // "hello"

The full description — reading and writing from code, bulk imports and key deletion — is on the KV store page.

You need the project directory with wrangler.jsonc or wrangler.json in it; wrangler.toml will not do — convert it to JSON. If there is a package.json, dependencies are installed by the package manager whose lock file we find (npm, pnpm or yarn), and the build script runs if it is declared. Then the project is deployed by the Wrangler config.

Terminal window
webshield apps deploy --project shop --app api

An archive from your computer on the Deployments tab and an https link to a .tar.gz work too (more on the ways to deploy in Apps). The new version starts answering within ten seconds after the deployment turns Live.

Variables. The Variables tab is what the function gets in env on top of vars from the config. They are stored encrypted, so secrets go here as well. References to the project databases work too: DATABASE_URL = ${{db.url}}. Variables are part of a deployment, so after editing them press Redeploy: the function is rebuilt from the same archive with the new values. From the terminal — webshield apps env set … --redeploy.

Rollback. Roll back to this on an earlier deployment switches the code within seconds, the data stays as it is. The earlier version comes back with the variables it had.

Hostnames are attached on the Hostnames tab, the same way as for an app. Inside the function request.url holds your hostname, not our address.

The Log tab shows the output of the function for the last 7 days: console.log and uncaught exceptions of handlers with their stack. On such an exception a visitor gets a 500 response with no details — the error text and the stack are visible only to you.

The data of a function — Durable Objects, D1, KV, queues and alarms — can be returned to any moment of the last 7 days. The code stays as deployed.

Data tab → Return data to a moment, or from the terminal:

Terminal window
webshield apps window --app api # from and to which moment
webshield apps restore --app api --time 2026-10-21T15:00:00+03:00

While the restore runs, the function is stopped and answers 503. The history is kept: if you went to the wrong moment, return the data to the moment before the restore.

The data of one function gets 2 GB. This includes earlier versions of the data for 7 days: returning to a point in time relies on them. The Data tab shows how much is used; at 80% you get an email.

When the space runs out, the function stops answering requests, even those that do not touch the data, and cannot recover on its own. Do not let it get there — remove what you no longer need in advance; the space frees up once the versions of removed data leave the window. If the space is not enough, contact support.

With Always running instances = 0 the function sleeps without requests. We track Durable Object alarms and cron ourselves and wake the function on time, so schedules run for a sleeping function too. The first response after sleep comes with a delay; if that matters, set it to 1.

The same as for apps: CPU and memory while the function runs, data at the price of object storage, including the earlier versions for 7 days. A sleeping function pays only for its data.