> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fga.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Getting Started with the FGA Permissions Index

> Learn how to create an FGA Permissions Index, stream expansions, and persist them in your own data store.

## What Read Expansions Sends You

Each time a tuple is written or deleted in FGA, the Permissions Index incrementally computes every access that the permission change implies and streams one or more [expansion events](https://docs.fga.dev/permissions-index/terminology.md#expansion-events) on the Read Expansions endpoint. You store those events as rows in a permissions table next to your application data. The question "which documents can Anne view?" becomes a SQL join instead of an API call per row.

To learn how the index keeps up with every permission change, see [FGA Permissions Index](https://docs.fga.dev/permissions-index/fga-permissions-index.md).

***

## Prerequisites

Before creating an index, make sure you have an Auth0 FGA [enterprise subscription](https://docs.fga.dev/subscription-plans.md#enterprise-subscription). The Permissions Index is not available for free customers. If you are an enterprise customer, you are [entitled to](https://docs.fga.dev/subscription-plans.md#permissions-index-subscription-add-on) 1 index, 1 relation, and 10 million expansions. Any additional usage will require the FGA Permissions Index add-on SKU. You can always delete an index to reduce your entitlements.

Make sure the Permissions Index is enabled for your account. When it is, a **Permissions Index** tab appears in the sidebar when you open a store in the [FGA Dashboard](https://dashboard.fga.dev/). If you don't see it, [get it enabled](https://docs.fga.dev/subscription-plans.md#permissions-index-subscription-add-on) before continuing.

### Save environment variables

Copy these environment variables into your favorite text editor. You fill in the values as you follow the guide, then paste them into your terminal.

```sh theme={null}
# Swap 'us1' for your region ('eu1' or 'au1') if different
FGA_API_URL=https://api.us1.fga.dev
FGA_API_TOKEN_ISSUER=auth.fga.dev
FGA_API_AUDIENCE=https://api.us1.fga.dev/
FGA_STORE_ID=your-store-id
FGA_MODEL_ID=your-model-id
FGA_INDEX_ID=your-index-id
FGA_CLIENT_ID=your-client-id
FGA_CLIENT_SECRET=your-client-secret
```

## Step 1: Create a Test Store and Authorization Model

This guide uses a demo store and model. Create a new store so the guide doesn't touch your existing FGA data:

1. [Download the demo .fga.yaml file](https://docs.fga.dev/downloads/permissions-index-demo.fga.yaml)
2. Navigate to the [FGA Dashboard](https://dashboard.fga.dev/).
3. Create a new store called `permissions-index-demo`.
4. Navigate to the **Model Explorer** page.
5. Drag the downloaded `permissions-index-demo.fga.yaml` file into the **Model Explorer** to upload the model and tuples.
6. Select `Import model` and `Import tuples`. This will seed your store with the model and tuples.

![Uploading the demo model file in the FGA Dashboard Model Explorer](https://mintlify.s3.us-west-1.amazonaws.com/auth0-fga/images/fga/static/img/model-file-upload.gif)

The demo defines a simple hierarchy of `folder` and `document` types and distributes sample tuples so that each incrementing folder ID contains exactly the number of documents under it. The demo has three moving parts:

* **Folders hold documents.** `folder:N` is the parent of exactly N documents. For example, `folder:4` holds `document:4-1`, `document:4-2`, `document:4-3`, and `document:4-4`.
* **Folder viewers can view every document inside.** `document#viewer` includes `viewer from parent`, and `document#can_view` is defined as `viewer`.
* **Teams can be folder viewers.** The store already gives `team:design` access to `folder:3`, `team:product` access to `folder:5`, and `team:engineering` access to `folder:10`. No team has members yet.

Copy the **Store ID** and **Model ID**, and update `FGA_STORE_ID` and `FGA_MODEL_ID`.

***

## Step 2: Create a Permissions Index

1. Open the `permissions-index-demo` store in the top right "Select Store" dropdown.

2. Select the **Permissions Index** tab from the sidebar.

3. Click the **Create Index** button in the top right.

4. Select an authorization model, then click **Next**.

5. Select one or more relations to index. Select `document#can_view` to follow this guide, then click **Next**. Relations that use [unsupported modeling features](https://docs.fga.dev/permissions-index/fga-permissions-index.md#authorization-models) are disabled.

   ![Selecting the document#can\_view relation in the FGA Dashboard](https://mintlify.s3.us-west-1.amazonaws.com/auth0-fga/images/permissions-index/create-permissions-index.png)

6. Click **Create Index**.

Copy the new **Index ID** and update `FGA_INDEX_ID`. You will use it to read expansions from the stream later.

> [!TIP]
>
> FGA automatically assigns existing compatible authorization model versions to the index, plus assigns any new compatible authorization models created in the future. See [migrating between authorization models](https://docs.fga.dev/permissions-index/best-practices.md#3-migrating-between-authorization-models) for what to do if a model is incompatible.

## Step 3: Configure Client Credentials

[Create client credentials](https://docs.fga.dev/getting-started.md#create-api-client-credentials) for your application:

1. In the FGA Dashboard, open **Store Settings**.
2. In the **Authorized Clients** section, click **Create Client**.
3. Name the client `index-demo` and enable these permissions:
   * **Read Permissions Index**, to call the [Read Expansions](https://docs.fga.dev/api/service/permissions-index/read-expansions.md) endpoint.
   * **Write and delete tuples**, to write the relationship in Step 5.

Copy the **Client ID** and **Client Secret**, and update `FGA_CLIENT_ID` and `FGA_CLIENT_SECRET`.

> [!TIP]
>
> If you are using an existing client, make sure to update it with **Read Permissions Index** access.

### Obtain an access token

All FGA API endpoints require a `Bearer` token. Get one with the OAuth2 client credentials flow, as described in the [Call the API](https://docs.fga.dev/getting-started.md#call-the-api) guide.

Make sure the variables from [Save environment variables](#save-environment-variables) are set in your terminal before continuing.

Then run:

```sh theme={null}
curl -X POST \
    https://$FGA_API_TOKEN_ISSUER/oauth/token \
    -H 'content-type: application/json' \
    -d '{"client_id":"'$FGA_CLIENT_ID'","client_secret":"'$FGA_CLIENT_SECRET'","audience":"'$FGA_API_AUDIENCE'","grant_type":"client_credentials"}'
```

Copy the `access_token` from the response and set it:

```sh theme={null}
FGA_ACCESS_TOKEN=your-access-token
```

You will need to use two terminals in the next steps. Set the environment variables and `FGA_ACCESS_TOKEN` in both.

> [!TIP]
>
> All FGA access tokens are short-lived. Cache the token for reuse and obtain a new one before expiry to avoid interruptions. FGA SDKs handle token caching and refreshing automatically.

## Step 4: Open the Read Expansions Stream

Read Expansions is a long-lived NDJSON stream endpoint emitting one JSON event per line, delivered in real-time.

In your first terminal, open the stream and leave it running. `--no-buffer` prints each event as it arrives.

```sh theme={null}
curl --no-buffer \
  "$FGA_API_URL/stores/$FGA_STORE_ID/indexes/$FGA_INDEX_ID/expansions?authorization_model_id=$FGA_MODEL_ID" \
  --header "Authorization: Bearer $FGA_ACCESS_TOKEN"
```

The first connection replays every existing expansion event, then stays open waiting for new events.

Also watch for freshness events. These indicate that the index is caught up and waiting for new changes.

```json theme={null}
{
  "result": {
    "freshness": {
      "as_fresh_as": "2026-04-14T18:20:54.368739Z"
    }
  }
}
```

When `as_fresh_as` is recent, the index has caught up to that point. Any event after that comes from your writes.

## Step 5: Grant Access, Receive Expansions

In your second terminal, grant Anne viewer access to `folder:4` by writing to FGA:

```sh theme={null}
curl --request POST \
  --url "$FGA_API_URL/stores/$FGA_STORE_ID/write" \
  --header "Authorization: Bearer $FGA_ACCESS_TOKEN" \
  --header 'content-type: application/json' \
  --data "{
    \"authorization_model_id\": \"$FGA_MODEL_ID\",
    \"writes\": {
      \"tuple_keys\": [
        { \"user\": \"user:anne\", \"relation\": \"viewer\", \"object\": \"folder:4\" }
      ]
    }
  }"
```

The Write response is empty when it succeeds. Now look at your first terminal. Four events arrived, one for each document in the folder:

```text theme={null}
You write 1 tuple
  user:anne viewer folder:4
        │
        ▼
FGA follows the model
  folder:4 is parent of:
    document:4-1
    document:4-2
    document:4-3
    document:4-4
        │
        ▼
You receive 4 events
  INSERT user:anne can_view document:4-1
  INSERT user:anne can_view document:4-2
  INSERT user:anne can_view document:4-3
  INSERT user:anne can_view document:4-4
```

Your write changed permissions at the folder level; the expansions resolved to the document level. Each event turns into a row in a database that your application can query to determine access.

```json theme={null}
{
  "result": {
    "event": {
      "from": "FmhrVnpxNHBsUWgyNHc3NXh0R2NIX2e...",
      "id": "018f0c21-9dc8-7e38-9a45-0f2bc4d5e6f7",
      "subject_type": "user",
      "subject_id": "anne",
      "object_type": "document",
      "object_id": "4-1",
      "relation": "can_view",
      "operation": "EXPANSION_OPERATION_INSERT",
      "as_fresh_as": "2026-04-14T18:21:03Z"
    }
  }
}
```

* `operation` is `EXPANSION_OPERATION_INSERT` when access is granted and `EXPANSION_OPERATION_DELETE` when access is revoked.
* `from` is a continuation token. You use it in Step 7 to resume the stream from a specific point.
* `subject_relation` is set only when the subject is a userset, such as `team:design#member` in the demo. Store an empty string when it's absent.

## Step 6: Persist the Stream in Your Database

Read Expansions delivers events. It does not maintain a table for your application to query. Your consumer reads each event and applies it to a permissions table in your own database:

```sql theme={null}
CREATE TABLE permissions (
  subject_type     TEXT NOT NULL,
  subject_id       TEXT NOT NULL,
  subject_relation TEXT NOT NULL DEFAULT '',
  object_type      TEXT NOT NULL,
  object_id        TEXT NOT NULL,
  relation         TEXT NOT NULL,
  PRIMARY KEY (subject_type, subject_id, subject_relation, object_type, object_id, relation)
);
```

On `EXPANSION_OPERATION_INSERT`, upsert the row. On `EXPANSION_OPERATION_DELETE`, delete the matching row. The stream can deliver an event more than once, so this keeps replays harmless. See [Designing an Idempotent Consumer](https://docs.fga.dev/permissions-index/best-practices.md#designing-an-idempotent-consumer) for a production-ready version.

After Step 5, Anne has four rows: `document:4-1`, `document:4-2`, `document:4-3`, and `document:4-4`. Filter search results with a join, with no FGA API call necessary:

```sql theme={null}
SELECT d.*
FROM documents d
JOIN permissions p
  ON p.object_type = 'document'
  AND p.object_id = d.id
  AND p.relation = 'can_view'
WHERE p.subject_type = 'user'
  AND p.subject_id = 'anne'
  AND d.title LIKE '%budget%';
```

## Step 7: Resume After Disconnect

The server closes each stream connection after 5 minutes, and your consumer will need to restart sometimes. You will not want to replay the whole index each time.

As you process events, save the `from` token of the last event you stored. To resume, pass it back. The stream picks up right after that event:

```sh theme={null}
FGA_INDEX_FROM=your-last-saved-continuation-token

curl --no-buffer --get \
  "$FGA_API_URL/stores/$FGA_STORE_ID/indexes/$FGA_INDEX_ID/expansions" \
  --header "Authorization: Bearer $FGA_ACCESS_TOKEN" \
  --data-urlencode "authorization_model_id=$FGA_MODEL_ID" \
  --data-urlencode "from=$FGA_INDEX_FROM"
```

## Next Steps

Before you use the Permissions Index in production, read the [best practices](https://docs.fga.dev/permissions-index/best-practices.md):

* [Continuation token management](https://docs.fga.dev/permissions-index/best-practices.md#continuation-token-management): where to store `from` tokens and when to save them.
* [Idempotency and deduplication](https://docs.fga.dev/permissions-index/best-practices.md#1-idempotency-and-deduplication-patterns): handling duplicate and out-of-order events.
* [Freshness](https://docs.fga.dev/permissions-index/best-practices.md#2-leveraging-freshness-for-authorization-decisions): how current your table is, and when to fall back to `Check`.
* [Migrating between authorization models](https://docs.fga.dev/permissions-index/best-practices.md#3-migrating-between-authorization-models): what happens to your index when your model changes.

> [accordion] Read Expansions with an FGA SDK
>
> In production, your consumer reads the stream with an FGA SDK instead of `curl`:
>
> > [tab] Node.JS
> >
> > ```js theme={null}
> > const resp = await fgaClient.executeStreamedApiRequest({
> >     operationName: "ReadExpansions",
> >     method: "GET",
> >     path: '/stores/{store_id}/indexes/{index_id}/expansions',
> >     pathParams: {
> >         store_id: process.env.FGA_STORE_ID,
> >         index_id: process.env.FGA_INDEX_ID,
> >     },
> >     queryParams: {
> >         authorization_model_id: process.env.FGA_MODEL_ID,
> >     },
> > })
> >
> > for await (const item of parseNDJSONStream(resp)) {
> >     console.log(item)
> > }
> > ```
>
> > [tab] Go
> >
> > ```go theme={null}
> > req := openfga.NewAPIExecutorRequestBuilder(
> >     "ReadExpansions",
> >     "GET",
> >     "/stores/{store_id}/indexes/{index_id}/expansions",
> > ).
> >     WithPathParameter("store_id", os.Getenv("FGA_STORE_ID")).
> >     WithPathParameter("index_id", os.Getenv("FGA_INDEX_ID")).
> >     WithQueryParameter("authorization_model_id", os.Getenv("FGA_MODEL_ID")).
> >     Build()
> >
> > channel, err := fgaClient.GetAPIExecutor().ExecuteStreaming(ctx, req, openfga.DefaultStreamBufferSize)
> > if err != nil {
> >     log.Fatalf("failed to send request: %v", err)
> > }
> > defer channel.Close()
> >
> > for {
> >     select {
> >     case result, ok := <-channel.Results:
> >         if !ok {
> >             // Results channel closed, stream completed
> >             // Check for any final errors
> >             select {
> >             case err := <-channel.Errors:
> >                 if err != nil {
> >                     log.Fatalf("stream error: %v", err)
> >                 }
> >             default:
> >             }
> >             return
> >         }
> >
> >         log.Printf("%+v", string(result))
> >     case err := <-channel.Errors:
> >         if err != nil {
> >             log.Fatalf("stream error: %v", err)
> >         }
> >     }
> > }
> > ```
>
> > [tab] .NET
> >
> > ```csharp theme={null}
> > var request = RequestBuilder<object>
> >     .Create(
> >         HttpMethod.Get,
> >         configuration.ApiUrl,
> >         "/stores/{store_id}/indexes/{index_id}/expansions"
> >     )
> >     .WithPathParameter("store_id", Environment.GetEnvironmentVariable("FGA_STORE_ID"))
> >     .WithPathParameter("index_id", Environment.GetEnvironmentVariable("FGA_INDEX_ID"))
> >     .WithQueryParameter("authorization_model_id", Environment.GetEnvironmentVariable("FGA_MODEL_ID"));
> >
> > await foreach (var item in fgaClient.ApiExecutor.ExecuteStreamingAsync<object, object>(
> >     request, "ReadExpansions")) {
> >     Console.WriteLine(item);
> > }
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > async for chunk in fga_client.execute_streamed_api_request(
> >     operation_name='ReadExpansions',
> >     method='GET',
> >     path='/stores/{store_id}/indexes/{index_id}/expansions',
> >     path_params={
> >         "store_id": os.environ['FGA_STORE_ID'],
> >         "index_id": os.environ['FGA_INDEX_ID'],
> >     },
> >     query_params={
> >         'authorization_model_id': os.environ['FGA_MODEL_ID'],
> >     }
> > ):
> >     print(repr(chunk))
> > ```
>
> > [tab] Java
> >
> > ```java theme={null}
> > var request = ApiExecutorRequestBuilder.builder(
> >                 HttpMethod.GET,
> >                 "/stores/{store_id}/indexes/{index_id}/expansions"
> >         )
> >         .pathParam("store_id", System.getenv("FGA_STORE_ID"))
> >         .pathParam("index_id", System.getenv("FGA_INDEX_ID"))
> >         .queryParam("authorization_model_id", System.getenv("FGA_MODEL_ID"))
> >         .build();
> >
> > fgaClient.streamingApiExecutor(HashMap.class)
> >         .stream(
> >                 request,
> >                 System.out::println,
> >                 err -> err.printStackTrace()
> >         )
> >         .exceptionally(err -> {
> >             err.printStackTrace();
> >             return null;
> >         });
> > ```
