---
title: tenants
description: Create, deploy, configure, copy and delete the tenants of an environment from a luna's handler.
related:
  - /platforms/manage-tenants-from-code
  - /platforms/add-tenants
  - /platforms/call-across-tenants
---

`tenants` returns a client for the tenants added to an environment. A platform's lunas use it to give each customer a tenant and deploy the customer's code to it.

```ts luna/lunas/customer.ts
import { defineLuna, t, tenants } from "luna";

export const Customer = defineLuna({
  name: "Customer",
  key: { id: t.string() },
  handlers: (h) => ({
    open: h({ args: { name: t.string() } }, async (ctx, { name }) => {
      const platform = tenants({ token: ctx.env.PLATFORM_TOKEN, parent: ctx.tenant });
      const made = await platform.create(name, { labels: { plan: "free" } });
      return made.tenant;
    }),
  }),
});
```

## Reference

### tenants(options)

| Prop | Type | Default | Description |
| - | - | - | - |
| `token` | `string` | - | An API token with the scopes each method needs. |
| `parent` | `string` | - | The full name of the environment's default tenant, which the tenants belong to. |

Call it inside a handler. It reaches Luna from there with no network. In a luna of the default tenant, `ctx.tenant` holds the name `parent` needs. `luna tenants list --json` shows it as the `tenant` of the `default` row.

### TenantsClient

Methods take a tenant's short name, the one you passed to `create`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `create(name, options?)` | `Promise<{ tenant: string; publishableKey: string; apiToken: string }>` | - | Adds a tenant, with `options.labels` to find it by, and returns its full name and its two main credentials. |
| `list(options?)` | `Promise<{ tenants: { name: string; version: number; labels?: Record<string, string> }[]; cursor: string \| null }>` | - | The environment's tenants in order of name, only those with every label in `options.labels`, `options.limit` at a time, after the `options.after` cursor. |
| `get(name)` | `Promise<unknown>` | - | The tenant: its version, settings, the limits that hold for it, its usage counters and its luna types. |
| `deploy(name, code)` | `Promise<TenantDeployResult>` | - | Builds source files and deploys them to the tenant. |
| `configure(name, settings)` | `Promise<void>` | - | Changes the settings in `settings` and keeps the rest. |
| `fork(name, to, options?)` | `Promise<{ copied: number; skipped: number }>` | - | Copies every luna of a tenant into another, as they are now or at `options.at`. |
| `delete(name)` | `Promise<{ deleted: boolean }>` | - | Deletes the tenant with its lunas, data, versions, keys and secrets. |

Each scope the token needs:

| Method | Scope |
| --- | --- |
| `create`, `deploy`, `configure`, `delete` | `tenants:write` |
| `list`, `get` | None: any token that reaches the environment |
| `fork` | `data:read` on the source and `data:write` on the destination |

### deploy code

| Prop | Type | Default | Description |
| - | - | - | - |
| `files` | `Record<string, string>` | - | Each file's relative path, split by `/`, and its contents as UTF-8 text. |
| `entry?` | `string` | - | The entry module's path, and when left out, Luna reads the config file or looks for a default entry module. |
| `confirm?` | `boolean` | `false` | Deploys even though the preview lists changes that need your say-so. |

### TenantDeployResult

| Prop | Type | Default | Description |
| - | - | - | - |
| `deployed` | `boolean` | - | Whether the files were deployed. |
| `version?` | `number` | - | The version the tenant now runs. |
| `preview` | `unknown` | - | What the deploy changes, or what blocked it. |
| `publishableKey?` | `string` | - | The tenant's main publishable key. |
| `apiToken?` | `string` | - | The tenant's main secret token. |

### configure settings

The type of `settings` is `TenantLimits`, which the package exports.

| Prop | Type | Default | Description |
| - | - | - | - |
| `quotas.requestsPerSecond?` | `number` | - | The most requests a second. |
| `quotas.cpuPercent?` | `number` | - | The most CPU the tenant can use, as a percent of one core. |
| `quotas.storageBytes?` | `number` | - | The most storage, in bytes. |
| `quotas.sandboxes?` | `number` | - | The most sandboxes running at once. |
| `quotas.lunaMemoryMib?` | `number` | - | The most memory one luna can declare or use, in MiB. |
| `quotas.lunaCpu?` | `number` | - | The most cores one luna can declare or use. |
| `quotas.lunaDefaultMemoryMib?` | `number` | - | The memory a luna has when it declares none, in MiB. |
| `quotas.lunaDefaultCpu?` | `number` | - | The cores a luna has when it declares none. |
| `hostnames?` | `string[]` | - | Extra routes to the tenant, each as `host` or `host/first-path-segment`. |
| `grants?` | `Record<string, { luna: string }>` | - | The platform's luna types the tenant's code may call, each under the service name its code uses. |
| `outbound?` | `{ luna: string; key: unknown; handler: string } \| null` | - | A handler of the platform's that sees each request the tenant sends out and may refuse it. |
| `retentionDays?` | `number` | - | Days the tenant's logs and traces are kept. |
| `historyDays?` | `number` | - | Days back its lunas can be restored or forked, at most what the plan keeps. |
| `otlp?` | `{ endpoint: string; headers?: Record<string, string> } \| null` | - | A separate export of the tenant's telemetry. |
| `labels?` | `Record<string, string>` | - | Tags for finding and grouping tenants. |

The `outbound` handler receives `{ tenant, method, url, host, port }` and answers `{ allow: boolean }`. Any other answer, or none within 5 seconds, refuses the request.

### fork options

| Prop | Type | Default | Description |
| - | - | - | - |
| `at?` | `number` | - | The moment to copy the lunas as of, in milliseconds since the epoch, and now when left out. |
| `schedules?` | `boolean` | `false` | Whether each copy keeps its source's schedules. |

## Good to know

- A tenant's name is lower-case letters, digits and single dashes. With its parent's name it fits in 60 characters, and no tenant is named `default`.
- A tenant has its own lunas, data, keys and secrets. It runs nothing until you deploy to it.
- The files of one `deploy` are at most 48 MiB, paths included. Luna builds them inside the tenant's own isolation.
- A refused deploy returns `deployed: false` with its `preview`. It does not throw.
- Any other failure throws an `Error` with the message Luna answered.
- `list` returns full names, and includes the environment's default tenant.
- `fork` copies one page of lunas per request and goes on until all are copied. A destination with nothing deployed gets the source's code and settings first.
- `delete` returns `deleted: false` while the delete carries on in the background.
- `configure` keeps every setting you leave out. A setting you pass is replaced whole, so `quotas` replaces every quota.

:::warning
`delete` cannot be undone.
:::

## Examples

### Deploy a customer's code

```ts luna/lunas/customer.ts
ship: h({ args: { name: t.string(), code: t.string() } }, async (ctx, { name, code }) => {
  const platform = tenants({ token: ctx.env.PLATFORM_TOKEN, parent: ctx.tenant });
  const result = await platform.deploy(name, { files: { "lunas.ts": code }, entry: "lunas.ts" });
  if (!result.deployed) return { refused: result.preview };
  return { version: result.version };
}),
```

### Set a tenant's limits and routes

```ts luna/lunas/customer.ts
limit: h({ args: { name: t.string() } }, async (ctx, { name }) => {
  const platform = tenants({ token: ctx.env.PLATFORM_TOKEN, parent: ctx.tenant });
  await platform.configure(name, {
    quotas: { requestsPerSecond: 50, sandboxes: 2 },
    hostnames: [`${name}.example.com`],
    grants: { billing: { luna: "Billing" } },
  });
}),
```

### List tenants by label

```ts luna/lunas/customer.ts
free: h({}, async (ctx) => {
  const platform = tenants({ token: ctx.env.PLATFORM_TOKEN, parent: ctx.tenant });
  let page = await platform.list({ labels: { plan: "free" }, limit: 100 });
  const names = page.tenants.map((x) => x.name);
  while (page.cursor) {
    page = await platform.list({ labels: { plan: "free" }, limit: 100, after: page.cursor });
    names.push(...page.tenants.map((x) => x.name));
  }
  return names;
}),
```

### Copy a tenant as it was an hour ago

```ts luna/lunas/customer.ts
copy: h({ args: { from: t.string(), to: t.string() } }, async (ctx, { from, to }) => {
  const platform = tenants({ token: ctx.env.PLATFORM_TOKEN, parent: ctx.tenant });
  return platform.fork(from, to, { at: ctx.now() - 3_600_000 });
}),
```

Keep the token as a secret named `PLATFORM_TOKEN`, set with [luna secrets](/cli/secrets). See [Automate with API tokens](/platforms/automate-with-api-tokens).
