# Share data with spaces

https://docs.serverpod.dev/next/concepts/data-and-the-database/database/offline-sync/spaces

Every synced row belongs to one space. A space's members are the users who sync its rows. To share data, your server creates a shared space and gives users a role in it. Their devices then write rows into that space.

## Personal and shared spaces

Each user has a personal space, with the user's id as its UUID. It needs no setup, and only that user syncs it.

A shared space has members, and each member has the role `readOnly` or `readWrite`. Offline sync has only these two roles, so keep invitations and app roles, such as owner, in your own tables. A role covers every row in the space. There are no per-row permissions, so put data for different groups of users in different spaces.

## Create a shared space and add members

You create shared spaces and manage their members in your own server endpoints. A device can't create a space, so it can't start sharing while it's offline. Create the space together with the row it's for, such as a project, and store the space's UUID on that row:

```dart
// requires `import 'package:serverpod_auth_idp_server/core.dart';`
class ProjectEndpoint extends Endpoint {
  @override
  bool get requireLogin => true;

  Future<UuidValue> createProject(Session session, String name) async {
    final userId = session.authenticated!.authUserId;
    final spaceUuid = await session.offlineSync.spaces.createFor(userId);
    await session.db.transactionForUser(
      userId,
      (transaction) => Project.db.insertRow(
        session,
        Project(name: name, spaceUuid: spaceUuid),
        transaction: transaction,
      ),
      spaceId: spaceUuid,
    );
    return spaceUuid;
  }
}
```

The `createFor` method creates the space, makes the user a `readWrite` member, and commits right away. The insert then runs in `transactionForUser` with the new space's UUID, so the project row belongs to that space. If the insert fails, the empty space stays, and calling the endpoint again creates a second one. [Read and write on the server](#read-and-write-on-the-server) covers the rules for server code.

Add and list members with `grant` and `members`. The `grant` method also changes an existing member's role:

```dart
final spaces = session.offlineSync.spaces;
await spaces.grant(
  space: spaceUuid,
  user: memberId,
  role: OfflineSyncSpaceRole.readWrite,
);
final members = await spaces.members(spaceUuid);
```

Each method also takes an optional `transaction`, so you can save a membership change and your own rows together.

Membership changes come with two rules:

- **Check permissions before you change members.** Offline sync doesn't check who may change a space's members. Without your check, any signed-in user who can call the endpoint can give themselves access to any space.
- **Let a device sync before it writes to a new space.** Devices learn of membership changes when they sync. Until then, a write to the new space throws `OfflineSyncSpaceMembershipException`.

## Remove a member

From your endpoint, remove a member with `revoke`:

```dart
await session.offlineSync.spaces.revoke(space: spaceUuid, user: memberId);
```

After you revoke a member:

- Their device stops showing the space's rows on its next sync.
- The rows stay in that device's local database, so the member keeps a copy of the space's data.
- Their unsynced changes to the space stay on the device and upload only if the member gets write access again.

## Read and write on the server

On the server, run every read and write of synced tables in `session.db.transactionForUser`:

```dart
final userId = session.authenticated!.authUserId;
final tasks = await session.db.transactionForUser(
  userId,
  (transaction) => Task.db.find(
    session,
    where: (t) => t.projectId.equals(projectId),
    transaction: transaction,
  ),
);
```

Inside the transaction, reads return only rows from the user's spaces, and writes are checked against the user's role. Two rules keep it that way:

- **Pass the transaction to every call.** A read without it returns every user's rows, and a write without it throws.
- **Take the user id from `session.authenticated`.** Offline sync doesn't check that the id is the signed-in user's, so an id the app sends could let one user act as another.

## Read and write on the device

On the device, writes go to the user's personal space by default. To write to a shared space, run the write in `transactionForUser` with the space's UUID:

```dart
final userId = client.auth.authInfo!.authUserId;
await session.db.transactionForUser(
  userId,
  (transaction) => Task.db.insertRow(
    session,
    task,
    transaction: transaction,
  ),
  spaceId: project.spaceUuid,
);
```

If the user can't write to the space, the write throws and nothing is written:

- A `readOnly` member gets `OfflineSyncSpaceRoleException`.
- A user who isn't a member gets `OfflineSyncSpaceMembershipException`.

To write to several spaces in one transaction, use `transactionForSpaces`, as [Move data into a shared space](#move-data-into-a-shared-space) shows.

Unlike on the server, reads need no transaction. They return rows from every space the user belongs to. To read one space only, add `t.spaceEquals(spaceUuid)` to the `where` clause.

The `spaceId` field reads as `null` in your app, so it can't tell you a row's space. Instead, store the space's UUID on the row the space is for, like `spaceUuid` on `Project`.

## Move data into a shared space

A row can't change its space. To share data that's in the personal space, insert copies with new ids in the shared space and delete the originals. Do both in one transaction with `transactionForSpaces`, so the device makes both changes or neither:

```dart
await session.db.transactionForSpaces(userId, {userId, spaceUuid}, (spaces) async {
  await spaces.runForSpace(spaceUuid, (transaction) async {
    // Insert the copies.
  });
  await spaces.runForSpace(userId, (transaction) async {
    // Delete the originals.
  });
});
```

Two rules apply to the move:

- **Copy related rows together.** [Relations can't reach another space](https://docs.serverpod.dev/next/concepts/data-and-the-database/database/offline-sync/modeling.md#rules-for-synced-tables), so point each copy's foreign keys at the other copies.
- **Await each `runForSpace` call before you start the next.** Overlapping calls throw a `StateError`.

## Check membership on the device

Each device keeps a read-only copy of the user's own memberships, so your app can check a role, for example to hide edit buttons for `readOnly` members:

```dart
final role = await OfflineSyncSpaceMembership.roleOf(
  session,
  userUuid: userId,
  spaceUuid: spaceUuid,
);
```

The `roleOf` method returns `null` if the user isn't a member, or if the device hasn't synced the membership yet. To list a space's members, call `members` from an endpoint.

## Related

- [Offline sync](https://docs.serverpod.dev/next/concepts/data-and-the-database/database/offline-sync.md): how sync works and the rules every write follows.
- [Model synced data](https://docs.serverpod.dev/next/concepts/data-and-the-database/database/offline-sync/modeling.md): what to keep in one space, and links between spaces.
- [Test offline sync](https://docs.serverpod.dev/next/concepts/data-and-the-database/database/offline-sync/testing.md): testing server code that uses synced tables.
