# Set up offline sync

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

To set up offline sync, you add the offline sync packages, mark the tables to sync, open a local database on the device, and start the sync. Your app then reads and writes synced data on the device, and the sync keeps it up to date with the server.

## Before you start

- Offline sync requires a signed-in user whose user id is a UUID, which Serverpod's [authentication module](https://docs.serverpod.dev/concepts/authentication/get-started.md) provides by default.

## Add the packages

Offline sync is a [module](https://docs.serverpod.dev/concepts/server-fundamentals/modules.md) with two packages, one for your server and one for your app. Add the server package to your server project, and the client package to your client project and your Flutter app. Also add `serverpod_database` to your client project, because the generated code for synced tables uses it. Run these commands from your project's root folder:

```bash
cd my_project_server
dart pub add serverpod_offline_sync_server

cd ../my_project_client
dart pub add serverpod_offline_sync_client
dart pub add serverpod_database

cd ../my_project_flutter
flutter pub add serverpod_offline_sync_client
```

The `pub add` command picks the newest version that works with your project's Serverpod version.

## Mark the tables to sync

:::warning
An existing table usually needs remodeling before it can sync. Marking it changes its id to a UUID and limits its relations to other synced tables. [Model synced data](https://docs.serverpod.dev/concepts/data-and-the-database/database/offline-sync/modeling.md) lists the rules.
:::

Offline sync only syncs the tables you mark. Mark each one, then regenerate the code and migrate the database:

1. Set `database: sync` on each table model whose data should sync:

   ```yaml
   class: Task
   table: task
   database: sync
   fields:
     title: String
     done: bool, default=false
   ```

2. Save the file. With `serverpod start` running, Serverpod regenerates the code. If a model breaks one of the [rules for synced tables](https://docs.serverpod.dev/concepts/data-and-the-database/database/offline-sync/modeling.md#rules-for-synced-tables) that code generation checks, the terminal shows the error.

3. In the `serverpod start` terminal, press **M** to create and apply the migration. If you don't use `serverpod start`, follow [Migrations](https://docs.serverpod.dev/concepts/data-and-the-database/database/migrations.md) instead.

The generated `Task` class differs from a normal table's class in two ways:

- **UUID ids instead of numbers:** Devices create rows while offline, so each row needs an id that no other device will make.
- **An extra `spaceId` field:** It records who the row is shared with. Offline sync sets it, so don't set it yourself.

:::note
Your server needs no code of its own to sync. If your server code reads or writes synced tables, follow [Read and write on the server](https://docs.serverpod.dev/concepts/data-and-the-database/database/offline-sync/spaces.md#read-and-write-on-the-server).
:::

## Open the local database

In your Flutter app, after the user signs in, open the local database with `createSyncSession`, not `createSession`. Pass the user's id as `persistentUserId`:

```dart
import 'package:flutter/foundation.dart';
import 'package:serverpod_offline_sync_client/serverpod_offline_sync_client.dart';

final userId = client.auth.authInfo!.authUserId;
final session = await client.createSyncSession(
  await resolveDatabasePath('tasks_$userId.db'),
  isDebugMode: kDebugMode,
  persistentUserId: userId,
);
```

The `resolveDatabasePath` helper comes from [Create a session](https://docs.serverpod.dev/concepts/data-and-the-database/database/client-side-database.md#create-a-session).

The session works like any [client-side database](https://docs.serverpod.dev/concepts/data-and-the-database/database/client-side-database.md) session, including device migrations and the extra files web apps need. These points are specific to offline sync:

- **Writes go to the user's [personal space](https://docs.serverpod.dev/concepts/data-and-the-database/database/offline-sync/spaces.md#personal-and-shared-spaces) by default.** Reads include every space the user belongs to. To write to a shared space, see [Share data with spaces](https://docs.serverpod.dev/concepts/data-and-the-database/database/offline-sync/spaces.md).
- **One file per user keeps accounts apart.** A file named after the user, like `tasks_$userId.db`, gives each account on the device its own data.
- **The database opens offline.** Only syncing needs the server.
- **The session type is `OfflineSyncDatabaseSession`.** Use that type, not `ClientDatabaseSession`, for fields and parameters that hold the session.
- **A watch updates when a sync brings in changes.** To keep a widget up to date, [watch](https://docs.serverpod.dev/concepts/data-and-the-database/database/crud.md#watching-rows) a query.

## Start the sync

Call `syncOnce` to sync once, for example on pull-to-refresh, or `syncContinuously` to keep syncing while the app runs:

```dart
// Sync once. Throws if the sync fails.
await client.offlineSync.syncOnce(session);

// Or keep syncing until you cancel.
final subscription = client.offlineSync.syncContinuously(session);
```

A continuous sync sends and receives changes as they happen, until you cancel it or the connection drops.

## See sync working

Make a change on one device and watch it reach another:

1. Sign in as the same user on two devices, such as two simulators.
2. Start the sync on both devices.
3. Add a task on one device. It appears on the other device after both have synced.

## Restart after the connection drops

A continuous sync stops when the connection drops, and it doesn't restart by itself. To find out when it stops, await `subscription.done`. The `await` throws if the sync failed. Start a new sync when the device is back online, or after a short pause:

```dart
import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:serverpod_offline_sync_client/serverpod_offline_sync_client.dart';

final updateRequired = ValueNotifier(false);
Object? _syncRun;
OfflineSyncSubscription? _subscription;
Completer<void>? _backOnline;

void _onConnectivityChanged(bool connected) {
  final backOnline = _backOnline;
  if (connected && backOnline != null && !backOnline.isCompleted) {
    backOnline.complete();
  }
}

Future<void> keepSyncing() async {
  final run = Object();
  _syncRun = run;
  client.connectivityMonitor?.addListener(_onConnectivityChanged);
  while (_syncRun == run) {
    final backOnline = _backOnline = Completer<void>();
    _subscription = client.offlineSync.syncContinuously(session);
    try {
      await _subscription!.done;
    } on OfflineSyncTablesHashMismatchException {
      // The app and the server have different synced schemas, so retrying
      // won't help. Show an "Update required to sync" message.
      updateRequired.value = true;
      return;
    } catch (_) {
      // The connection dropped or the sync failed.
    }
    if (_syncRun != run) return;
    // Try again when the device is back online, or after 5 seconds.
    await Future.any([
      backOnline.future,
      Future<void>.delayed(const Duration(seconds: 5)),
    ]);
  }
}

Future<void> stopSync() async {
  _syncRun = null;
  client.connectivityMonitor?.removeListener(_onConnectivityChanged);
  await _subscription?.cancel();
}
```

Call `keepSyncing` after the user signs in. It listens to the `FlutterConnectivityMonitor` that a new Serverpod Flutter app attaches to the client. A new sync starts as soon as the device is back online, or after 5 seconds if the server is still unreachable. Each call owns its run, so a quick sign-out and sign-in never leaves two syncs running. Show an update prompt while `updateRequired` is true.

## Close the database

When the user signs out, stop the sync before you close the session:

```dart
await stopSync();
await session.close();
```

## Troubleshooting

- **Sync fails with `ServerpodClientUnauthorized`.** The user isn't signed in, and sync only works for a signed-in user. Start the sync after the user signs in.
- **Sync fails with `OfflineSyncTablesHashMismatchException`.** The app and the server have different versions of the synced tables, because one of them is out of date. Update the one that's behind. See [Change a synced schema](https://docs.serverpod.dev/concepts/data-and-the-database/database/offline-sync/schema-changes.md).
- **Sync throws `This database is not an OfflineSyncDatabase`.** The session came from `createSession`, which opens a local database without sync. Open the database with `createSyncSession` instead.
- **A server write throws `No user clock found for transaction or persistent user ID`.** Your server code wrote to a synced table outside `transactionForUser`. Run the write inside `transactionForUser`, as [Read and write on the server](https://docs.serverpod.dev/concepts/data-and-the-database/database/offline-sync/spaces.md#read-and-write-on-the-server) shows.
- **Sync fails with `OfflineSyncIntegrityViolationException`.** The server or the device rejected a change it couldn't merge, such as a row whose id another space already uses. It recorded the reason in its `offline_sync_integrity_violations` table. When the server rejects the change, the device sees `ConnectionClosedException` instead, and its sync keeps failing. Check that table on the server and on the device for the row (`domainTableName`, `uuidRowId`) and the reason (`type`), then fix that row.

## Related

- [Offline sync](https://docs.serverpod.dev/concepts/data-and-the-database/database/offline-sync.md): how merges behave and the rules every write follows.
- [Model synced data](https://docs.serverpod.dev/concepts/data-and-the-database/database/offline-sync/modeling.md): the rules for synced tables, and patterns that keep edits from being lost, mixed, or duplicated.
- [Share data with spaces](https://docs.serverpod.dev/concepts/data-and-the-database/database/offline-sync/spaces.md): shared spaces, and how server code reads and writes synced tables.
- [Test offline sync](https://docs.serverpod.dev/concepts/data-and-the-database/database/offline-sync/testing.md): offline sync in `withServerpod` tests.
