Skip to content

Bindings

Register storage, Durable Objects and Workers AI inference for your Next.js app.

View as Markdown

A project can have Cloudflare KV namespaces, D1 databases, R2 buckets and SQLite-backed Durable Object namespaces of its own. Create them in the dashboard, and read them from your Next.js app with @stayingupwind/sdk: there is no configuration file, and no credentials go in your code.

Supported SSR frameworks, Hono and native fetch handlers read the same managed KV, R2 and D1 bindings from their Worker environment, without the Next.js SDK setup below. See Hono and fetch handlers.

Add bindings

Private alpha projects can also register a Cloudflare Workflow with a project-relative module path and named WorkflowEntrypoint class. Deploy it before starting instances. See Cloudflare Workflows for authoring, branch isolation and dashboard operations; existing Workflow SDK runs remain separate.

  1. Open Bindings in the project's sidebar.
  2. Enter a Name: the name your app reads it by, such as DB.
  3. Choose its Type: D1 database, KV namespace, R2 bucket, Durable Object namespace, Workers AI or Images transforms.
  4. For a D1 database or an R2 bucket, choose a Location: the region it should be kept in. It applies when the storage is created, and cannot be changed afterwards. The first choice, Default (Western North America), keeps it in Western North America. A KV namespace is read from everywhere and takes none.
  5. For a Durable Object namespace, enter a Module path, such as src/objects/counter.ts, and its Exported class, such as Counter. The path is relative to the project's configured application root directory, not necessarily the repository root. Export the class by name; a default export cannot be registered. Durable Objects have no dashboard Location setting.
  6. Choose Add.

New storage reaches the next deployment in its environment. The deployment being served is not bound to storage added after it was made. To use new storage now, choose Redeploy on the project's Overview.

  • While storage is being created, it is listed as Provisioning, and a deployment that starts in the meantime waits for it.
  • A newly registered Durable Object, AI or Images binding is Awaiting deployment. It becomes Ready after the next successful publication. Registration alone does not run its code or construct any objects.
  • Storage that could not be created is listed as Failed. It is tried again every six hours, and deployments fail until it is created or removed.
  • Storage belongs to its deployment environment. Storage added manually in the dashboard is for production. When automatic default storage is enabled for the project, each new preview environment also gets its own default KV namespace, D1 database and R2 bucket. Their data is separate from production.
  • Durable Objects also work in branch previews: each preview environment has separate namespaces and data, and receives the production binding's current module and class definition on its next deployment. Production data is never copied into a preview.
  • Owners and admins of the team can add and remove storage, and adding it needs an active plan. Every member of the team can see it.

A name:

  • is up to 64 letters, digits and underscores, and starts with a letter or an underscore;
  • is not the name of another binding of the project, or of one of its environment variables;
  • is not one Arkor uses itself: a name that starts with ARKOR_, in any case, NEXT_DEPLOYMENT_ID, NEXT_PRIVATE_RESPONSE_CACHE_TTL or VERCEL_WEB_ANALYTICS_ENDPOINT.

Run D1 SQL

Team owners and admins can open a ready D1 binding from Bindings and run SQL in its SQL console. Choose the environment first: production and each preview have separate databases. You can read data, insert, update and delete rows, and create, alter or drop tables. Results show columns, rows and execution metadata; the console previews the first 100 rows of each statement. Use SQL LIMIT to keep larger reads manageable.

The public API and Remote MCP expose the same operation as executeD1Query. Every call requires bindings:write, including SELECT. List the binding to obtain its current createdAt, then send that value with the SQL:

curl -X POST "https://api.arkor.dev/v1/projects/$PROJECT/environments/production/bindings/DB/d1/query" \
  -H "Authorization: Bearer $ARKOR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"createdAt":"2026-11-09T00:00:00.000Z","sql":"SELECT * FROM users WHERE email = ? LIMIT 100","params":["hello@example.com"]}'

params is an optional array of at most 100 positional string parameters. SQL is limited to 100,000 UTF-8 bytes. Multiple statements separated by semicolons return separate result sets; atomic execution or automatic rollback of the whole script is not guaranteed. Provider responses are limited to 8 MiB. Database contents and SQL are not cached or included in navigation prefetches.

Numeric results use JavaScript number precision. Select large integer identifiers with CAST(id AS TEXT) when their exact decimal value is needed; BLOB results are byte arrays.

Allow at least 45 seconds in an API or MCP client. d1_query_failed reports a SQL failure; d1_query_unknown, a timeout or a lost response can leave the write outcome unknown. Inspect the database before repeating an operation. Cancellation does not undo SQL already accepted, and SQL execution must not be retried automatically.

Images transforms

Native Workers, Hono and supported SSR apps can use an Images transforms binding for runtime image information, resizing, formatting, text and composition. Add a binding named IMAGES, or choose a custom name and declare it in Wrangler:

wrangler.jsonc
{ "images": { "binding": "IMAGES" } }
src/index.ts
export default {
  async fetch(request, env) {
    const input = request.body;
    if (!input) return new Response('Send an image', { status: 400 });
    const result = await env.IMAGES.input(input)
      .transform({ width: 800 })
      .output({ format: 'image/webp' });
    return result.response();
  },
};

fetch's env, Hono's c.env and env imported from cloudflare:workers expose the same API, including top-level captures. .input(), .text(), .transform() and .draw() chain synchronously. Await .info() or .output(); the result's .response(), .image() and .contentType() stay synchronous. Images are limited to 20 MiB per decoded input. The binding does not expose .hosted, image storage, account management, Cloudflare build-time transforms or /cdn-cgi/image routing.

Astro's unconfigured image service uses local build-time compilation and managed runtime Images when automatic default bindings are enabled. With defaults disabled, register IMAGES explicitly; a custom name also needs to be selected in the adapter. See Astro image settings. An explicit passthrough or compile setting does not add runtime Images. A host whose Images service has not passed its live availability checks reports that it is unavailable.

Grants and default-binding policy are sealed at deployment start. Branch previews receive their own environment grants. New declarations or removals affect the next deployment; retained deployments keep authorized transforms until retirement, and restoring one uses its original grant. Legacy deployments receive no implicit Images grant. Environment variables, secrets, resources and asset binding names may not collide with an Images name or required Astro alias.

The private service authenticates every operation, including cache hits, against the deployment, team subscription, suspension and spend limit. Its cache separates tenants and deployments and keys on actual input bytes and ordered operations. Successful cache misses use the existing Image transforms meter; information requests and cache hits do not add a transformation. No new pricing tier is introduced. Next.js keeps its existing /_next/image integration.

Read and write from your app

Install the SDK in your app:

terminal
npm install @stayingupwind/sdk

Each kind of storage has a default import: the project's one database, namespace or bucket of that kind.

ImportWhat it is
import db from '@stayingupwind/sdk/db'The project's D1 database, a D1Database
import kv from '@stayingupwind/sdk/kv'The project's KV namespace, a KVNamespace
import blob from '@stayingupwind/sdk/blob'The project's R2 bucket, an R2Bucket
import objects from '@stayingupwind/sdk/durable-object'The environment's one Durable Object namespace, a DurableObjectNamespace

The types are Cloudflare's own, and so are their methods.

Arkor builds your app without its storage, so read storage when a request comes in, not while a page is prerendered: call await connection() from next/server before the first read, in a component inside <Suspense>.

app/posts/page.tsx
import db from '@stayingupwind/sdk/db';
import { connection } from 'next/server';
import { Suspense } from 'react';

async function Posts() {
  await connection();
  const { results } = await db
    .prepare('select id, title from posts order by id desc')
    .all<{ id: number; title: string }>();

  return (
    <ul>
      {results.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}

export default function Page() {
  return (
    <Suspense fallback={<p>Loading posts…</p>}>
      <Posts />
    </Suspense>
  );
}

A Route Handler that answers POST, or a Server Action, runs only when a request comes in:

app/api/greeting/route.ts
import blob from '@stayingupwind/sdk/blob';
import kv from '@stayingupwind/sdk/kv';

export async function POST() {
  await kv.put('greeting', 'hello');
  await blob.put('greeting.txt', 'hello');
  const object = await blob.get('greeting.txt');
  return Response.json({ kv: await kv.get('greeting'), blob: await object?.text() });
}
  • A default import throws when the project has none of its kind, or more than one. With several, name the one you mean: d1('ORDERS'), kv('SESSIONS'), blob('UPLOADS') or durableObject('COUNTERS'), from @stayingupwind/sdk or from the same subpath. Each returns undefined for a name the project has no storage of that kind by.
  • published(), from @stayingupwind/sdk, lists the deployment's storage by name.
  • generateStaticParams, getStaticProps at build time, and anything else that runs while Arkor builds your app cannot read storage.
  • Before a deployment is published, Arkor requests some of its pages to check them. For KV, D1 and R2, those requests use the deployment environment's real storage, so a page that writes when it renders writes during the checks too. Durable Object checks use temporary, isolated namespaces and data. If your page calls an object during a check, it cannot change the production or preview object's data; the temporary namespace's usage is paid by Arkor.

Workers AI

Register an AI binding explicitly; default storage does not add one. It has no location or physical storage to provision. Registration is Awaiting deployment, and becomes Ready after a successful publication. Production and each branch preview have separate binding identities. Existing deployment URLs may call AI while their deployments and binding references are retained and authorized. Removing a binding prevents new deployments from receiving it.

The binding exposes only run(model, inputs) for approved public Workers AI models. Model inputs and outputs retain Cloudflare's types, including supported streaming output. A third argument is rejected in JavaScript as well as TypeScript. AI Gateway, external providers, BYOK, AI Search, private models and LoRA, Batch and WebSocket APIs are unavailable.

Use a POST Route Handler so inference starts only for an actual request:

app/api/inference/route.ts
import { ai } from '@stayingupwind/sdk';

export async function POST(request: Request) {
  const { prompt } = await request.json();
  const inference = ai('INFERENCE');
  if (!inference) return new Response('AI binding is unavailable', { status: 503 });
  const output = await inference.run('@cf/meta/llama-3.1-8b-instruct-fp8-fast', { prompt });
  return Response.json(output);
}

import inference from '@stayingupwind/sdk/ai' resolves the environment's sole AI binding lazily. With several bindings, use ai(name); it returns undefined when that name is absent or has another kind. Durable Object classes can call the same inference service through this.env.INFERENCE; they receive no account management capability.

To return a model's supported stream, pass stream: true in its inputs and return a Response with that stream as its body. The service forwards JSON, binary and streams without buffering the whole response or retrying an inference. If you infer in a Server Component, call await connection() inside Suspense before calling AI; builds and prerendering must not infer.

For local development, declare UPWIND_AI_BINDINGS='["INFERENCE"]'. This declaration alone makes no remote connection. To infer using your own Cloudflare account, set CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN, then run upwind dev --remote-ai. Remote authentication failure leaves local storage available. Builds and CI never enable remote inference automatically. See the Upwind local development documentation.

Workers AI costs $0.011 per 1,000 Neurons, including small fractional quantities. The shared Cloudflare account's free allowance is not repeated for each customer. Only exact, settled measurements are charged; provisional, missing and sampled readings are distinguished on Usage & billing. AI GPU usage is separate from site Active CPU. A team that reaches its spend limit, or whose month on the free plan has used what it includes, cannot start new inference; in-flight inference may finish, and usage beyond the existing invoice cap is paid by Arkor.

AI registration requires a host that supports inference and verified metering. Publication is refused when that capability is unavailable. Ordinary requests, PPR shells and static delivery perform no AI authorization or metering work unless the application calls AI.

Durable Objects

Write your class in the module registered on Bindings. It uses Cloudflare's native storage and RPC APIs; this example stores its counter in SQLite through the key-value storage methods:

src/objects/counter.ts
import { DurableObject } from 'cloudflare:workers';

export class Counter extends DurableObject {
  async increment(): Promise<number> {
    return this.ctx.storage.transaction(async (storage) => {
      const count = ((await storage.get<number>('count')) ?? 0) + 1;
      await storage.put('count', count);
      return count;
    });
  }

  async fetch(): Promise<Response> {
    return Response.json({ count: await this.increment() });
  }
}

Use a type-only class import in your Next.js app, so its Worker-only code stays outside the app's bundle. durableObject<Counter>('COUNTERS') returns the native namespace, with typed RPC methods:

app/api/counter/route.ts
import { durableObject } from '@stayingupwind/sdk';
import type { Counter } from '../../../src/objects/counter';

export async function POST() {
  const counters = durableObject<Counter>('COUNTERS');
  if (counters === undefined) return new Response('Binding unavailable', { status: 503 });
  return Response.json({ count: await counters.getByName('visits').increment() });
}

HTTP works through the same native stub. For example, replace that handler with:

app/api/counter/route.ts
import { durableObject } from '@stayingupwind/sdk';

export async function POST(request: Request) {
  const counters = durableObject('COUNTERS');
  if (counters === undefined) return new Response('Binding unavailable', { status: 503 });
  const id = counters.idFromName('visits');
  return counters.get(id).fetch(request);
}

Your request chooses the object name with getByName() or idFromName(). Registering or preparing the persistent namespace does not invoke an object. The first actual use determines placement near the caller; if you need a region hint, pass it on get() or getByName(), such as counters.getByName('visits', { locationHint: 'apac' }). A hint is not a placement guarantee and does not move an existing object. See Cloudflare's namespace API and data location guide.

The namespace and object IDs stay the same across deployments in an environment. After a successful publication, all deployments in that environment, including older deployment URLs, use its latest published class code. A deployment rollback does not restore old Durable Object code. On Bindings, Edit class… changes the module path or class export for the next deployment, while keeping the namespace and its stored data. Keep new code compatible with data written by earlier code and the methods called by retained app deployments. Each preview environment shares code in this way independently of production and other previews. The same original registration in the same preview generation keeps its data; closing and reopening a preview branch starts a new generation with fresh namespaces and data.

If the team reaches its spend limit or uses up its month on the free plan, or the project or team is suspended, Durable Object calls are paused along with the site. While paused, customer alarm handlers do not run: an alarm that expires during the pause is consumed and skipped. Stored data remains, and its storage can still be metered. Resuming restores the last successfully published class and its environment before calls are accepted again. Alarms that expired during the pause are not replayed.

Local development

next dev and next build give your app no storage: a default import throws there, and d1(), kv(), blob() and durableObject() return undefined. To read storage while you develop, run your app with upwind's upwind dev, as upwind's storage guide shows: add upwind and @stayingupwind/adapter to your dev dependencies, and run upwind dev in place of next dev. It gives your app a D1 database, a KV namespace and an R2 bucket of its own, and keeps their data in .upwind/; add that to .gitignore. Nothing on Arkor reads it.

  • The default D1, KV and R2 storage upwind dev makes has names of its own, not the ones you gave on Arkor, so d1('ORDERS') returns undefined there. The default imports work in both places.
  • Leave adapterPath out of next.config. Arkor builds your app with the Arkor adapter, which it names in NEXT_ADAPTER_PATH, and an adapterPath in next.config would be used instead.

For Durable Objects, pass the same name, module path and class export to the local runner:

terminal
UPWIND_DURABLE_OBJECTS='[{"name":"COUNTERS","module":"src/objects/counter.ts","className":"Counter"}]' npx upwind dev

Run it from the configured application root directory. This gives the app a local native COUNTERS namespace, so the named SDK accessor above works locally too. Its SQLite data is kept in .upwind/ across restarts and source edits. Local namespaces and data are separate from production and previews. The dashboard remains the source of hosted registrations; this JSON configures only the local runner. The same input works with upwind build.

Remove storage

On Bindings, choose Remove… next to it, then Remove.

New deployments in that environment are no longer bound to it. Removing a production Durable Object registration also retires its preview copies on their next deployment. Its data is kept for at least a day, and for as long as a deployment Arkor keeps still uses it; then it is deleted, and cannot be brought back. Storage added later under the same name is new and empty.

Limits

LimitValue
Storage per project environment, all kinds combined10, or 20 counting removed storage being deleted
Storage per team on Pro, removed storage being deleted included20 KV namespaces, 10 D1 databases, 50 R2 buckets, 10 Durable Object namespaces
Storage per team on the free plan, counted the same way4 KV namespaces, 4 D1 databases, 10 R2 buckets, 2 Durable Object namespaces
Storage added per team10 a minute
Length of a name64 characters

Production, preview and removed-but-retained Durable Object namespaces each count toward the team's limit: 10 on Pro, 2 on the free plan. Temporary validation namespaces do not consume your binding slots. An object name such as visits is not another namespace and does not consume another binding slot.

Default storage counts too: a deployment whose environment has no KV namespace, D1 database or R2 bucket is given one of that kind, in production and in each preview alike. On the free plan, that is room for about two projects, each with production and one preview, and a deployment that needs default storage the team has no room for fails. To make room, turn a project's default storage off through the Public API, with an API token that holds Bindings at Read and write. Its next deployments get only the storage you added, and the default storage made already is kept until you remove it:

terminal
curl -X PUT https://api.arkor.dev/v1/projects/$PROJECT_ID/default-bindings \
  -H "authorization: Bearer $ARKOR_TOKEN" \
  -H "content-type: application/json" \
  -d '{ "enabled": false }'

Storage a team holds beyond its plan's allowance, such as from a Pro subscription that has ended, is kept; only new storage is refused.

Not supported

  • Bringing in existing KV namespaces, D1 databases, R2 buckets or Durable Object namespaces, or their data. Storage on Arkor is created new.
  • Using your own Cloudflare account.
  • Bulk importing, exporting or backing up data from the dashboard or the API. D1 supports the SQL console and execution API.
  • Direct public access to managed storage from outside your application. Next.js uses @stayingupwind/sdk; native Workers and supported SSR frameworks use their environment bindings.

Pricing

Storage and Durable Objects use Cloudflare's unit rates for KV, D1 and R2 and SQLite Durable Objects. See the pricing page for pricing and Usage for the storage meters.

Containers

Enable Attach a container when registering or editing a Durable Object class. Choose a Dockerfile and build context inside the implementation owner's source directory, or an existing public image. Select the instance size and maximum number of running instances. A container attachment is deployed with its class definition; it does not start a container during registration.

Arkor uses Cloudflare's default scheduling policy. The configured image and instance size are fixed for the application. Both the native ctx.container API and compatible @cloudflare/containers subclasses can control the lifecycle. Runtime image and instance-size selection specific to the durable_object scheduling policy are not supported.

src/objects/compute.ts
import { DurableObject } from 'cloudflare:workers';

export class Compute extends DurableObject {
  start() {
    const container = this.ctx.container;
    if (container === undefined) throw new Error('No container is configured');
    if (!container.running) container.start();
  }

  async stop() {
    await this.ctx.container?.destroy();
  }
}

Call its native namespace with the existing SDK:

import { durableObject } from '@stayingupwind/sdk';
import type { Compute } from './objects/compute';

const compute = durableObject<Compute>('COMPUTE');
await compute?.getByName('job-123').start();

Starting the process does not mean its port is ready. Before forwarding traffic, check readiness with a deadline as described in the native Container API. The maximum applies to concurrently running instances; named instances keep their Durable Object identity and persistent storage after the container stops. The container filesystem is ephemeral.

The existing Durable Object update rules also apply to its attached image: publication changes all deployments using that environment's namespace. Restoring an app deployment does not restore older class code or an older attached image. Keep class and image changes compatible with retained callers. For release-pinned HTTP containers, use Services.