Prisma Composer

Building an app

This guide covers everything you reach for once Getting started has shown you the shape: giving a service a database (plain or Prisma-ORM-typed), packaging pieces as reusable Modules, the cron/storage/streams modules that ship with the framework, the service input — configuration and secrets as one schema — and making a service reachable from the internet.

How the pieces fit

A Prisma App is a tree of Modules. At the leaves are services — compute(), the units that run your code — and resources — stateful things like rawPostgres(). A parent module wires them together; your code never participates in the wiring, it just receives the results:

compute({
  name: 'auth',                 // the service's name in the app graph
  deps: { db: rawPostgres() },     // what it needs         → read via service.load()
  input: authInput,             // its incoming config   → read via service.input()
  build: node({ module: import.meta.url, entry: '../dist/server.mjs' }),
  expose: { rpc: authContract },// what it offers to other services
});

A service that receives no requests and so never listens on its port, such as a scheduler that only calls out, declares listens: false. prisma dev then reports it running as soon as its process starts, instead of waiting for its port. Every other service must listen on service.port().

Dependencies and input are two deliberately separate channels with two separate accessors. A dependency is a live connection to another node; input is data — plain values and credentials together, declared as one schema (below), where a field typed as the redacting SecretString box can never end up as an ordinary string. Your code contains no configuration process.env reads and no URLs; that is what makes every environment — production, staging, a test — just a different set of injected values.

Contracts

An RPC contract is a service's API written as schemas, and it types both ends of the edge: the producer's handlers and the consumer's client. Define it once, in the package of the service that owns it:

import { contract, rpc } from '@prisma/composer/service-rpc';
import { type } from 'arktype';

export const authContract = contract({
  verify: rpc({ input: type({ token: 'string' }), output: type({ ok: 'boolean' }) }),
});

On the producer, serve() turns the service's expose into a fetch handler. The handler map must cover every method — a missing or wrong-shaped handler doesn't compile. Each handler receives the validated input, the service's own loaded deps as a second argument, and an optional third argument carrying the call's idempotency key (see below — most handlers ignore it):

const handler = serve(service, {
  rpc: {
    verify: async ({ token }) => ({ ok: await check(token) }),
  },
});

On the consumer, declare deps: { auth: rpc(authContract) } and service.load() returns { auth } — call await auth.verify({ token }) like a local function. Inputs and outputs are also validated at runtime, at the boundary, against the same schemas.

For an HTTP server the framework does not generate, use a raw HTTP connection instead. There are no gRPC, WebSocket or streaming contracts yet.

Calls are authenticated for you

You don't do anything for this. There is no key in your code, your contract, or your module — but it's worth two minutes, because one consequence looks like a broken deploy the first time you meet it.

When you deploy, the framework creates an unguessable service key for each dependency you declared, gives it to the consumer's client, and tells the provider to accept it. Every call carries the key, and serve() answers anything else with 401 before your handler runs. So a provider answers only the services your app connected to it — which matters, because a deployed service has a public URL and would otherwise answer the whole internet.

The surprise: curling your own endpoint returns 401. You aren't one of the services connected to it, so it turns you away. That's the feature, not a broken deploy. To exercise a provider by hand, call it through a consumer or run it locally.

Locally and in tests, nothing changes. Only a deploy creates keys, so a service you run in a terminal, a fake, and bootstrapService all accept every call, and there's no key for you to supply.

Calls retry safely for you

You don't do anything for this either. A provider that has scaled to zero has to boot before it answers, and a first call can be dropped mid-connection while it does. The client absorbs that: every call carries an idempotency key, a dropped call is retried with a backoff, and the provider runs one call per key — a retry that arrives after the first already ran gets the first answer back instead of running your handler twice. So await auth.verify(...) just works across a cold start, and it works whether or not the call changes state. You write nothing; the key is on the request and the deduplication is in serve().

The deduplication rides on the key, so a request sent without one — a curl, any hand-rolled request — simply isn't deduplicated: it runs once, which is what you'd expect. The generated client always sends a key, so your service-to-service calls always get it. If a handler needs a stronger guarantee than one instance's memory — surviving a crash mid-call — its optional third argument carries the key to write into its own transaction; most handlers never need it.

Two limits worth knowing:

Raw HTTP connections and reverse proxies

A reverse proxy, a Next.js app or a static file server already speaks HTTP and has no RPC contract. To call one, the provider exposes rawHttpContract and the caller declares rawHttp():

import { appRoot } from '@prisma/composer';
import { rawHttp, rawHttpContract } from '@prisma/composer/http';
import node from '@prisma/composer/node';
import { compute } from '@prisma/composer-prisma-cloud';

const site = compute({
  name: 'site', deps: {}, expose: { http: rawHttpContract },
  build: node({ module: import.meta.url, entry: '../dist/site/server.mjs' }),
});
const docs = compute({
  name: 'docs', deps: {}, expose: { http: rawHttpContract },
  build: node({ module: import.meta.url, entry: '../dist/docs/server.mjs' }),
});
const gateway = compute({
  name: 'gateway', deps: { site: rawHttp(), docs: rawHttp() },
  build: node({ module: import.meta.url, entry: '../dist/gateway/server.mjs' }),
});

export default appRoot('web', ({ provision }) => {
  const siteRef = provision(site);
  const docsRef = provision(docs);
  provision(gateway, { deps: { site: siteRef.http, docs: docsRef.http } });
});

In the gateway, gateway.load() returns { site, docs }. Each has a url, to hand to your proxy library, and fetch(path, init), which resolves path against that url. The client never leaves its provider's origin by itself: fetch rejects a path that resolves to another host, such as //other.example/x or an absolute URL, and it returns a redirect to you instead of following it. Pass redirect: 'follow' in init to follow redirects. The framework fills in the right origin locally and in each deployed environment.

The framework checks only that the provider declared an HTTP port: TypeScript and Load both reject a bare service reference or a port of another kind. Which paths, methods and headers the provider accepts is your code's business. A raw HTTP connection has no service key, retry or idempotency key, and exposing the port adds nothing to the provider's server.

Each dependency appears as a call from the gateway to the upstream in the application topology, including through module boundaries. Passing a URL as input (for example with serviceOrigin()) does not; use it for canonical link origins, and declare a dependency for every service you call.

Databases

There are two ways for a service to get a Postgres, depending on how much you want the framework to do.

rawPostgres() — bring your own client

The dependency delivers connection config — { url } — and nothing else. You build the client you already know (pg, Bun's SQL, an ORM) in your server entry:

import { SQL } from 'bun';

const { db } = service.load();
const sql = new SQL({ url: db.url, max: 1, idleTimeout: 10 });

(Those pool settings are not decorative — Compute scales to zero and idle connections get closed; see Deploying and operating.)

postgres() — a Prisma-ORM-typed database

If you want typed queries and managed migrations, make the database a Prisma ORM one. load() then returns { url, client } and two more members covered below: the raw connection string, plus a client generated from your schema — queries like db.client.orm.public.Product.where({ id }).first() are compile-time checked, no SQL strings, no row mapping. The client is constructed on first access, so a service that brings its own Postgres client reads db.url and still gets contract-checked wiring and deploy-time migrations.

The app lists the ORM's packages in its own package.json, all at the exact version Composer names: @prisma/orm-postgres, which the app imports, and the four packages it is built from, @prisma/orm-framework, @prisma/orm-family-sql, @prisma/orm-target-postgres and @prisma/orm-toolchain, plus pg, @types/pg and temporal-polyfill. The ORM's packages name each other as peer dependencies, so the app's list is where the one installed copy of each comes from; prisma orm init writes these lines. In prisma.config.ts, the contract entry lists the database capabilities it requires; Prisma Postgres runs PostgreSQL 17:

import { defineConfig as orm, postgres17, postgresDriver } from '@prisma/orm-postgres/config';

orm({
  contract: { path: './contract.prisma', requiredCapabilities: [...postgres17, ...postgresDriver] },
});

The workflow, once per schema change (Prisma ORM commands, via the prisma CLI — see the Prisma ORM docs for the details):

  1. Edit contract.prisma — your schema.
  2. prisma contract emit — regenerates contract.json + contract.d.ts from it.
  3. prisma migration plan --name <slug> — authors the migration into migrations/. On a brand-new project this authors the baseline (empty → your schema).
  4. prisma migration ref set <environment> <newest migration directory> for each environment the change should reach, for example prisma migration ref set production 20260711T1921_init. This writes migrations/app/refs/<environment>.json, the ref that environment's deploy migrates to. Commit migrations/ with the change.
  5. Deploy. The deploy migrates the database before the service starts — there's no CREATE TABLE IF NOT EXISTS anywhere in app code. Every service that uses the database waits for its migration: if the migration fails, the new service code does not ship. Old code keeps running against the new schema until the new deployment is live, so a migration must not break the code it replaces.

Every deploy, and every prisma dev converge, runs the ORM's migrate for each ORM database: the equivalent of prisma db migrate --to <targetRef> against the database Composer provisioned, whether or not anything in your repository changed. The ORM works out what is pending; when nothing is, it applies nothing, and the deploy redeploys no service because of it. When it applies something, the deploy prints the ORM's own summary as a line naming the migration step, such as shop.database.migration: Applied 1 migration(s) (2 operation(s)) across 1 contract space(s). The deploy only migrates: it never runs db update, db init or db sign, and it never creates schema from the contract. A fresh database is brought up by replaying the committed migrations from empty.

Under prisma dev, plan a migration for each contract change. A current limitation: a local database moved with prisma db update to a contract no migration ends at is refused on every rebuild with the ORM's MIGRATION.SIGNATURE_NOT_IN_GRAPH, although it is already at the target, until you plan a migration that ends at that contract. This is a Prisma ORM bug.

A deploy moves the database to its ref, not to the code. A ref may trail the contract your code was built against, which the ORM allows on purpose; the deploy migrates to the ref as asked and does not compare the two. Moving the ref is yours, in the pull request that changes the contract (step 4).

A failed migration fails the deploy with the ORM's own error. Composer prints one line naming the database and the command it ran, and the ORM's error under it: its code and summary, its why, one → line per next action, and its docs link. For example:

shop.database: Composer ran prisma db migrate --to production on this database.
  [MIGRATION.POLICY_MISMATCH] The ref's policies differ from the database's
    why: production declares change: migrate; the database has change: migrate, reconcile.
  → Make the ref match the database, or have whoever owns the database apply the ref's policies.

Follow the ORM's advice; Composer writes no advice of its own for a migration failure. The commands it advises repeat --to <targetRef>, so running one as printed acts on the same ref. A database whose ref declares policies the database does not have is refused this way, and so is a new database whose ref declares policies other than the ORM's defaults, on its first deploy. Applying a ref's policies is a decision for whoever administers the database, made by hand; see Deploying and operating. Composer checks three things itself before the ORM runs: that the emitted contract.json your prisma.config.ts names can be read, that it has a storage hash, and that the hash matches the contract the database was declared with.

In your app, the emitted contract is wrapped once, and that one value is referenced by both the resource and every service that queries it:

// src/data.ts
import { dataContract } from '@prisma/composer-prisma-cloud/orm';
import type { Contract } from '../contract.d.ts';
import contractJson from '../contract.json' with { type: 'json' };

export const catalogData = dataContract<Contract>(contractJson);

postgres is both ends of the edge, told apart by its argument. A contract is the dependency end — the service declaring what it queries:

deps: { db: postgres(catalogData) }

A { name, contract, config, targetRef } object is the resource end — the module that owns the database provisions it, naming the prisma.config.ts path (relative to the module file) so the deploy can reload the emitted contract.json and find migrations/, and the ref every deploy migrates the database to:

const db = provision(
  postgres({
    name: 'database',
    contract: catalogData,
    config: './prisma.config.ts',
    targetRef: resolve([environment.name], ([name]) => (name === 'dev' ? '@contract' : name)),
  }),
);

targetRef is required. It takes the name of a ref in migrations/app/refs/, or @contract, the ORM's name for the contract this commit emits. The example above, with environment from the module body and resolve from @prisma/composer, migrates each deployed environment to the ref named after it and prisma dev, whose environment is dev, to the contract you just emitted. Nothing else is accepted: @empty, @db, a contract hash or a migration directory name is refused when the node is declared, or, for a value computed at deploy, when the deploy runs. A Module that provisions its own ORM database targets '@contract'. Its migrations ship inside its package, so the app that uses it cannot commit ref files for it; a Module that copies the app's resolve([environment.name], …) pattern makes the app's first deploy to production fail with the ORM's MIGRATION.UNKNOWN_REF, because the Module's package has no production ref. Your prisma.config.ts names no database: the deploy passes the ORM the database it provisioned.

Because both ends share the contract value, the deploy refuses to wire a service against a database whose schema doesn't match. The migration resource persists only compact contract identity in deploy state; the full emitted contract is reloaded from prisma.config.ts at reconcile time. If that artifact is missing, unreadable, or no longer matches the declared contract, the deploy fails before touching the database. examples/orm-demo is the minimal working version; examples/store/modules/catalog is the full pattern inside a reusable Module.

Client options, such as extension types

load() hands the service a binding with three ways to reach the database. All of them share one connection pool, which retries a database that is still starting and drops idle connections before Prisma Postgres closes them:

The options belong to the code that uses the client, not to the dependency declaration, which only states what the service needs.

If your schema uses a column type from a Prisma ORM extension pack, such as embedding pgvector.Vector(length: 1024)? with @prisma/orm-extension-pgvector listed in prisma.config.ts, the client needs that pack's runtime extension. Install the pack in the app at exactly the version of @prisma/orm-postgres that Composer names, and pass its runtime extension:

import pgvectorRuntime from '@prisma/orm-extension-pgvector/runtime';

const { db } = service.load();
export const orm = db.clientWith({ extensions: [pgvectorRuntime] });

Composer does not look extensions up from the contract. If you use db.client with such a contract, the first access throws Contract requires extension pack(s) 'pgvector', but runtime descriptors do not provide matching component(s). A service that reads only db.url needs no extensions.

The exact version matters. The pack names the ORM's packages (@prisma/orm-framework, @prisma/orm-family-sql and the others) as peer dependencies at its own exact version. With a pack version different from the app's, npm refuses the install, and pnpm, Yarn and Bun warn and install it anyway; the client then rejects or mishandles the runtime extension without a clear error.

Reusable Modules

When a service and its database belong together, package them as a Module: a unit that owns its internals and offers only typed ports. A consumer provisions the Module and wires its exposed contract — it never sees, and can never reach, the database inside.

A Module declares its boundary (what it depends on, what it exposes) in the second argument, wires its internals in the builder function, and returns the exposed interfaces it promised. The builder function receives provision, the boundary's forwarded deps, the module's input (below), and environment, whose name is a value (below):

import { module } from '@prisma/composer';
import { secretString } from '@prisma/composer/arktype';
import { rawPostgres } from '@prisma/composer-prisma-cloud';
import { type } from 'arktype';

export default module(
  'auth',
  { input: type({ signingKey: secretString() }), expose: { rpc: authContract } },
  ({ input, provision }) => {
    const db = provision(rawPostgres({ name: 'database' }));
    const service = provision(authService, {
      id: 'service',
      deps: { db },
      input: { signingKey: input.signingKey },
    });
    return { rpc: service.rpc };
  },
);

The module declares signingKey as a secretString() field of its input and passes it on without learning the platform variable's name. Inside, the field is just another leaf of the service's input binding (below).

The root then treats it like any other node. It declares the platform secret and passes its value in (Platform variables):

const signingKey = provision(variable.secret({ name: 'AUTH_SIGNING_SECRET' }));
const auth = provision(authModule, { input: { signingKey } });
provision(storefrontService, { deps: { auth: auth.rpc } });

A Module can also declare boundary deps — dependencies its parent must supply, wired exactly like a service's. The builder function receives them as deps, ready to forward into a provision() call. (Before Composer 0.36 this field was called inputs; rename it in the builder function's destructuring.) The root module you already have is the outermost Module, built with appRoot(): it has no boundary, and nothing can provision it.

provision(node, opts?) takes:

Two naming rules the platform enforces: provision names must be at least three characters (call a database 'database', not 'db' — the wiring key on the service side can still be db), and ids must be unique within their module.

A module's input

A module declares its configuration as one input schema, as a service does (below), and whoever provisions it binds input:

import { appRoot, module, resolve } from '@prisma/composer';
import { field, secretString } from '@prisma/composer/arktype';
import { variable } from '@prisma/composer-prisma-cloud';
import { type } from 'arktype';

const email = module(
  'email',
  { input: type({ from: 'string', deliveryCredential: secretString(), 'replyTo?': field(type('string')) }) },
  ({ input, environment, provision }) => {
    const sender = resolve([input.from, environment.name], ([from, name]) =>
      name === 'production' ? from : `${name}+${from}`);
    provision(emailService, {
      id: 'service',
      input: { from: sender, replyTo: input.replyTo, deliveryCredential: input.deliveryCredential },
    });
  },
);

export default appRoot('shop', ({ provision }) => {
  const deliveryCredential = provision(variable.secret({ name: 'EMAIL_DELIVERY_CREDENTIAL' }));
  provision(email, { input: { from: 'shop@example.com', deliveryCredential } });
});

prisma deploy --environment staging gives shop.email.service the input { from: 'staging+shop@example.com', deliveryCredential }, where deliveryCredential is the value of the platform secret EMAIL_DELIVERY_CREDENTIAL, which the service reads at boot.

Object Storage

bucket is a raw S3-compatible object-store bucket — a flat key-value store with no higher-level abstractions attached. Import it alongside postgres and use it the same way:

import { bucket, compute } from '@prisma/composer-prisma-cloud';

export default compute({
  name: 'uploads',
  deps: { store: bucket() },           // dependency end: receives credentials
  // ...
});
// module.ts — provision the bucket resource and wire it to the service
const store = provision(bucket({ name: 'uploads' })); // resource end: provisions + keys
provision(uploadsService, { deps: { store } });

Inside the service entry, load() hands back { url, bucket, accessKeyId, secretAccessKey } — the standard S3 config set. Use any S3-compatible client (@aws-sdk/client-s3, minio, Bun's S3 API, …):

import { S3Client } from '@aws-sdk/client-s3';
const { store } = service.load();
const s3 = new S3Client({
  endpoint: store.url,
  bucket: store.bucket,
  credentials: { accessKeyId: store.accessKeyId, secretAccessKey: store.secretAccessKey },
});

A bucket resource uses the same S3 contract kind as the storage module's blob store, so a service declared with deps: { store: s3() } — where s3 is imported from @prisma/composer-prisma-cloud/storage — can also be wired to a bucket resource without any changes to the service declaration.

The building blocks that ship with the framework

These are the Modules you compose instead of building the capability yourself. Each owns its internals and hands you a typed port, so adding one is a couple of lines:

Import What you get Exposes
cron from @prisma/composer-prisma-cloud/cron A scheduler that fires your jobs at your service on an interval nothing
storage from @prisma/composer-prisma-cloud/storage An S3-backed blob store, credentials included store
streams from @prisma/composer-prisma-cloud/streams Durable append-only event streams, backed by a store streams

Cron is the one most apps want first. You supply two things — a schedule and a runner service that exposes the trigger contract — and the module does the rest:

// service.ts — the runner. The schedule is the single source of truth
// for job ids and intervals.
import { defineSchedule, triggerContract } from '@prisma/composer-prisma-cloud/cron';

export const schedule = defineSchedule({ rotateSpecial: '30s' });

export default compute({
  name: 'promotions',
  deps: { catalog: rpc(catalogContract) },
  build: node({ module: import.meta.url, entry: '../dist/server.mjs' }),
  expose: { trigger: triggerContract },
});
// server.ts — map each job id to work. serveSchedule checks the map
// against the schedule, so an unhandled job doesn't compile.
import { serveSchedule } from '@prisma/composer-prisma-cloud/cron';

const handler = serveSchedule(service, schedule, {
  rotateSpecial: (deps) => deps.catalog.rotateSpecial({}),
});
// module.ts — the cron module needs whatever your runner needs, so the
// root wires it like any other edge.
provision(cron({ schedule, runner: promotionsService }), {
  deps: { catalog: catalog.rpc },
});

A runner that declares an input schema (below) takes its binding on cron() itself, with a platform secret's value where the schema expects a secret. It is required exactly when the runner declares a schema, the same rule provision() applies:

const token = provision(variable.secret({ name: 'INGEST_TOKEN' }));
provision(
  cron({ schedule, runner: ingestService, input: { token } }),
  { deps: { catalog: catalog.rpc } },
);

The scheduler is the one service in your app that never sleeps. Compute scales an idle service to zero, and the scheduler receives no requests of its own, so it holds the platform's keep-awake guard for its whole lifetime. One warm instance per app is the cost of the clock; the runner sleeps like any other service and wakes when the scheduler calls it.

examples/storage and examples/streams show the other two, including the streams module's secret binding.

Where new blocks come from

An extension is a package that brings its own Modules, resources, or deploy target — the same mechanism @prisma/composer-prisma-cloud itself uses. The convention is an npm package named prisma-composer-*, which is how you and your agent find one; an extension is installed like any dependency and enters the deploy through the extensions array in the composer section of prisma.config.ts.

The ecosystem is new. Today the three Modules above plus the ones you write are the whole set, so treat prisma-composer-* as the place to look rather than a catalogue that already has what you need.

Service input

Everything a running service receives arrives through one of two channels, and choosing the channel is most of the decision:

The value is… Declare it as Provide it Read it
produced by another node — a database, another service a dependency: deps: { db: rawPostgres() } wire it at provision() service.load()
anything else — a region, a flag, a job list, a credential one field of the service's input schema bind it at provision(): a literal, a root input field, a platform variable node's value, or a value from resolve() service.input()

Dependencies are covered above. This section is the second row.

A service declares its whole incoming configuration — plain values and credentials together — as one Standard Schema (arktype, zod, valibot — anything implementing the interface). The schema gives you the TypeScript type and validates the assembled input at deploy and again at boot, so garbage config is a loud failure, not a runtime surprise. A credential is simply a field typed as the framework's redacting SecretString box:

import { secretString } from '@prisma/composer/arktype';
import { type } from 'arktype';

const schedulerInput = type({
  jobs: type({ jobId: 'string', every: 'string' }).array(),
  'region?': 'string',
  apiKey: secretString(),
});

compute({ name: 'scheduler', input: schedulerInput, /* ... */ });

With Zod, import secretString from @prisma/composer/zod instead: z.object({ apiKey: secretString() }). With another Standard Schema library, accept a value for which isSecretString() or isSecretPointer() from @prisma/composer is true.

These helpers use your app's copy of the schema library, so the app installs it: arktype for @prisma/composer/arktype, which supports ArkType 2, and zod for @prisma/composer/zod, which supports Zod 4. Composer installs neither.

Because the input is a real schema, legality can be conditional — "no stripeSecretKey unless billing is on" is a union, not a framework feature, and service.input() narrows it like any other TypeScript union:

const chatInput = type({ stripeEnabled: 'false', appOrigin: field(type('string')) }).or(
  type({ stripeEnabled: 'true', appOrigin: field(type('string')), stripeSecretKey: secretString() }),
);

const chat = compute({ name: 'chat', input: chatInput, /* ... */ });

Every service also gets a reserved port (default 3000), outside the input schema and read through its own typed accessor — service.port(), a sibling of service.origin() — so Bun.serve({ port: service.port() }) listens where Compute routes, with no process.env in your code. (The framework also exports the resolved port as the PORT environment variable, but that is only for a server it does not write and cannot call — Next.js's standalone server.js, which binds PORT itself.)

Binding the input at provision

The service declares what shapes are legal; the place that provisions it decides where each value comes from. The binding is a plain object mirroring the schema's shape whose leaves are literals, values such as a root input field or a resolve() result (below), or sources such as a platform variable node's value. It is typed from the schema, as a module's binding is. So a binding of the wrong shape or kind fails to compile: a missing or undeclared key, a literal of the wrong type, a source in the wrong kind of field. A refinement the type cannot carry, such as a URL format, is checked by the deploy:

import { appRoot } from '@prisma/composer';
import { variable } from '@prisma/composer-prisma-cloud';

export default appRoot('shop', ({ provision }) => {
  const appOrigin = provision(variable({ name: 'APP_ORIGIN' }));
  const stripeSecretKey = provision(variable.secret({ name: 'STRIPE_SECRET_KEY' }));
  provision(chat, { input: { stripeEnabled: true, appOrigin, stripeSecretKey } });
});

Here chat's schema declares appOrigin as field(type('string')), because a platform variable's value is known only at boot.

Secretness is checked twice. The binding's type refuses a plain literal where the schema expects a SecretString, a platform secret's value where it expects text, and a SecretString box written in the code, so each fails to compile. The deploy checks the binding with the schema too, so where the schema has no type information, or a cast hides the mistake, the deploy fails before anything is created. Neither side can silently misclassify a credential.

A field bound to a value known only at boot is wrapped. A plain platform variable's value, serviceOrigin() and generatedParam({ redacted: false }) exist only at boot, so at deploy the schema sees a pointer to the variable, and only a field wrapped with field(), from @prisma/composer/arktype (or @prisma/composer/zod), accepts it: type({ returnUrl: field(type('string')) }). Binding one to a plain 'string' field fails to compile, in a service's binding as in a module's, and the deploy refuses it where the compiler cannot see the schema's types. A platform secret and a redacted generatedParam() are secrets, so their field is secretString(). In the service a wrapped field reads as its inner type: service.input().returnUrl is a string, because at boot the pointer has been replaced by the variable's text. mockService() takes the input double in the same shape.

An ArkType schema with a SecretString field cannot also transform its input. A morph anywhere in the schema, such as 'string.trim', .pipe() or a wrapped transforming field like field(type('string.integer.parse')), and deleting undeclared keys with '+': 'delete', make ArkType copy the whole input, and a copied SecretString loses its value, so the service could not read the secret at boot. The deploy checks for this and refuses such a schema, naming the secret field. Do the transform in the service code instead. A Zod schema keeps the secret box when it transforms, so it can do both.

Two ways to get a value

A value you supply, rather than write in the code, reaches the app in one of two ways. Pick by who reads it:

Who reads the value Declare it as Where you set it
the deploy, before anything runs a root input field: a field of your root's input schema the config adapters: by default the shell that runs prisma deploy or prisma dev
the service, at boot a platform variable node, provisioned in your root with variable({ name }) or variable.secret({ name }) on the platform, with prisma project env add; under prisma dev, the config or secrets adapters

A value the deploy reads can be listed in resolve() and put in a resource's props. A value the service reads at boot cannot, because the deploy never has it.

Root input fields

A root input field is for a plain value the deploy needs, which differs per environment and is not a credential: a sender address, a hostname, a feature flag. Declare it in your root's input and pass it on by name:

import { appRoot } from '@prisma/composer';
import { type } from 'arktype';

export default appRoot('shop', { input: type({ GREETING: 'string' }) }, ({ input, provision }) => {
  provision(web, { input: { greeting: input.GREETING } });
});

The deploy reads GREETING from the app configuration (Values from outside the code), checks it with the root's schema before anything is created, and writes its value into the service's input document. So set it in the deploying shell for every deploy; in CI, export it per environment. An unset value fails the deploy with the schema's message, unless the root declares the field optional ('GREETING?': 'string'), in which case the key is left out. Declare the field with the type the service needs, such as 'resend' | 'smtp' | 'none', and the root's schema checks it. To change the value, deploy again with the new value. examples/root-input is the minimal working version, including a smoke script that proves the per-environment split.

Platform variables

A platform variable is a variable on the platform that a service reads by name at boot. It comes down to three things: its name, the services that read it, and the place the operator sets its value. You declare it with a node in your app root. The node holds the name, the graph records which services read it, and preflight prints the command that sets its value when it has none.

import { appRoot } from '@prisma/composer';
import { variable } from '@prisma/composer-prisma-cloud';

export default appRoot('shop', ({ provision }) => {
  const from = provision(variable({ name: 'EMAIL_FROM' }));
  const deliveryCredential = provision(variable.secret({ name: 'EMAIL_DELIVERY_CREDENTIAL' }));
  provision(mailer, { input: { from, deliveryCredential } });
});

Here mailer is a service of the app whose input schema declares from: field(type('string')) and deliveryCredential: secretString().

A name is an upper-case letter followed by upper-case letters, digits and underscores, such as STRIPE_SECRET_KEY. Any name starting with COMPOSER_, and DATABASE_URL, DATABASE_URL_POOLED, PORT, PATH and HOME, are reserved. A name has one meaning in an app: two nodes with one name, or a platform variable and a root input field with one name, fail before anything is created, naming the variable and both places. Declare each platform variable once and pass its value to every module that needs it. A node's value bound as a service's whole input also fails: bind it to one field.

A typed platform variable

A variable on the platform holds text. Give variable() a schema to say what the text means:

import { appRoot } from '@prisma/composer';
import { variable } from '@prisma/composer-prisma-cloud';
import { type } from 'arktype';

export default appRoot('shop', ({ provision }) => {
  const smtpPort = provision(variable({ name: 'SMTP_PORT', schema: type('number') }));
  provision(mailer, { input: { smtpPort } }); // mailer declares smtpPort: field(type('number'))
});
$ prisma project env add 'SMTP_PORT=587' --project 'proj_…' --role production
$ prisma deploy --environment production

mailer.input().smtpPort   // 587, a number

schema is a schema from any library that implements Standard JSON Schema; ArkType and Zod both do. variable.secret() takes no schema: a platform secret's value arrives as text in a secret box, and the service's secretString() field takes the box without checking its text.

What a schema library loses on the way. No library code runs on a platform variable's value, because the app's module code is not in the service. Composer asks the library for the plain JSON Schema it emits, and boot checks the text against that. Anything the JSON Schema cannot say does not run:

Put any check or change the JSON Schema cannot hold in the service's own schema, which runs at boot on the decoded value.

A reusable Module takes a secret as a secretString() field of its input and passes it on without ever learning the platform name (above), which is what lets a Module require credentials without dictating your naming.

Absence is the schema's call

A field bound to a platform variable whose value is unset (or empty) resolves to key omitted at boot. The schema decides whether that is allowed: an optional field, a union member, or a validation error. A credential for an off-by-default feature is an ordinary optional SecretString field, not a framework flag. Preflight decides the same way before the deploy: it fails when the schema needs a variable that has no value, and lists the others.

What travels

The deploy validates the resolved binding, applies the schema's defaults, and serializes the result into one document, with each secret as a pointer naming the platform variable that holds the value — never the value itself. The deploy writes the document into the service's artifact, not into an environment variable:

{ "stripeEnabled": true, "stripeSecretKey": { "$platform": { "name": "STRIPE_SECRET_KEY", "secret": true } } }

A typed platform variable's marker also carries its JSON Schema: { "$platform": { "name": "SMTP_PORT", "schema": { "type": "number" } } }. At boot the framework swaps each marker for a redacting box over the named variable, for the variable's text, or for the value a typed variable's schema decodes from its text, or leaves the field out when the variable is unset or empty. It validates against the schema again, and service.input() returns the typed object. When the schema fails and a field was left out, the error ends with the names of the variables that had no value. A marker inside an array cannot be left out, so an unset variable there fails boot, naming it. The document holds no secret values, which is why the deploy report can print it, with each marker shown as $platform NAME, or $platform SMTP_PORT (number) for a typed variable.

Values that differ per environment

The graph is the same in every environment: the same services, the same databases, the same wiring. What may differ is configuration. A module body computes it with resolve(), from the name of the environment being deployed:

import { appRoot, resolve } from '@prisma/composer';

export default appRoot('shop', ({ environment, provision }) => {
  const greeting = resolve([environment.name], ([name]) => `hello from ${name}`);
  const shout = resolve([greeting], ([text]) => text.toUpperCase());
  provision(echoService, { input: { greeting: shout } });
});
prisma deploy                          # echo's greeting input is "HELLO FROM PRODUCTION"
prisma deploy --environment staging    # "HELLO FROM STAGING"
prisma dev                             # "HELLO FROM DEV"

environment.name and the result of resolve() are values: stand-ins for data that is known only once the deploy knows which environment it is deploying. The module body cannot read a value, compare it or branch on it. It can only pass it on: as a dependency of another resolve(), as a leaf of a service's or a module's input binding at any depth, as a service param (a deploy-time value only), as one of a resource() node's props, or as a public URL's url. A field of a module's input is a value too (A module's input). A value cannot be a provision id or a deps entry.

resolve(dependencies, fn) lists the values it depends on, and fn receives their real values as one tuple, in the same order. After every module body has run, the deploy runs each fn once, dependencies first, and puts its result where the value was bound. fn returns plain data: strings, finite numbers, booleans, null, arrays and plain objects. It runs synchronously.

Two rules follow from running fn after the module bodies:

Each of these stops prisma deploy or prisma dev before anything reaches the platform, with a message that names the binding the value sits in, such as input key "greeting" of service "shop.echo":

When a dependency's fn is the one that failed, the message says so: it starts A resolve() function that … depends on. examples/root-input serves a value computed from the environment's name.

Sources in resolve()

A root input field is known at deploy, so resolve() can list it: fn receives the field's value, read from the app configuration. A platform variable's value, generatedParam() and serviceOrigin() are known only at boot: the deploy never holds a platform variable's value, and it creates a generated value or a service's origin after it has run fn. So fn would have nothing to compute with, and resolve() cannot list them. Nor can it list a module's input field wrapped with field() or typed secretString(), because its real value may be one of them. A dependency must be a deploy-time value: environment.name, another resolve() result, a root input field, or a plain field of a module's input. Bind the other sources directly:

import { appRoot, module, resolve } from '@prisma/composer';
import { field, secretString } from '@prisma/composer/arktype';
import { serviceOrigin, variable } from '@prisma/composer-prisma-cloud';
import { type } from 'arktype';

const billing = module(
  'billing',
  { input: type({ greeting: 'string', stripeKey: secretString(), returnUrl: field(type('string')) }) },
  ({ input, provision }) => {
    provision(billingService, {
      id: 'service',
      input: { greeting: input.greeting, stripeKey: input.stripeKey, returnUrl: input.returnUrl },
    });
  },
);

export default appRoot('shop', { input: type({ GREETING: 'string' }) }, ({ input, provision }) => {
  const stripeKey = provision(variable.secret({ name: 'STRIPE_KEY' }));
  provision(billing, {
    input: {
      greeting: resolve([input.GREETING], ([greeting]) => greeting.toUpperCase()),
      stripeKey,
      returnUrl: serviceOrigin('shop.web'),
    },
  });
  // … shop.web
});

GREETING=hi prisma deploy --environment staging gives shop.billing.service the input binding { greeting: 'HI', stripeKey, returnUrl: serviceOrigin('shop.web') }, where stripeKey is the platform secret STRIPE_KEY's value.

Listing a value known only at boot, such as resolve([stripeKey], ([key]) => …), fails to compile, with a type error that says a dependency must be a deploy-time value:

error TS2322: Type 'SecretSource<PlatformVariablePayload> & RuntimeValue<SecretString> & { readonly id: string; }' is not assignable to type '"a resolve() dependency must be a deploy-time value, never a value known only at boot or a field wrapped with field(); to compute with an input field, declare it plain"'.

A second error can follow where the result is used, because TypeScript types the result of a call that fails as Value<unknown>. The compiler cannot see every case: a field typed unknown, a schema without type information and a cast all compile. So the deploy also refuses a dependency whose real value is a value known only at boot, or holds one at any depth, before anything reaches the platform. The message names the field and says what to do instead. For a wrapped field, it says to declare the field plain:

The resolve() function for input key "url" of service "shop.email.service" lists input.from of module "shop.email", whose real value is serviceOrigin('shop.web'), a value known only at boot. A resolve() dependency must be a deploy-time value. To compute with input.from, declare it plain, without field(), and bind it to deploy-time data.

For a secret field, the message says to pass the field on into a binding and read it in the service. For a source listed directly, such as a platform secret's value, it says to bind it directly into the input of the service that reads it.

To use a different secret in each environment, give the secret one name and set a different value for it on each environment, instead of choosing between two names in resolve().

Turning a platform variable's value into text in a module body, such as `${stripeKey}`, fails the deploy, as reading an input field does.

Values from outside the code

// prisma.config.ts
import { defineConfig as composer, dotenv, environmentVariables } from '@prisma/composer/config';
import { nodeBuild } from '@prisma/composer/node/control';
import { prismaCloud, prismaState } from '@prisma/composer-prisma-cloud/control';
import { definePrismaConfig } from 'prisma/config';

export default definePrismaConfig({
  composer: composer({
    entry: './module.ts',
    extensions: [prismaCloud(), nodeBuild()],
    state: prismaState(),
    config: [dotenv(), environmentVariables()],
    secrets: [dotenv(), environmentVariables()],
  }),
});
// module.ts: the root declares its input; the deploy fills it from the app configuration
export default appRoot(
  'shop',
  { input: type({ EMAIL_FROM: 'string', 'SITE_HOSTNAME?': 'string' }) },
  ({ input, environment, provision }) => {
    const stripeKey = provision(variable.secret({ name: 'STRIPE_KEY' }));
    const web = provision(webService, { input: { from: input.EMAIL_FROM, stripeKey } });
    const url = resolve([input.SITE_HOSTNAME, environment.name], ([hostname, name]) =>
      hostname !== undefined ? publicUrl.hostname(hostname) : publicUrl.prismaBuild());
    provision(publicUrl({ id: 'site', url, target: web.http }));
  },
);

A root module declares input like any other module, and the deploy fills it from the config adapters.

Each adapter receives the environment's name and returns values. When two adapters return the same top-level key, the later one in the list wins.

Without config or secrets, both read the process environment. A list you write replaces that default, so list environmentVariables() to keep reading the shell.

dotenv() reads .env, .env.local, .env.<environment> and .env.<environment>.local beside prisma.config.ts, in that order, through dotenv-flow, and a later file wins. It skips .env.local for the environment test, and never reads .env.defaults. An environment name with / is encoded in the file name: the environment feature/x reads .env.feature%2Fx. If prisma.config.ts has import 'dotenv/config', remove it when you list dotenv(): the import puts .env into the shell's values, which environmentVariables() returns last, so .env would override .env.<environment>.

The app configuration fills only the root's input. Under prisma dev it also gives each plain platform variable a service reads its value, under the variable's name.

The secrets adapters give prisma dev its secrets. A deploy reads them only to know which values to redact. The operator sets a platform variable on the platform; the deploy does not copy it from the secrets adapters (Deploying § Platform variables).

A root's input takes no secret, so provision a platform secret node inside the body and bind its value, as stripeKey is above.

Pass the root's input fields on by name, as from: input.EMAIL_FROM is above. No module can pass its whole input on, and for the root it matters most: its whole input is every value the config adapters return, which by default is every variable of the shell, secrets included.

The root's schema checks the app configuration before anything is created, so a missing value fails with the schema's message.

A deploy reads the adapters once, in the command's own process, and runs the deploy engine in that process too. prisma dev reads them at start and again at each rebuild, and runs the deploy engine in a worker thread of its own process, which runs no adapter and receives the values it needs in memory. The destroy operation reads your config adapters once and runs the deploy engine in the process that calls it. No command writes these values to a file. A root field your body passes on must hold data JSON can hold exactly: text, numbers, booleans, null, arrays and plain objects.

A plain value never carries a secret: a deploy never sends one to the platform as plain configuration. Every command fails if a root field your body passes on has the same name as a platform secret in the graph. prisma deploy fails before it creates anything, and prisma dev before it runs the deploy engine, if any root input value contains a secret's value, such as the password in a URL (CONFIG.SECRET_AS_PLAIN_VALUE). prisma dev also fails if a plain platform variable's value contains one. destroy does not make that check: it sends no configuration anywhere and writes none to disk. A secret shorter than eight characters, such as a dev placeholder, counts only when it is the whole value, so it does not refuse dev@example.com. The error names the field and the secret's name, never the value. The fix it gives: pass the value of the platform secret to where the plain value is used, or give the plain value text that does not contain the secret's value.

Composer replaces a secret's value with [redacted] wherever it prints. The secrets it knows are the values under the names of the graph's platform secrets, in either list, including one no service reads. The lists' other values, such as EMAIL_FROM in .env or the shell's SHLVL, are not secrets and print as they are, apart from values that look like credentials. Under prisma deploy, the deploy engine's progress and log lines reach you through Composer and are redacted. Under prisma dev, the engine's own output is not redacted yet; Composer redacts its failure message. Nothing is redacted by the known secrets before Load has named them: an adapter that throws, and a root schema failure that echoes a field's value, are redacted only by the credential-looking rule.

A value in .env or .env.local is read by every environment, including a prisma deploy to production from your machine.

PRISMA_SERVICE_TOKEN and PRISMA_WORKSPACE_ID still come from the shell.

An adapter is any function, so a project can write its own.

Making a service public

A service is reachable from the internet only through a public URL that you declare. A public URL depends on the HTTP interface a service exposes, and exposes nothing itself. Provision it where the hostname is decided, usually in the root module:

// web/src/service.ts
import { rawHttpContract } from '@prisma/composer/http';
import node from '@prisma/composer/node';
import { compute } from '@prisma/composer-prisma-cloud';

export default compute({
  name: 'web', deps: {}, expose: { http: rawHttpContract },
  build: node({ module: import.meta.url, entry: '../dist/server.mjs' }),
});
// module.ts
import { appRoot } from '@prisma/composer';
import { publicUrl } from '@prisma/composer-prisma-cloud';
import webService from './web/src/service.ts';

export default appRoot('shop', ({ provision }) => {
  const web = provision(webService);
  provision(publicUrl({ id: 'site', url: 'shop.com', target: web.http }));
});

publicUrl() takes three parameters:

url takes one of two strategies:

One public URL serves one hostname. To serve shop.com and www.shop.com, provision two public URLs wired to the same interface. Two public URLs in one app may not name the same hostname: the deploy and prisma dev stop before changing anything, naming both public URLs.

publicUrl() checks a hostname as soon as it runs. It trims the hostname, drops one trailing dot and lowercases it. It throws, naming the public URL and the problem, for a scheme such as https://, a path, a port, a * label, an IP address, fewer than two labels, a label that is not 1 to 63 characters of a-z, 0-9 and - or that starts or ends with -, or a hostname longer than 253 characters:

publicUrl("site"): "https://shop.com" has a scheme. Pass the hostname alone, without "https://".

A hostname per environment

The hostname usually differs per environment, so url is usually a value. fn returns either strategy, or a bare string:

import { appRoot, resolve } from '@prisma/composer';
import { publicUrl } from '@prisma/composer-prisma-cloud';

export default appRoot('shop', ({ environment, provision }) => {
  const web = provision(webService);
  const url = resolve([environment.name], ([name]) =>
    name === 'production' ? 'shop.com' : publicUrl.prismaBuild());
  provision(publicUrl({ id: 'site', url, target: web.http }));
});

Production serves at shop.com, and every other environment at its service's prisma.build hostname. The graph is the same in every environment; only the resolved url differs. A value is checked once it resolves, so a fn that returns anything else stops prisma deploy and prisma dev before any of the app's resources are created or changed:

shop.site: url resolved to 42, which is not a hostname or a public URL strategy.

Before you name a hostname

The deploy attaches a named hostname to the service straight away, and the platform refuses it unless two DNS records are already published:

If either is missing, the deploy fails with the platform's error, such as domain-ownership-required for a missing TXT record. Publish the records, then deploy again. Until a hostname can be declared before its DNS is ready, use publicUrl.prismaBuild() for every environment whose DNS is not set up.

Until the next Composer release, a named hostname works only in the production environment, the one on the project's default branch. Use publicUrl.prismaBuild() in every other environment.

Changing a hostname that is serving to one whose records are not published fails the deploy too, and the old hostname keeps serving. The deploy creates the new custom domain before it removes the old one, and stops when the platform refuses the new one.

To move a hostname to another service, remove its public URL and deploy, then add it on the new service and deploy again. The hostname does not serve between the two deploys.

Under prisma dev

prisma dev serves every service on its local URL. It ignores a named hostname, and prints one warning per public URL that names one:

shop.site names the hostname shop.com. prisma dev ignores it and serves the service on its local URL.

This holds whatever name --environment gives: the local target ignores hostnames in every environment.

A service with no public URL

A service with no public URL is meant to be reached only by other services in the app. Today the platform still gives every service a prisma.build hostname, so such a service is reachable there. When the platform makes that hostname opt-in, your code does not change.

examples/root-input makes its service public at its prisma.build hostname.

Builds

The framework never bundles your code — it assembles what your build produced, byte for byte. Two build adapters ship:

node — any plain server process. Point entry at the file your build produced. By default deploy copies exactly that and never ships node_modules, so the build must inline everything except runtime built-ins (bun, bun:*, node:*), which the deploy VM provides. Any bundler that produces such a file works. With bun:

bun build src/server.ts --target=bun --outfile dist/server.mjs

Building two services from one package? Two separate builds, one per entry, so shared code lands in both.

If your build emits a directory instead — a server plus the client bundle, CSS and images it serves at runtime, as Bun's HTML import produces — name the directory with dir and the file that boots inside it with entry:

build: node({ module: import.meta.url, dir: '../dist/server', entry: 'server.js' })

dir resolves relative to your service module, like entry does; entry then resolves inside dir, and may be nested (server/start.js). Deploy copies the whole tree verbatim and boots the file you named, so the server finds its siblings exactly where the build left them — resolve them against import.meta.url, not the working directory.

Nothing is guessed: you name the directory and the entry, and that is what ships. Two things to know:

Packages your build leaves external. Both forms take dependencies, which says what your build did with installed packages, in the words bundlers use (esbuild's and Rollup's external, Vite's ssr.external):

// The build leaves packages external, so stage them from node_modules.
build: node({ module: import.meta.url, dir: '../dist', entry: 'server/entry.mjs', dependencies: 'external' })

The trace reads every file the entry reaches, so on a large build it can take minutes. Use 'external' only when the build needs it.

If dependencies is wrong and a package is missing, the service fails to start with the runtime's own error. If it fails with Cannot find package 'x', bundle x into the build or set dependencies: 'external'.

Framework server builds. These leave packages external by default, so set dependencies: 'external' on their node() build:

Through v0.28, the directory form always traced. A directory build that relied on that now needs dependencies: 'external', or it fails at boot with a missing-package error.

nextjs — a Next.js app. next build with output: 'standalone' is the whole build; the adapter just needs to know where the app lives:

build: nextjs({ module: import.meta.url, appDir: '..' })

Add nextjsBuild() from @prisma/composer/nextjs/control to the deploy config's extensions. And remember: any page or action that calls service.load() needs export const dynamic = 'force-dynamic'.

Digging deeper

The design record explains why the model is shaped this way: