# Per-customer data

A customer portal shows each customer its own orders, prices or documents. dcupl
has no user accounts and no row-level security: it does not know who is
looking. Your backend draws the line between customers, or what you deploy
does. A query in the browser never does.

## What dcupl does not check

- **The SDK in the browser has no row-level security.** Every item the app
  loads is in the browser's memory and readable in its developer tools,
  whatever list or query the app shows. A query on `customerId` hides rows; it
  doesn't protect them.
- **The key a browser app ships with is public.** Every visitor holds it and
  can download every file its read patterns cover, including `dcupl.lc.json`,
  which lists every resource path of the project (see
  [Two audiences in one project](/console/api-keys#two-audiences-in-one-project)).
- **The application is no boundary.** `process({ applicationKey })` selects
  resources in the browser, after the whole `dcupl.lc.json` has been
  downloaded. Anyone can pass another application or other `resourceTags`.
- **A REST API instance has one key, not one per user.** The runner checks the
  single API key of the instance's template and answers whoever sends it with
  every row the instance loaded. The key names no user and no customer, and an
  instance has no sign-in (see
  [One API key per instance](/console/rapi#one-api-key-per-instance)).
- **Scripted endpoints don't see the caller.** The runner removes the
  `authorization` and `cookie` headers and the API key before a script runs, so
  a script cannot check your users' sessions. What it does get, the path, query,
  body and the other headers, is whatever the caller sent (see
  [Scripted endpoints](/console/rapi/scripted-endpoints)).

A per-customer portal therefore needs a backend of yours that knows the
signed-in user. dcupl answers that backend's queries; it doesn't replace it.

| Pattern                                                                                                  | Who calls dcupl                                      | Fits                                                                 |
| -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------- |
| [Your backend in front of one instance](#your-backend-in-front-of-one-rest-api-instance)                 | Your backend, with the instance key                  | Most portals, any number of customers                                |
| [One instance per customer](#one-rest-api-instance-per-customer)                                         | The customer's own system or agent, with its own key | A few customers who call an API of their own directly                |
| [Your backend hands the browser one customer's rows](#your-backend-hands-the-browser-one-customers-rows) | The browser SDK, with rows from your backend         | Filtering and facets in the browser on data small enough to download |

## Your backend in front of one REST API instance

This is the recommended pattern. One [REST API](/console/rapi) instance loads
the data of all customers, and only your backend talks to it:

```mermaid
flowchart LR
  subgraph Browser["Browser: public"]
    U["Portal user<br/>signed in with your session"]
  end
  subgraph Backend["Your backend: trusted"]
    A["1. check the session<br/>user → customer"]
    Q["2. build the query<br/>add the customer filter"]
  end
  subgraph Runner["REST API instance"]
    I["every customer's data<br/>one API key"]
  end
  U -->|"session cookie"| A
  A --> Q
  Q -->|"api-key, server only"| I
  I -->|"that customer's rows"| Q
  Q -->|"JSON"| U
```

1. Your backend authenticates the user with your own sign-in and looks up the
   customer the user belongs to.
2. It builds the dcupl query itself and adds the customer condition, which the
   request cannot remove.
3. It calls the instance with the instance's API key and returns the result.

The browser never holds the instance key and never calls the runner.

```typescript filename="server/orders.ts"
const RAPI_URL = process.env.RAPI_URL; // {runner-url}/instance/{instance-key}
const RAPI_KEY = process.env.RAPI_KEY; // the instance's API key, on the server only

type Condition = { attribute: string; operator: string; value: unknown };

// customerId comes from the session; filters are the portal's own,
// already checked against the attributes the portal offers
export async function customerOrders(customerId: string, filters: Condition[], start = 0) {
  const response = await fetch(`${RAPI_URL}/query`, {
    method: 'POST',
    headers: { 'api-key': RAPI_KEY, 'content-type': 'application/json' },
    body: JSON.stringify({
      modelKey: 'Order',
      groupType: 'and',
      queries: [
        { attribute: 'customerId', operator: 'eq', value: customerId },
        { groupType: 'and', queries: filters },
      ],
      start,
      count: 50,
    }),
  });
  if (!response.ok) {
    throw new Error(`REST API answered ${response.status}`);
  }
  return response.json();
}
```

What keeps one customer out of another's rows:

- **Take the customer from the session, never from the request.** A customer
  id the browser sends is a guess anyone can change.
- **Put the customer condition at the top level, with `groupType: 'and'`, and
  nest the portal's filters in a group below it.** An `or` the filters bring
  then stays inside their group and cannot widen the result past the customer.
  Set `groupType` on every group: the default differs between the query builder
  and evaluation (see [DcuplQueryGroup](/sdk/api/query-operators#dcuplquerygroup)).
- **Choose the model on the server.** Query only the models the portal shows,
  each with its customer attribute. Don't forward `modelKey`, `queries` or a
  whole options object from the browser: a model the filter doesn't cover
  answers with every customer's rows.
- **Filter every route you use.** `facet`, `aggregate`, `pivot`, `suggest` and
  `metadata` take the same condition in their `query` option; without it they
  count across all customers. Don't pass `overview` through to the portal: it
  reports item counts over all the data.
- **Keep caches per customer.** Data responses carry
  `cache-control: private, max-age=3600`. A cache your backend puts in front of
  the instance must key on the customer, not only on the request.
- **Keep the instance's MCP endpoint away from customers.** An agent connected
  with the instance key reads every row too.

A [scripted endpoint](/console/rapi/scripted-endpoints) fits the same pattern:
your backend passes the customer id as a path parameter, query value or body
field, and the script filters by it. The script can trust that value only
because no one but your backend holds the instance key.

## One REST API instance per customer

When a customer's own system or agent calls an API directly, deploy one
template per customer. Each template loads only that customer's resources and
has an API key of its own, so the key reaches nothing but that customer's
data.

Tag each customer's resources in `dcupl.lc.json`, tag the shared ones (the
product catalog) as well, and define one application per customer:

```json filename="dcupl.lc.json"
{
  "applications": [{ "key": "customer-acme", "name": "ACME", "resourceTags": ["shared", "customer-acme"] }],
  "resources": [
    { "url": "${baseUrl}/models/product.dcupl.json", "type": "model", "tags": ["shared"] },
    { "url": "${baseUrl}/models/order.dcupl.json", "type": "model", "tags": ["shared"] },
    { "url": "${baseUrl}/data/products.csv", "type": "data", "model": "Product", "tags": ["shared"] },
    { "url": "${baseUrl}/data/customers/acme/orders.csv", "type": "data", "model": "Order", "tags": ["customer-acme"] }
  ]
}
```

The template picks that application on the server, where a caller cannot
change it:

```json filename="api/portal-acme.api.json"
{
  "key": "portal-acme",
  "name": "Portal ACME",
  "vGuardEnabled": false,
  "auth": [{ "type": "api-key", "value": "a-long-random-key-for-acme" }],
  "dcuplConfig": {
    "projectId": "your-project-id",
    "apiKey": "your-sdk-readonly-key",
    "processOptions": { "applicationKey": "customer-acme" }
  }
}
```

Plan for the limits of this pattern:

- **The key belongs to the customer, not to a user.** Everyone who holds it
  gets the same access. To change it, edit the template and redeploy the
  instance (**Update** on the runner's tab).
- **Deployed instances per project are capped.** The Templates tab shows
  _Deployed: X/max_.
- **Every instance holds its own copy** of the shared data in memory.

Beyond a handful of customers, put your backend in front of one instance
instead.

## Your backend hands the browser one customer's rows

When the portal should filter in the browser (instant facets, no round trip
per click), let your backend send the browser only the signed-in customer's
rows and load them into the SDK:

```typescript filename="portal.ts"
import { Dcupl } from '@dcupl/core';

const dcupl = new Dcupl();

dcupl.models.set({
  key: 'Order',
  properties: [
    { key: 'status', type: 'string' },
    { key: 'total', type: 'float' },
  ],
});

// your own route: it checks the session and returns that customer's orders only,
// each row with its `key`
const orders = await fetch('/api/my-orders', { credentials: 'include' }).then((r) => r.json());
dcupl.data.set(orders, { model: 'Order' });

await dcupl.init();
```

Your backend reads the rows from a REST API instance, as in the first pattern,
or from your own database. Data that every customer may see, such as the
product catalog, can still come from the dcupl CDN with the browser key: see
[Hybrid data loading](/sdk/guides/hybrid-data). The loader can also fetch its
configuration from your server with your own headers (see
[FetchOptions](/sdk/api/loader#fetchoptions)).

## What about a key per customer in the browser?

On a project with Private CDN, a scoped key whose read patterns cover only
`data/customers/acme/**` (plus the shared files) keeps other customers' files
out of that key's reach. It is still no per-user boundary:

- the key is the same for every user of that customer, and a key cannot be
  revoked for one user;
- every key counts toward your plan's key limit;
- the public `dcupl.lc.json` still lists every customer's resource paths.

Use it only where that is acceptable. See
[A scoped key carries globs over your files](/console/api-keys#a-scoped-key-carries-globs-over-your-files).

## Check the boundary

- Signed in as customer A, open the browser's network tab: no request goes to
  the runner or carries the instance key, and no response holds a row of
  customer B.
- Call each of your backend's routes with customer A's session and customer
  B's id in every parameter you can find: the answer stays customer A's.

## Next steps

- [REST APIs](/console/rapi) — deploy the instance your backend queries
- [API keys](/console/api-keys) — what each key type can read
- [Scripted endpoints](/console/rapi/scripted-endpoints) — routes of your own on the instance
- [Hybrid data loading](/sdk/guides/hybrid-data) — combine CDN data with rows from your backend
