Organizations
Build a SaaS on Foir. An organization is a tenant of your product, living inside one of your projects, so your users’ data is separated by the same row-level engine that separates your workspace from every other Foir user’s, and not by code you have to write and keep right.
That is the whole claim, and the reason it is unusual is worth stating before anything else:
Your application never says which organization a request belongs to. It cannot, so it cannot say it wrongly.
Where an organization sits
workspace
└─ project
├─ the project-shared rows
└─ organization
├─ its own rows
└─ organization
├─ its own rows
└─ ...and so on, as deep as your data goesA project is one product: a store, a site, an app. An organization is one of that product’s own tenants: one pop-up shop, one client, one brand. The workspace and the project are the levels a Foir user manages; organizations are the levels their users live in.
An organization can contain another organization, to any depth. Give one a parent and it sits inside that parent’s subtree: a reseller with its own clients, a franchise with its shops, a region with the brands under it. Depth lives in your data rather than in a setting, so a project may use no organizations at all, one flat row of them, or a tree twelve deep, and nothing is declared or migrated to go deeper. An organization created without a parent is a root of the project.
There is nothing to switch on. A project with no organizations behaves exactly as a project did before organizations existed, and the rows it already holds stay project-shared for good: an organization owns the data written while standing in it.
Three placements are refused, in the database rather than in an application: an organization inside itself, an organization inside one of its own descendants, and an organization inside a parent belonging to a different project. Deleting an organization deletes everything below it, so a subtree is never left behind with its parent gone.
The exact rules for reading down a tree, inheriting definitions down it, moving an organization and deleting or suspending a subtree are on Organization Trees.
What takes the level
Two kinds of thing carry an organization, and they travel in opposite directions.
Content takes the level and is read down the tree. Records, files, users, notes and notifications, and everything derived from them: the field index, record relationships, natural-key lookups, geometry, embeddings, note attachments, mentions, approvals, notification preferences, device tokens and resource grants. Events and their deliveries, operation runs and dead letters, hooks, schedules and publish batches take it too. That list is longer than it first looks for a reason the platform states plainly: a reader who cannot see a record but can see its indexed field values, its embedding, its geometry, its natural key, its edges or its grants has not been contained. Embeddings and geometry are the sharpest of those, because a similarity or bounding-box query reads content without ever naming a record.
An organization reads its own content, the content of every organization beneath it, and the project-shared tier. It writes only its own, and in the project-shared tier only the organization-owned records it owns.
Definitions take the level and are inherited down the tree. Models, operations, locales, context dimensions, user sign-in providers, design tokens, notification categories and variant catalog entries can each be defined at the project or at any organization. An organization reads the project’s definitions, those of every organization above it, and its own; where the same key is defined at more than one of those levels, the deepest one wins for its callers. A reseller defines a model once and every client beneath it receives it, and a client’s own model never appears in its reseller’s schema.
Some things stay with the project as a whole. The project’s configurations, applying a configuration bundle, the project’s own settings and publishing the project schema are refused to a caller standing in an organization. A key confined to an organization manages no keys, and there is no organization-level sending address (below).
The organization registry itself (the organizations, their members and their limits) is not partitioned the way content is. An organization’s own row is its identity rather than something inside it, so a caller holding organizations:read at the project reads every organization of the project. A key confined to an organization reads and manages the registry rows of that organization and the organizations beneath it, and nothing else, and a user reads the organizations their memberships reach.
How the boundary is enforced
Three mechanisms, none of which live in your application.
Stamped on the way in. org_id is written by a BEFORE INSERT trigger in the database that reads the caller’s own claim and fills the column when the row does not already carry one. Not a handler, and not a column default: a default is skipped the moment a statement names the column, so an insert passing org_id => NULL would silently lose the stamp.
Confined on the way out. Every policy on an organization-scoped table carries the same terms, compiled from the authorization spec rather than written by hand. Reading content admits a row when this holds:
((org_id IS NULL OR org_id = (current_setting('request.jwt.claims', true)::json ->> 'org_id') OR (current_setting('request.jwt.claims', true)::json ->> 'org_reach') = 'project') OR org_id IN (SELECT auth.organization_closure_reach_set((current_setting('request.jwt.claims', true)::json ->> 'org_id'))))auth.organization_closure_reach_set returns the claimed organization and every organization beneath it. Reading a definition uses the same term with auth.organization_closure_inherit_set instead, which returns the claimed organization and every organization above it. Changing or deleting a row, content or definition, admits only the caller’s own level:
org_id IS NOT DISTINCT FROM (current_setting('request.jwt.claims', true)::json ->> 'org_id')Records, and the lookups, index rows, edges and points derived from them, are the one exception, because one kind of record sits in the project-shared tier on purpose and still belongs to an organization: an organization-owned record. Their update and delete policies admit the shared tier as well, and a second, restrictive policy on the same command takes it back to the caller’s level, with the owner as the only way in:
auth.record_write_level_admits(org_id, owner_kind, owner_id, (current_setting('request.jwt.claims', true)::json ->> 'org_id'))It admits a row whose org_id is not distinct from the claim, or a project-shared row whose owner is the organization the caller stands in (owner_kind is 'organization' and owner_id is the claim). A derived row asks the same of the record it belongs to.
All three are copied from the generated authorization migration rather than retyped.
Pinned once written. A caller standing in an organization may not change org_id at all. The attempt raises org_id is pinned: moving a row between organizations is a project-level act. That holds for an ancestor too: an organization reads its descendants’ rows, cannot update or delete them, and cannot move a row into or out of any organization. Without the pin, the read term above is satisfied on both sides of an UPDATE that moves a project-shared row into the caller’s own organization, which would let one tenant quietly take a row the project shares. Assigning a row to an organization stays a project-level act.
What a credential with no organization reads
This is the one result that surprises people, and it is worth being exact about because the intuitive reading is wrong.
A caller carrying no organization claim reads the project-shared rows only: the rows whose org_id is NULL. It does not read every organization’s rows.
The read term has four ways to admit a row, and with no claim three of them fail. org_id = NULL evaluates to NULL, which is never true. org_reach is absent, so comparing it with 'project' is never true either. And the subtree of no organization is empty, so org_id IN (...) admits nothing. The whole term collapses to org_id IS NULL: the absent claim narrows to the shared tier rather than opening to all of it.
The consequence is real and you should design for it: your own back office, holding your project key, cannot see your tenants’ rows from that credential. The answer is to stand in one organization at a time, or to ask for X-Org-Reach: project on a read, not to widen the term.
The two populations
This is the part worth reading twice, because it is where tenancy models usually get tangled.
The shop owner is your user. The buyer is the shop owner’s user.
Dave runs a pop-up shop on your platform. Dave is your user: he signed up, he pays you, and he acts for his shop. Someone who buys a coffee from Dave is Dave’s user, and has nothing to do with you.
Both are users in Foir. What separates them is the pool each signs in to, and where each stands:
| Pool | Who they are | Where they stand | |
|---|---|---|---|
| Shop owner | the project’s | your user | a membership of each organization they act for |
| Buyer | the organization’s own, or the project’s | the shop owner’s user | a membership of the organization they buy from |
There is no third identity to learn. Everyone is a user of one pool, and where they may act is a membership holding their roles there. That is what lets one person run two pop-ups from one sign-in rather than holding two accounts.
An organization that signs its own people in
An organization made the ordinary way shares the pool above it: the nearest organization over it that has its own, or the project’s. One that signs its own people in, apart from its parent’s and the project’s, has a pool of its own, and the organizations inside it share that pool unless one of them starts another, at any depth. A sibling keeps its own.
The pool can be chosen when the organization is made, or started later and dropped again:
| Where | Chosen when made | Started later | Dropped | Read |
|---|---|---|---|---|
| Console | Its own people, on the new organization form | Start its own pool, under Who signs in here on the organization’s page | Drop its own pool, in the same place | the same place |
| CLI | foir orgs create --name Acme --own-pool | foir orgs pool start <id> [--move-people] [--dry-run] | foir orgs pool drop <id> | foir orgs pool show <id> |
| Platform API | CreateOrganization with own_pool: true | StartOrganizationPool with move_people, dry_run | DropOrganizationPool | GetOrganizationPool |
| Data API | provisionOrganization(input: { provisionId, name, ownPool: true }) | startOrganizationPool(movePeople, dryRun) | dropOrganizationPool | organizationPool |
| SDK, in an operation | organizations.provision({ provisionId, name, ownPool: true }) | organizations.startPool({ movePeople, dryRun }) | organizations.dropPool() | organizations.pool() |
| Agent | foir_manage_organization with create and own_pool | foir_manage_organization_pool with start, move_people, dry_run | foir_manage_organization_pool with drop | foir_get_organization |
On the data API and in an operation an organization is never an argument: the three act on the organization the request stands in, named by X-Org-Id, or the one the run acts in. Starting and dropping take organizations:write, and reading takes organizations:read, held by a role, an admin key or an operation that declares it. A publishable or server key holds neither. Reading says which pool serves the organization and where it comes from: its own, with how many people it holds; an organization’s above it, named; or the project’s. ownPool on an organization says which have their own.
Starting one where people already stand takes them along, when asked. Without move_people, starting a pool for an organization that already exists is refused while anybody of the pool it signs in to now holds a membership in it or anywhere beneath it, or an invitation there is open to that pool, and the refusal says how many. With it, the organization and every organization beneath it that shares its pool move into the new pool, and so do their people:
- Somebody who stands only there moves whole. Their addresses, passwords, passkeys and other ways of signing in, second factors and sessions go with them, and they sign in as before.
- Somebody who also stands elsewhere, at the project or at an organization that does not move, keeps their user where they are. The organization is given a new user for them in its pool, made as a staffer makes somebody: their name, their first address not yet proved, and no way of signing in until they prove the address there. Their memberships and roles there go to that new user, with the records, files, notifications and choices of what they are told that they own there, the notes assigned to them there and the access they were given to single resources there. What they did there before stays their own user’s: who made and wrote what, the trail and the runs. Nothing is merged by address, and no password or way of signing in is copied across pools.
- The new user is told as anybody made for them is. The new pool keeps the settings of the one its people came from, so where that pool emails the people made for them, each new user is sent a link to set up their account.
- An address is held once. The start is refused while somebody who moves holds the first address of somebody who is given a new user, and the refusal says how many.
- Invitations and requests. An invitation open there goes to the new pool. A request to join from somebody the organization no longer signs in is withdrawn.
Run it with dry_run first: it does all of it, undoes it, and answers what it would move by kind, or the refusal the start would meet. Starting a pool for an organization that has one answers the pool it has and moves nobody.
Dropping a pool deletes nobody. It is refused while the pool holds anybody, or while an invitation is open to it, and the refusal says how many. An account its holder deleted keeps only its id, so it is nobody here, and it goes with the pool as it goes when an organization is purged. Once the pool is dropped, the organization and everything beneath it sign in to the pool above it, and the pool’s own settings go with it.
Its apps follow. An app bound to an organization signs in the people of the pool that serves it. When that changes, because a pool was started or dropped or the organization moved, the apps beneath it sign in to the new pool, and anybody signed in through them who is not in it is signed out; somebody who moved into it with their organization stays signed in. No key is revoked.
A move keeps everybody where they sign in. Moving an organization with no pool of its own can change the pool it signs in to. That move is refused while anybody of the pool it signs in to now stands in it or beneath it, and so is one that would leave somebody in a pool their place is no longer served by. An organization with its own pool keeps it wherever it goes, and so do its people. A move’s answer says whether its pool changed.
An address belongs to one user per pool. alice@example.com in Acme’s own pool and in the project’s pool is two users, each with their own password, sessions and recovery, and neither can find the other. In one pool it is one user, who may stand in several of its organizations; each organization’s permissions, its records and what it keeps private stay its own.
A project can make its new organizations keep their own users. Turn on New organizations get their own sign-in in the project’s settings, or set organizationOwnPool: true in foir.config.ts, and every new top-level organization starts a pool of its own unless whoever creates it says otherwise. One made inside another shares its parent’s unless asked otherwise.
Who an organization’s users are
Organizations that share a pool share its people. You choose what signing up at one of them means:
- Joined, the default. Somebody who signs up at an organization becomes that organization’s user, and becomes another’s when they sign in there or are added to it. This suits separate businesses on one sign-in: a booking platform’s salons each see the clients who booked with them, and none can email a client who never visited.
- Everyone. Somebody who signs up at an organization becomes a user of the project, and so of every organization that shares its sign-in. Any of them can find, email and sign them in. This suits branches of one business: a gym chain’s members use any club, and any club can look them up.
Either way, a user of the project is a user of every organization that shares the project’s pool. They are found, emailed and signed in at any of them, and act there with what the project gives them. An organization with a pool of its own reaches only the project’s users who are members of it, and its own people.
The project sets the default and each organization can choose for itself. An organization that chooses nothing takes the nearest organization above it that chose, then the project. For an organization with a pool of its own, everyone means that organization’s whole pool, the organizations inside it included. Somebody invited to an organization, or made its first member, is a member of it either way, and changing the choice moves nobody: it applies to people who sign up from then on.
| Where | The project’s default | One organization’s own choice |
|---|---|---|
| Console | Organization users, in the project’s settings | Organization users, in the organization’s settings, and on the new organization form |
| CLI | organizationUsers: 'everyone' in foir.config.ts, then foir push | foir orgs create --name Acme --users everyone, foir orgs update <id> --users joined |
| Platform API | UpdateProject with organization_users | CreateOrganization or UpdateOrganization with users |
| Data API | provisionOrganization(input: { provisionId, name, users: "everyone" }) | |
| SDK, in an operation | organizations.provision({ provisionId, name, users: 'everyone' }) | |
| Agent | foir_manage_organization with users |
Reading an organization says what it chose, if anything, and what applies to it.
Who may join an organization
Somebody who can already sign in at an organization’s page, because they are of the pool it uses, is not its member until something makes them one. You choose what signing in there does for them:
- By invitation only, the default. They are turned away with the answer an unknown address gets. Only an invitation, or its staff adding them, makes them a member.
- Open. Signing in there makes them a member. This suits a community or a club anyone on your sign-in may use.
- By request. Signing in there asks to join. They see that their request was sent, its staff approve or decline it, and they are emailed the outcome. A declined person may ask again.
Joining only ever adds a membership. It never connects a sign-in method, and nobody from another organization’s sign-in can join this way: at an organization with a pool of its own, only its own people can.
An organization can name the role joining gives, its joining role. Somebody who joins an open organization holds it, and so does somebody whose request is approved without a role being named. Naming one is staffing the organization, so only somebody who could give that role there can name it. With none, they join with no role of their own.
| Where | The project’s default | One organization’s own choice | The requests |
|---|---|---|---|
| Console | Joining without an invitation, in the project’s settings | The same, in the organization’s settings and on the new organization form, with Role for people who join | Access → Join requests |
| CLI | organizationJoining: 'request' in foir.config.ts, then foir push | foir orgs create --name Acme --joining open, foir orgs update <id> --joining request --joining-role <roleId> | foir orgs requests list [id], foir orgs requests approve <requestId> [--role <roleId>], foir orgs requests decline <requestId> |
| Platform API | UpdateProject with organization_joining | CreateOrganization or UpdateOrganization with joining, and joining_role_id on UpdateOrganization | ListJoinRequests, ApproveJoinRequest, DeclineJoinRequest |
| Data API | provisionOrganization(input: { provisionId, name, joining: "request" }), and updateOrganization(input: { name, joining, joiningRoleId }) for the organization the request stands in | joinRequests, approveJoinRequest(id, roleId), declineJoinRequest(id), for the organization the request stands in | |
| SDK, in an operation | organizations.provision({ provisionId, name, joining: 'request' }) | ||
| Agent | foir_manage_organization with joining and joining_role_id | foir_list_join_requests, foir_manage_join_request |
Requests are read with members:read and settled with members:write, at the organization or across the project. Each step sends a hook event that stands at the organization and names the person: JOIN_REQUESTED, JOIN_REQUEST_APPROVED (with ORGANIZATION_MEMBER_ADDED) and JOIN_REQUEST_DECLINED.
How an organization’s people sign in
An organization can narrow how its people sign in, and can require a second factor:
- Only some sign-in methods. It accepts only the methods it names, of those its project allows: a password, an emailed code, a passkey, or a sign-in provider. Its sign-in page offers only those.
- A second factor. Every session acting there must have proven one.
- Locking an account after wrong passwords, for an organization with a sign-in of its own. Ten wrong passwords in an hour always block the IP they came from; with this on, they also lock the address everywhere for an hour. It follows the project until the organization chooses. An organization that shares a sign-in follows whoever keeps it, and is refused a choice of its own. See wrong passwords.
People sign in to the sign-in the organizations share, not to one organization, so the rules are asked of the session on every request that stands at the organization, not only at its sign-in page. A request whose session the rules turn away is answered STEP_UP_REQUIRED, with extensions.stepUp saying how: second_factor (prove a second factor on the hosted step-up page in extensions.stepUpUrl, and retry) or sign_in_method (sign in again with a method it accepts). The same person’s same session goes on acting at the project and at organizations without the rule. An organization beneath another is held to every rule above it too, so it can narrow further and never widen. A request made for a person by an operation, with no session of theirs, is not asked.
import { stepUpRequired } from '@foir/sdk/data';
try {
await foir.order.list();
} catch (error) {
const asked = stepUpRequired(error);
if (asked?.kind === 'second_factor' && asked.url) {
const page = new URL(asked.url);
page.searchParams.set('return_to', window.location.href);
window.location.assign(page.toString());
} else if (asked?.kind === 'sign_in_method') signInAgain();
else throw error;
}| Where | |
|---|---|
| Console | Only some sign-in methods, Require a second factor and, with a sign-in of its own, Lock accounts after failed sign-ins, in the organization’s settings |
| CLI | foir orgs update <id> --sign-in-methods passkey,provider:google --require-second-factor --lock-accounts on |
| Platform API | UpdateOrganization with sign_in_methods, requires_second_factor and locks_accounts_after_failed_sign_ins |
| Data API | updateOrganization(input) with signInMethods, requiresSecondFactor and locksAccountsAfterFailedSignIns (on, off, or inherit to follow the project) |
| Agent | foir_manage_organization with sign_in_methods, requires_second_factor and locks_accounts_after_failed_sign_ins |
Where a person may go
A signed-in person can list the organizations they can enter, in their own sign-in, the way an organization switcher offers them:
- those they are a member of;
- those invited them, with the invitation waiting;
- those they may join by signing in there: an organization that is open or takes requests, or whose verified domain takes an address of theirs;
- those they asked to join, with the request waiting.
The list is theirs alone and asks nothing of any organization’s staff. An organization that lets them in no way is never named, so a person learns nothing of organizations they have no way into. One that may not act now, suspended or due to be deleted, is listed as unavailable rather than left out. Somebody who stands at the project stands at every organization sharing its sign-in, which the list says once (projectMember) instead of naming each.
| Where | |
|---|---|
| Data API | myOrganizationChoices { organizations { orgId name relation available joining byAddress invitationId requestId } projectMember } with the user’s bearer |
| SDK | myOrganizationChoices(env, { bearerToken }) |
| Platform API | ListMyOrganizations |
An app of the whole project signs in its organizations’ people. An app bound to no organization signs in anybody of the project’s sign-in who is a member of the project or of any of its organizations. People of an organization with its own sign-in never reach it: they sign in there.
The login page can ask where they are going. Turn on Ask which organization on such an app (prompts_for_organization, promptsForOrganization in foir.config.ts), as a SaaS console would, so a shop owner of two pop-ups picks one. Then a sign-in through it that names no organization asks somebody who may enter more than one place which of them they are going to: the project, where they stand at it, each organization they are a member of, and each that takes anybody of its sign-in who signs in there, which choosing joins. Somebody whose one place is an organization goes straight there. The app is told where in the ID token of the sign-in (org_id); a refresh’s names none, and neither does any access or refresh token, so each request names where it stands with X-Org-Id and a move or a revoked membership is never stale in a token. Leave it off for an app whose people act across organizations at once, such as a buyer’s bookings at every shop: nobody is then asked, and the app offers its own switcher from the list above. A sign-in that names an organization, or an app bound to one, is never asked, and neither is a sign-in that asks for no page (prompt=none).
Joining by email domain
An organization can take people by the domain of their address. It proves it controls a domain by publishing a DNS TXT record, and then says what a verified address there gets:
- Joins the organization, with its joining role.
- Asks to join, a request its staff approve or decline as above.
Somebody of the organization’s sign-in with a verified address at the domain joins, or asks, when they sign in at any page of that sign-in (the project’s included), sign up, or prove the address, for example by accepting an invitation or resetting their password. Only a verified address counts: one a sign-in provider asserts counts only where Foir already trusts that provider to prove it. Nobody from another organization’s sign-in joins this way.
A domain is held by one organization of a sign-in at a time, so an address there says which of them its holder belongs to; an organization with its own sign-in may hold the same domain as one sharing the project’s. A common mail provider’s domain (gmail.com and the like) or a disposable one can never be verified, because anybody may hold an address there. A project’s own verified domain vouches for addresses and no more.
| Where | |
|---|---|
| Console | Access → Sign-in → Domains: add a domain, check its record, remove it, and choose what an address there gets |
| CLI | foir domains add example.com, foir domains check <id>, foir domains joining <id> open, foir domains list, foir domains remove <id>, standing at the organization with --org-id |
| Platform API | AddVerifiedDomain, CheckVerifiedDomain, SetVerifiedDomainJoining, ListVerifiedDomains, RemoveVerifiedDomain |
| Data API | verifiedDomains, addVerifiedDomain(domain), checkVerifiedDomain(id), setVerifiedDomainJoining(id, joining), removeVerifiedDomain(id), for the organization the request stands in |
| Agent | foir_list_verified_domains, foir_manage_verified_domain |
Domains are read with signinproviders:read and changed with signinproviders:write, as an organization’s sign-in providers are; saying what an address gets is also charged orgsettings:write, because it says who may join the organization.
An organization run by its own people
The people who run an organization change its own settings through your app, without the console: its name and how it is presented, who may join it and the role joining gives, its sign-in rules, and the domains its people’s addresses are at. This is how WorkOS and Clerk let an organization’s own people run it.
Give them a role at the organization that holds what they run:
| They change | Permission |
|---|---|
| Its name, presentation, joining, sign-in methods, second-factor rule and, with a sign-in of its own, account locking | orgsettings:write |
| The role somebody who joins is given | orgsettings:write and members:write, a role the project lets organizations give |
| Its verified domains | signinproviders:read and signinproviders:write |
| What an address at a verified domain gets | signinproviders:write and orgsettings:write |
A role given at an organization reaches it and the organizations beneath it, never a sibling or the organization above it, and the app’s key must hold the permission too. On the data API the organization is the one the request stands in: updateOrganization(input), verifiedDomains and the domain writes above take no organization argument. The project’s own people keep all of it from above: project:manage holds orgsettings:write, and a role, key or token that held organizations:write before the two were told apart was given both.
What an organization may change about itself stays narrower than what its project may. Where its people stand (users), and the mail sent for it and where the links in it point (from_name, reply_to, support_email, app_base_url), are the project’s: a change to any of them is also charged organizations:write, which no organization may be given. In a shared sign-in, an organization able to point its password-reset links at its own site could take the account of anybody in it. Its parent, its pool, its limits, suspending it and deleting it stay the project’s too.
The Foir console stays what it is: a surface for your own staff. Your tenants’ users sign in to your application, not to Foir.
Which shape is yours
Foir gives you three, and picking the wrong one is expensive later.
One project with organizations: a SaaS, or one company with several brands. Your tenants inherit your models and can define their own beneath them, and their content is separated. This is the page you are reading.
A project each for clients who share nothing: their own verified sending address, their own Foir console login, or nothing in common with the rest at all. Nothing is shared between projects, which is the point.
One plain project: a single product with no tenants of its own. Most projects.
The first two compose. An agency can run a project per client where each client is itself split into organizations.
A worked example
Dave signs up, gets a shop, and writes a product. The thing to watch is what your application never does.
1. Dave signs up. He signs up through your app, on your project’s publishable key, which carries no organization, so his account is a user of the project.
2. Create his shop.
foir orgs create --name "Dave's Coffee"That prints the organization’s id, which is how everything else names it. An organization is identified by a server-minted id, exactly as a project and a tenant are; names are not unique, so keep the id.
Give it an address and a page on that address finds it: its app base URL, which may be a path of your app (saasapp.com/daves) or a subdomain (daves.saasapp.com), or a domain it brings. See finding the organization from the page address.
3. Let him act for it.
foir orgs members add org_d72zr40bcbei7ddgwwc96zft h7b2wi9k3m8qz1v0c4xe6tnaHe stays a user of the project. The membership is what says he acts for this shop, and he can hold several.
4. Mint the credential his traffic runs on. A key confined to his organization, holding no more than the key that mints it. From your server that is CreateApiKey with an orgId and at least one grant; from the terminal it is:
foir api-keys create --name "Dave's Coffee storefront" --kind publishable --grants records:read,records:write --confine-to-org org_d72zr40bcbei7ddgwwc96zft5. Write a product with it.
await foir.product.create({ input: { title: 'Flat White' } });That call names no organization. It does not need one: the insert is stamped in the database from the credential’s own claim, and a read from outside Dave’s shop and the organizations above it will not return it. If you searched your application for the line that decides which shop this belongs to, you would not find one. The only decision your code makes is which credential to pick up, once, at the edge.
The same is true in the other direction. A buyer signing up through that credential is stamped into Dave’s organization by the same trigger, and every session they hold afterwards resolves the organization from their own row.
Which credential to hold where
Three credentials exist in a product built on organizations, and holding the wrong one in the wrong place is the mistake worth designing out.
| Credential | Carries an organization? | Where it lives | Reaches |
|---|---|---|---|
| Project key (an admin key) | no, or one it names per request with X-Org-Id | your back office or back-office tooling, never your app | the project-shared tier, plus the organization registry: back office, management. When it names an organization, that organization and everything beneath it |
| Organization-scoped key | yes | one per organization: a publishable key in that organization’s storefront, or an admin key in an integration that serves only that organization | its organization and everything beneath it, plus the project-shared tier |
| Foir console session | one at a time | your staff’s browser | the organization the console’s address names and everything beneath it, or the shared tier when it names none |
The registry has its own permissions. Making an organization is organizations:create. Moving, suspending and deleting the ones there are is organizations:write, renaming one and changing its own settings is orgsettings:write, and reading them, their members and their limits back is organizations:read. Mint the key your back office runs on with those and nothing else: it reaches none of your project’s content, settings, locales or publishing. Signup needs no admin key: a person founds their own organization with their own bearer, as self-service sign-up describes, or one operation of yours signs them up, as sign-up as one operation describes. On a key confined to an organization, the same pair reaches only that organization and the organizations beneath it, so a new organization it creates must name one of them as its parent.
The middle row is what makes an anonymous storefront safe: a credential confined to Dave’s organization cannot be steered anywhere else, whatever the request says. The alternative, rendering that page on your project key and filtering by an organization your code picked, puts the boundary back in your application, which is the thing you adopted this to avoid.
One app on many addresses finds the organization from the page. When one storefront serves every organization from its own addresses (saasapp.com/daves, daves.saasapp.com, or a domain Dave brought), the page it is rendering already says which organization it is for. Send the page URL as X-Org-Url with the publishable key the page ships, and Foir binds the request to the organization whose address it is on. No admin key reads your organizations’ settings to find out, and nothing in your code decides the tenant.
Four rules hold that credential in shape, all enforced at the platform rather than by convention:
- It must name at least one scope. An empty scope set is the widest authority, not the narrowest, so the mint refuses it.
- Its scopes are clamped to a subset of the key that minted it. Authority only ever narrows.
- It cannot mint credentials. Not another organization’s, and not one for its own organization or anything beneath it either: a child credential would outlive its parent’s revocation. It may not hold
apikeys:readorapikeys:writeeither, because neither grants it anything. - It dies with its organization. Deleting the organization deletes the key rather than orphaning it, because a confined key whose confinement was removed would silently become a project key.
An admin key made for a workspace itself spans projects, so it cannot be confined to an organization at all, and says so rather than accepting the request and ignoring it. An organization lives inside one project.
Per-organization limits
Set a ceiling on one tenant without touching the others. Five metrics take an organization cap: records, media_storage, active_users, emails_per_month and ai_credits. An ai_credits cap is set in credits, and AI work standing in the organization is refused before it runs once the cap is reached.
A metric is cappable here only when it can be counted per organization and a gate exists that can refuse on the result. Both halves matter: a cap on something nothing counts resolves against zero, never refuses, and would be advertised, configurable and silently absent.
Caps are set from the CLI (foir orgs limits) or over the SetOrganizationLimit RPC. A cap narrows whatever stood above it (your project’s limit when one is configured, otherwise your plan’s) so an organization can never be given more than its project holds, even when the project itself has been cut below the plan. No row means no organization-level check, not a limit of zero.
An organization can manage its own clients’ caps, and nothing else. Standing in an organization, a caller holding organizations:write sets, clears and lists the caps of the organizations beneath it, which is the whole point of a reseller running its own clients. Not its own cap, because a cap the capped party can write is not a cap. Not an ancestor’s, which is the same escape one level up. Not a sibling’s, which is nothing to do with it. A non-descendant answers exactly as an organization that does not exist, so the surface cannot be used to find out which organizations there are. A caller standing in no organization keeps the full view.
A cap binds everything nested under it, and is measured on the same set. Set one on a reseller and every client underneath counts towards it. Otherwise adding a sub-organization would be the route around any cap above it, and a limit somebody escapes by creating a row below it is not a limit. That also means an organization holding nothing itself still reaches its cap, because its subtree does.
You hear about it before it refuses. Every organization with a cap gets a notice at 80% of it and again when it is reached, naming the organization and the number. That mattered enough to build separately: the limit chain is narrow-only, so an organization cap is the first thing a caller meets, and until it had its own warning, the layer that actually stops people was the only one that never said anything, while the workspace-wide alert stayed quiet because the workspace was nowhere near its plan. The figure quoted is the limit that actually binds, which is the project’s or the plan’s if either is narrower than the organization’s own cap.
An organization’s members can see how close it is to its caps. foir orgs limits usage [id], the organization’s Limits tab and the platform’s GetOrganizationCapUsage show, for each metric, what the organization and everything beneath it have used and the cap closest to its limit, with the organization that set it. A cap set higher up counts its owner’s whole subtree, siblings included, so this is the figure a write it refuses is told. It answers only for the organization the caller stands in and those beneath it. Any other answers as an organization that does not exist.
foir orgs usage reports per-organization figures across the project, including a (project-shared) row so the numbers add up to the total. It is for whoever manages the whole project: a caller standing in an organization is refused, because a list of every organization’s counts would tell them which organizations there are.
Each row counts only the organization it names, never its descendants, so the rows sum to the project’s totals and nobody is counted once per level of ancestry. A subtree figure is therefore something you add up yourself, over the tree as it stands, which means moving an organization moves its usage with it, immediately, with nothing having been consumed. Nothing stored is rewritten by a move: there is no per-organization usage archive for a move to restate, and each organization’s own figures are always the count for the organization named. It is worth knowing before a subtree total changes and nobody can say why.
Suspending, deleting and getting the data back
An organization is in exactly one of three states: active, suspended, or pending_deletion.
Suspending is not deleting, and they are separate actions on purpose. Everywhere else a tenancy boundary is also a container, so “cancel” gets wired to the only lever there is. Here they are different columns on one row.
foir orgs update <id> --from-name "Dave's Coffee" --reply-to hello@daves.coffee # the sender on mail sent for this org
foir orgs suspend <id> # every row stays, here and beneath it
foir orgs resume <id> # and it is backSuspending an organization removes nothing, and reversing it restores nothing, because nothing went.
A suspension covers everything nested under it, and writes to none of it. An organization’s effective status is the strictest one on its path up to the root, so suspending a reseller stops its clients too, without a single row of theirs being touched. Resume the reseller and they all come back as they were. That is why the suspension is not written down the tree: if it were, un-suspending a parent would leave children suspended by rows nobody chose to write. An organization inside one that is still suspended cannot be made active on its own, and the refusal names the organization above it.
Deleting is a deliberate, separate act with a 30-day window.
foir orgs delete <id> # schedules it; nothing is removed yet
foir orgs resume <id> # cancels it, right up to the last momentScheduling a deletion records a decision and a date. Nothing is removed until the window closes, and cancelling is possible up to the moment the purge takes its lock. Thirty days is long enough for a monthly billing cycle to turn over, which is when a wrongly deleted tenant is most likely to be noticed.
A deletion is scheduled on every organization it covers, by name. Deleting an organization destroys everything nested under it, so the schedule says so: each one gets the status and the same deadline, appears on its own, and is destroyed in its own right, children before their parents, rather than vanishing when somebody else’s clock runs out. The alternative, one row scheduled and the rest removed as a side effect, gives you no window in which cancelling that organization specifically was possible, and nothing naming it while there still was one.
Scheduling a deletion is its own permission. It takes organizations:delete. Suspending, resuming and cancelling a scheduled deletion take organizations:write, so whoever may close an organization need not be able to bring one back, and the other way round. A key or a role that held organizations:write before the two were told apart was given both.
An organization does not delete itself. A key confined to an organization and a member’s own session are refused every change of status, the deletion included. If the people who run an organization should be able to close it, write an operation that does it for them: see letting an organization close itself.
Cancelling reaches the same set, and puts each one back where it was rather than setting them all active. An organization that was suspended in its own right before the deletion was scheduled is suspended again afterwards: cancelling a deletion is not a decision about it, and an undo that hands out more access than existed before is not an undo.
Getting one tenant’s data back is a property of the level, not a feature bolted onto it. An export runs every read under the caller’s own claims, so an export taken while standing in an organization contains that organization’s rows and the project-shared tier, and no other organization’s rows. No export query carries an organization filter, and none should — the same policy that confines every other read confines this one.
Presentation
An organization can look like its own product without being its own project. Seven fields can be set per organization: display name, logo, primary colour, sender name, reply-to, support address and app base URL.
Every one is nullable and NULL means inherit. Presentation inherits down the tree, one field at a time. For each field:
- the organization’s own value wins;
- otherwise the nearest organization above it that sets that field;
- otherwise the project’s value;
- otherwise the default.
A reseller brands its whole client base once, and a client overrides only the fields it chooses. An organization that sets nothing, in a tree that sets nothing, presents exactly as the project does. A value that is only whitespace counts as unset.
Two fields have no default of their own. When no level sets them, neither an organization on the path nor the project, the sender name is the display name in force and the support address is the reply-to in force. So a client that sets only a display name sends mail under that name, while a sender name set explicitly at any level, the project’s included, still wins over it.
The same resolution is used everywhere the brand appears: the hosted sign-in page, every email sent for the organization, and the invitation link, which is built on the app base URL in force. Changing a field on an organization changes it for every organization below that leaves the field empty, from their next request, and moving an organization changes what it inherits the same way. In the console, each empty field says where its value comes from: an organization above it, named when you can read it, or the project, and the two derived fields say which field they follow when no level sets them.
Each field is tri-state on the way in: omit it to leave the stored value alone, pass a value to set it, pass an empty string to clear it back to inheriting. Without that third state an override could be changed but never removed.
Changing them takes orgsettings:write. The sender name, reply-to, support address and app base URL also take organizations:write, so an organization’s own people set its display name, logo and colour and the project sets where its mail comes from and where its links go (An organization run by its own people).
An organization’s id is not one of these. It is minted when the organization is created and it never changes, because it is what every row, credential and binding in the project references.
One thing Foir will not do
Stated here rather than discovered in a support reply.
An organization does not get its own sending address. The presentation fields above are real and they cover most of what “our own brand” means in practice, including its own domain, which binds to the organization the way a project’s does. One thing they do not cover:
- The address email is sent from. A custom sending address is only permitted alongside a verified sending key, because an address whose ownership cannot be proven is an address that burns the shared sender’s reputation for everyone on it. Restating that invariant one level down, against a key that lives two levels up, is the dangerous half of the feature, so
from_emailis deliberately absent at the organization level. Sender name and reply-to do resolve per organization; the envelope sender does not.
If each of your tenants needs their own verified sending address, that is the line: give each one its own project instead. A project carries its own sending key, and that is what a verified address requires.
From your own application
Your users need a way to say which of their shops they are in. List the organizations they may stand in with myOrganizations on @foir/sdk/auth, then make the client for the one they choose:
import { myOrganizations } from '@foir/sdk/auth';
const shops = await myOrganizations(env, undefined, { bearerToken });
const foir = createFoirClient({
apiUrl,
apiKey,
generated,
bearerToken: () => getUserToken(session),
orgId: shops[0].id,
});myOrganizations answers from the calling user’s own memberships, and everything beneath them, active ones only. Someone with no memberships sees an empty list rather than an error, a sibling’s branch is invisible however wide their own is, and a request naming an organization they cannot reach is answered “not found” whether or not it exists. Nothing your app sends widens it. A user whose role holds organizations:read in the project can stand in every organization of it, so they are listed every one, suspended ones included, as the console lists them. To read past the first page, pass the last entry’s cursor as after.
A membership reaches downward. Someone who is a member of an organization may stand in every organization beneath it without a row of their own there, so a reseller is offered its own organization and each of its clients. The reverse never works: a membership at a branch reaches no ancestor and no sibling, and the list is exactly the set a request may name, so it discloses nothing a request would not.
Each entry carries its position: parentId (null at the top), ancestorIds (the whole path, root first) and depth. Draw the list flat and a reseller’s clients render as its siblings, which is the one shape a tenant picker must not have. The path is ids rather than names: an id is disclosed to everything below it, a name is row content a user further down may not be entitled to, so an ancestor they cannot read appears as an id in the path and nowhere in the list.
Each entry also carries the caller’s own role there, role: { id, key, name, grants }, or null when the membership carries none or no membership of theirs reaches it. grants is what the role gives, in the permission catalogue’s names. It is the role on the caller’s membership in that organization when they hold one, and otherwise the role on the membership above it that reaches it. What a member may actually do is resolved by the platform on every request from the roles on every membership that reaches the organization, the one in it and any above it, together with the user’s own roles in the project, so someone who is a member of a reseller and of one of its clients holds both roles’ permissions in the client. Read role to decide what to show: hide the takings screen from door staff before the tap, rather than letting the platform’s refusal be the first they hear of it. It is never another member’s role, so it hands out nothing the platform would not already apply to that person’s next request.
Nothing is stored. The client names the organization on every request, and the platform checks on every request that the person may stand there, so a membership taken away stops answering on the next call. A client made with no orgId reads the project-shared tier.
Everything after that names no organization of its own:
const orders = await foir.order.findMany(); // Dave's orders. No filter, no argument.No read or write in the SDK takes an orgId argument. That absence is the feature. An organization your code passes per call is one it can forget, get wrong, or be tricked into passing, and then the boundary lives in your application again. The one place code names an organization is the client, once, from the project credential: createFoirClient({ …, orgId }) sends X-Org-Id on every request, for the side of the product that has to decide which tenant it is acting for. A confined credential cannot be steered by it.
Self-service sign-up
Everything above has your staff creating the organization and adding the founder by hand. For a product where strangers sign themselves up, turn on self-service in the project settings and name the role a founder gets:
// foir.config.ts
project: {
id: 'prj_...', // the pin: settings are pushed to the project it names
tenantId: 'ten_...',
settings: {
organizationSignupEnabled: true,
organizationSignupRole: 'shopkeeper', // a user role of this project
},
},foir push applies both. Then one call, from your signup flow, once the person has proved their email:
import { registerOrganization } from '@foir/sdk/auth';
const shop = await registerOrganization(env, { name: "Dave's Coffee" }, { bearerToken });
// shop.role.key === 'shopkeeper'The platform creates the organization and the caller’s own membership in it, carrying the role you named, in one transaction. The caller decides the name, and may say where the organization lives. The id is minted server-side the way a project’s and a tenant’s are, the founder is read from the caller’s own bearer token so nobody can register an organization in someone else’s name, and the role is the project’s so nobody picks their own grant.
Their users can do it too, one level down. Pass parentId and the new organization is founded under one the caller already operates (a reseller adding a client, a franchise adding a branch) with no manager in the loop:
const branch = await registerOrganization(
env,
{ name: 'Leeds', parentId: shop.id },
{ bearerToken },
);The parent is resolved against the caller’s own memberships, not merely against the project: on this lane “an organization that exists” is not the question, “one you operate” is, and anything else answers as not-found, which is also what stops the argument being used to find out what a project has. Omit it and the organization is founded at the top of the tree.
Give it its address as it is founded. An app that finds the organization from the page it is on (X-Org-Url) needs the new one to have an address before its founder lands there. Pass appBaseUrl and it has one from the first request:
const shop = await registerOrganization(
env,
{ name: "Dave's Coffee", appBaseUrl: 'https://daves.saasapp.com' },
{ bearerToken },
);The address is held to the rule every organization address is. It sits under your project’s own app address or a domain the project has verified, and an address another of the project’s organizations holds is refused. A refused founding writes nothing, so the founder can pick another subdomain and try again.
Or keep the door yours. Self-service lets any signed-in user register an organization. If sign-up should pass through your own checks first (a payment, an invitation, a waiting list), leave organizationSignupEnabled off, name the founder’s role alone, and provision from one operation that declares organizations:create.
Two things keep this safe to hand to the public. The mutation exists in your schema only while the setting is on: a project that never opted in has no registerOrganization field for anyone to find. And an opted-in project that names no usable role refuses every registration rather than founding an organization its founder cannot act in; fix the role, not the caller.
Routine work in every organization
A schedule starts its operation at the project’s own level, where no organization’s records are in reach. One that says each: 'organization' starts a run in every active organization instead, each confined to its own: the nightly upkeep every tenant needs, with no run that reaches two of them. See Running in every organization.
Letting an organization close itself
Scheduling a deletion is the project’s decision, and nothing standing in an organization makes it. A product where an organization’s owner can close their own account still needs that decision made by you, once, in advance: you write an operation that closes the organization it runs in, and you decide who may run it.
operations: [
{
key: 'close-organization',
name: 'Close this organization',
endpoint: 'https://example.com/api/close-organization',
grants: ['organizations:delete'],
},
],Its handler makes one call, with the app client and the token the run was dispatched with:
const { deletionScheduledAt, organizations } = await foir.organizations.scheduleDeletion();It takes no organization. The one it schedules is the one the run acts in, which is the one whoever started it was standing in, so a run cannot be pointed at another: not a client of a reseller on its own, not the organization next door. A run that acts in no organization is refused.
It goes through the same lifecycle as any scheduled deletion. The organization and everything nested under it go on the 30-day clock, and the answer names each one and the date. The organization stops being active at once, so whoever closed it stops standing in it as soon as the call answers. Nothing is removed until the date.
It cannot be undone from inside. Resuming is yours: a console user or a project key that holds organizations:write cancels the deletion during the 30 days. The operation cannot, and neither can anything else that stands in the organization.
It is for somebody who runs the organization. The run has to be acting for a signed-in user who holds a membership of that organization. A visitor who names the organization to a publishable key, and one of the organization’s own users, close nothing, whoever let them run the operation.
Among its members, who can close is who can run the operation. Give its operations:execute to the role your organizations’ owners hold, and to nobody else: any member whose role runs it can close the organization. Have the operation check what you need first: that the caller is the owner, a second factor, a typed confirmation.
Organization-owned records
Containment answers “which organization’s rows can this caller see”. Some records belong to an organization and still have to be read by the project: each tenant’s settings, which your back office lists across every shop and each shop reads as its own.
That is a model with access.ownerPlane: 'organization'. Its records are owned by an organization (_ownerKind is "organization", _ownerId is the org’s id) while staying in the project-shared tier (org_id unset). Ownership, not containment: the project key reads every organization’s, and each record still names its owner. singleton: true there means one record per organization.
// foir.config.ts: one settings record per tenant
{
key: 'tenant_settings',
name: 'Tenant settings',
singleton: true,
access: { ownerPlane: 'organization', defaultVisibility: 'private' },
fields: [
{ key: 'currency', type: 'text', required: true },
{ key: 'openingHours', type: 'text' },
],
}Such records are created by the project (a project credential, or a person on your team in the console), never for a user. An operation creates one in a single case: the settings record of an organization it provisions. The owner is named on create (ownerId), or is the organization the caller acts in: the console asks which organization when you create one, or uses the one you are standing in. The rules, and what is refused, are in Defining Models → Organization-owned models.
The organization that owns one writes it from inside itself. Standing in an organization (a key confined to it, X-Org-Id on the project key, or the console at its address), an update or a delete meets three kinds of row, and the refusal names the level on both sides:
| Standing in organization X, the row is | An update or delete |
|---|---|
| at X’s own level | is written, like any of X’s rows |
| in the project-shared tier, and X owns it | is written: X’s organization-owned records, and what is derived from them |
| in the project-shared tier, and X does not own it (another organization does, a user does, or nobody does) | is refused 403 PERMISSION_DENIED: cannot update this record: it sits at the project's shared level; this request writes at organisation X's level and does not own it |
A row at another organization’s level that the caller can read, one beneath it, is refused with that level named: cannot update this record: it sits at organisation Y's level; this request writes at organisation X's level. Deletes say cannot delete this record and are otherwise the same.
From the project, a write goes to the record’s organization. Standing at the project’s shared level you read every organization’s records, but an update to one an organization holds is refused: cannot update this record: it sits at organisation X's level; this request writes at the project's shared level. Send it to the organization instead. The console does that for you: a record opened from the project-wide list, a search, or any link that names it at the project opens at its organization’s address, /t/{workspace}/p/{project}/o/{organization}/…. A note about a record names that organization (subjectOrgId), so the field framed beside it in Work saves where the record is, and a site that frames a field for editing frames it at the same address.
Owning means being the owner, exactly: an organization above X does not write X’s settings record, and X does not write those of the organizations beneath it, the same as at their levels. So once your application has resolved a subdomain to its organization and acts inside it, the organization’s own settings record is written by that client too, with no second, project-wide client kept around to do it.
A user edits them only through a role that grants it. The table above is about where a write lands; who may make it is the caller’s authority, as everywhere. A service, a key or your staff in the console write the organization’s own records as described. A user holding a role in the organization reads them, and updates one only when the role grants writing its model: records:write:<model>, or records:write for every model. Otherwise the update is refused 403 PERMISSION_DENIED: cannot update this record: it sits at the project's shared level, owned by organisation X; this request writes at organisation X's level, and no role it holds in organisation X grants records:write on model <model>. No role lets a user delete one: the record is the project’s to provision and retire.
Naming the organization from the project credential (X-Org-Id)
A project’s key, of any kind, names the organization it acts in for one request with the X-Org-Id header. It is the project credential’s way of standing in a tenant: the back office acting on one user’s shop, or an app that already knows the organization’s id. An app that knows only the page it is on names the organization by that page’s address instead, with X-Org-Url.
- The id must be an active organization of the credential’s own project. Unknown, suspended, pending deletion and another project’s organization all answer
404NOT_FOUND: one answer, so the header cannot be used to find out which organizations exist. Active means effectively active: an organization inside a suspended one answers404too. - A credential already confined to an organization may only name that one, not even an organization beneath it. Anything else is
403PERMISSION_DENIED: the header can narrow a project key, and cannot widen or redirect a confined one. - A request acting for a user who does not stand in the named organization is refused
403PERMISSION_DENIED. A user who runs two shops holds one selection, and a request on the other shop’s host is refused rather than silently written into the shop they last picked. - It enters the response-cache key, so two organizations’ answers never share an entry, and it is on the CORS allow-list.
Once bound, the request behaves exactly as one on a confined credential: reads see that organization, everything beneath it and the project-shared tier, writes are stamped into it, and an organization-owned record created without an explicit owner belongs to it. The exact errors are in Selecting an Organization.
Knowing the organization’s id before the first request, end to end:
import { createFoirClient } from '@foir/sdk/data';
import * as generated from './foir.generated';
// 1. The publishable key the page ships asks which organization this page is
// for. An address no organization registered answers NOT_FOUND.
const project = createFoirClient({ apiUrl, apiKey: env.PUBLIC_FOIR_KEY, generated });
const orgId = (await project.ns.project.resolveOrganizationAddress({ url: request.url })) as string;
// 2. Act inside that organization from here on: every request this client
// makes carries X-Org-Id.
const foir = createFoirClient({ apiUrl, apiKey: env.PUBLIC_FOIR_KEY, generated, orgId });
const menu = await foir.menuItem.findMany(); // Dave's menu, and no one else'sWhen the id is only ever used to make requests, skip the first step and set orgUrl on the client instead: see below.
Set orgId on the client, not on the call. Build one client per organization you act in and do not reach for the project-wide one again once you know the tenant. There is a per-call orgId on the request options, for the odd request that has to act somewhere else, and it is the riskier spelling for an unglamorous reason: a call that omits it is not refused, it reads the project-shared tier. A smaller answer, not an error, and nothing on the screen to say which you got.
Naming an organization names a subtree. Organizations nest and reach runs downward, so the id of a reseller covers every client beneath it as well as the reseller’s own rows:
X-Org-Id: <reseller> → the reseller, every client under it, and the project-shared tier
X-Org-Id: <client> → that client and the project-shared tier. Nothing above or beside it.Send the narrowest id that covers what the request is about. Sending the reseller when you meant one client is not an error anywhere: it is a wider answer that looks right, which is the failure mode worth knowing about before it is a support ticket.
And what it can never do is widen: the server resolves the header against the credential’s own reach and refuses anything outside it, so this steers a project key within its project and steers an organization key nowhere at all.
Finding the organization from the page address (X-Org-Url)
An app that serves many organizations from its own addresses knows which organization a page is for from the page itself. X-Org-Url names the organization by that address, with any key of the project, a publishable one in the browser included:
curl https://api.foir.dev/graphql \
-H "x-api-key: foir_pub_..." \
-H "X-Org-Url: https://saasapp.com/daves/menu" \
-H 'content-type: application/json' \
-d '{"query":"{ menuItems(first: 20) { edges { node { _id name } } } }"}'// Every request this client makes names the organization the page is on.
const foir = createFoirClient({ apiUrl, apiKey: env.PUBLIC_FOIR_KEY, generated, orgUrl: window.location.href });An organization’s addresses are its app base URL, which may carry a path, and the verified custom domains bound to it. Set the app base URL in the organization’s settings, with appBaseUrl on UpdateOrganization, in the brand of a provision, or when a signed-in user founds the organization themselves.
An app base URL sits under a domain the project controls. User email links to it and the hosted sign-in returns users beneath it, so a new or changed one is admitted only when its host is the registrable domain, or a subdomain, of a custom domain the project has verified or of the project’s own app base URL. daves.saasapp.com and saasapp.com/daves are both fine for a project whose address is saasapp.com. Anything else is refused with 400 FAILED_PRECONDITION, naming the domains it may sit under; an http address, or one with a query or fragment, is refused with 400 INVALID_ARGUMENT. An address already stored is not checked again.
The longest address wins, at a path-segment boundary. The URL belongs to the organization whose address is its longest prefix, cut at a /:
| Page URL | Registered addresses | Organization |
|---|---|---|
saasapp.com/daves/menu | saasapp.com/daves | Dave’s |
saasapp.com/davesnews | saasapp.com/daves | none: /davesnews is not under /daves |
saasapp.com/daves/soho/menu | saasapp.com/daves, saasapp.com/daves/soho | Dave’s Soho branch, nested under Dave’s |
daves.saasapp.com/checkout | daves.saasapp.com | Dave’s |
https://DAVES.saasapp.com/?utm=x#top | daves.saasapp.com | Dave’s |
The host is compared lowercased; the scheme, query, fragment and a trailing slash are ignored. The path is compared as written, so /Daves and /daves are two addresses.
An address belongs to one organization of a project. Registering an address another organization of the project already holds, as its app base URL or as a custom domain bound to it, is refused with 409 ALREADY_EXISTS at the write that would give it to a second one. Two projects may use the same address.
It is X-Org-Id in another spelling, and bounded the same way.
- A URL no active organization’s address covers answers
404NOT_FOUNDwith the message an unknownX-Org-Idgets, so nothing can be learned from the difference. That includes a suspended organization’s address, and another project’s. - A credential confined to an organization may use only that organization’s own addresses; any other answers
404. - Sent with
X-Org-Id, the two must name the same organization, or the request is refused400INVALID_ARGUMENT. - Once resolved, the request is exactly one that sent the organization’s id: the same reads, writes and refusals, and the same response-cache entry. The organization is a selection, not authority: what the request reaches is still decided by the key’s scopes and the user’s own sign-in.
- There is no list and no prefix search. An organization is found only by an address that is its own.
- Answers are cached for a short time by URL at the edge, and every request counts against the key’s rate limit as usual.
To know the id up front, for a brand to render before the first data request or for code that sends X-Org-Id, ask for it:
{ resolveOrganizationAddress(url: "https://saasapp.com/daves/menu") }const orgId = (await foir.ns.project.resolveOrganizationAddress({ url: request.url })) as string;It answers the organization’s id, or NOT_FOUND exactly as the header does.
Reading across organizations (X-Org-Reach)
X-Org-Id stands in one organization. The reporting question (how many orders did every shop take this month) is the other one, and answering it by looping over ids is both slow and wrong at the edges, because an organization created between two iterations is simply missing from the total.
X-Org-Reach: project answers it in one request. The reads it makes return every organization of the credential’s own project, plus the project-shared tier, instead of one organization’s rows:
POST /identity.v1.IdentityService/ListOrganizations
x-api-key: foir_adm_...
X-Org-Reach: projectproject names the level the reach starts from, and it is the only value. Anything else is refused rather than ignored, so a narrower reach that does not exist yet cannot be asked for and silently granted in full.
Four bounds hold it, and each closes a different hole:
- The credential must hold
organizations:reach. The header grants nothing on its own, exactly asX-Org-Idgrants nothing on its own. It is a capability rather than an action: no endpoint requires it, and holding it changes only what reads the credential could already make return. - Never on a key confined to an organization. Reaching across organizations from inside one is the confinement escaping itself, which is the single thing this level exists to prevent. The scope is refused when such a key is minted, and the header is refused again on every request, because a key minted before that gate existed still carries whatever it was given.
- Never on a publishable or a server key. A publishable key is embeddable in a browser bundle, so a storefront carrying this would read every other storefront in the project, and a server key gives what a publishable key gives. Refused at mint.
- Not together with
X-Org-Id, and not on a request acting for a user. Standing in one organization and reading across all of them are different requests, and a caller who sent both has not said which they meant. A request acting for a user is refused outright: the capability is the project’s own view of its tenants, not something a user’s session borrows.
It is a read, and only a read. The claim widens what SELECT returns and nothing else. Inserts are still stamped from X-Org-Id, so a reaching credential writes to the project-shared tier exactly as it would without the header, and updates and deletes still pin the organization exactly. Reaching down to read is reporting; reaching down to write is managing somebody else’s data.
Ask per request, not once on the credential. A credential whose every read silently widened would widen the resolution reads inside its writes too (the natural-key lookup, the upsert target) so a key minted for a nightly report would change the meaning of an unrelated upsert. A credential holding the scope behaves identically to one without it until a request asks.
The platform endpoint only.
X-Org-Reachis read where the credential is presented to the platform directly. The public API atapi.foir.devneither accepts it in a browser preflight nor passes it on, so sending it there does nothing at all: reads carry on returning the project-shared tier.X-Org-Idis the header that works on both.
From the CLI
Organizations are managed with foir orgs: listing and drawing the tree, creating one under a parent, moving a subtree, suspending, deleting, members and caps. Every command is in the command reference.
You stand in an organization the same two ways you stand in a project, because it is the same kind of boundary one level down:
foir context switch-org org_leeds # stand in it, across commands
foir context show # say which one, or "the project itself"
foir --org-id org_bristol records list # act in one for this command only
foir --org-id - records list # the project itself, this command only--org-id beats a standing selection and writes nothing, so you can reach across without switching and switching back. - is the project said out loud — the way back up for one command, or permanently with foir context switch-org -.
Management commands are the exception, and deliberately so: foir orgs suspend, foir orgs delete and foir orgs members remove take their organization as an argument and never act on the one you happen to be standing in. This is the level where forgetting where you are means acting on the wrong user, so those commands make you name the subject in the command itself.
A credential confined to an organization ignores all of it: it can only ever be that organization, whatever it is asked, which is why a deployed key needs no selection and a person does.
From a connected agent
An agent connected over MCP stands in an organization the same way your staff do, and by the same explicit act: it lists the project’s organizations, names one, and every read and write from then on is that organization’s, reading down through everything beneath it and the project-shared tier. Every entry is audited, with the user’s name on it.
Standing in none is the project-shared position rather than a missing one, and the agent says which of the two it is on request. That distinction is the whole reason it is said out loud: an agent in the project-shared position asked “how many users are there” answers truthfully about a set that excludes every organization’s own, and a number with no position attached is the shape that gets read as a fact about the project.
A credential confined to an organization needs none of this: it can only ever be that organization, whatever it is asked.
In the console
Your staff pick one organization at a time from the switcher, exactly as they pick one project. It sits below the workspace and project switchers because it is the next containment level down, and it appears only once a project actually has organizations: a project with none does not grow a control that always says the same thing.
Selecting is not a filter. The session carries the organization, the row layer confines every read to it and everything beneath it, and the server returns a different set, so every cached answer is dropped and the screen re-reads exactly as it does on a project switch. Clearing the selection returns you to the project-shared view, which is a real position to be in rather than an empty one.
Managing one happens on its own page. The project’s organizations list opens each organization’s page: where it sits and moving it, which pool its people sign in to, suspending and deleting it, its usage, its limits, its members and the keys confined to it. Everything there is also foir orgs and the RPCs behind it.
Selection charges no permission of its own, and that is on purpose. It is not an escalation: it is the mechanism by which a project-level permission reaches a partitioned table at all. Without organizations, users:read.all showed every user; with them it shows the project-shared population, and selecting an organization restores the rest one subtree at a time. What you can do once you are there is still decided by the permissions you hold.