
# spring_boot_starter_supabase

`spring_boot_starter_supabase` connects a Spring for Dart application to a [Supabase](https://supabase.com) project, on a server and in a Flutter app. The project's database is reached through Spring Data repositories, its Auth through Spring Security, Realtime gives streams, Storage is a template and declared buckets, Edge Functions are declared interfaces.

## Why

A Supabase project is several services behind one address: a REST API over PostgreSQL, Auth, Realtime, Storage, Edge Functions. Each wants the project's key and the user's token on every call, and each has its own errors. The starter gives them the shape the rest of the application already has: repositories, `@PreAuthorize`, streams, beans with AOP. One bean, [`SupabaseCredentials`](credentials.md), gives every call its key and its token, so all parts act as the same user, and what a user may read and write is decided by the database (row-level security).

The client is the starter's own, over the `HttpTransport` and the WebSocket starter: it uses none of Supabase's packages, and it compiles to WebAssembly.

## Setup

```yaml
# pubspec.yaml
dependencies:
  spring_boot_starter_supabase: ^0.9.0

dev_dependencies:
  build_runner: ^2.17.0
  spring_core_dart_generator: ^0.9.0   # required: writes the repositories and the declared interfaces
```

One import: `package:spring_boot_starter_supabase/spring_boot_starter_supabase.dart` re-exports the data, cache, Feign, WebSocket and logging starters, `spring_security_core` and `spring_web_dart`. The starter does not depend on the security starters:

- a server that accepts the project's tokens adds [spring_boot_starter_security](../spring-boot-starter-security/index.md);
- a Flutter app that opens a provider's login window adds [spring_boot_starter_flutter_security](../spring-boot-starter-flutter-security/index.md).

## Example

```yaml
# lib/resources/application.yml
spring:
  supabase:
    url: https://abcd.supabase.co
    anon-key: ${SUPABASE_ANON_KEY}
```

```dart
@Table('todos')
class Todo {
  Todo({required this.title, this.done = false, this.id, this.createdAt});

  @Id()
  int? id;

  String title;
  bool done;
  DateTime? createdAt;
}

// A Spring Data repository: on the project's REST API, as the current user.
abstract interface class Todos implements ListCrudRepository<Todo, int> {
  Future<List<Todo>> findByDoneOrderByCreatedAtDesc(bool done);
}

@StorageBucket('avatars')
abstract interface class Avatars {
  @Upload('#{authentication.name}/avatar.png', upsert: true)
  Future<void> put(Uint8List bytes);
}

@EdgeFunctions()
abstract interface class Functions {
  @EdgeFunction('send-invite')
  Future<InviteResult> sendInvite(@RequestBody() Invite invite);
}

@Service()
class Account {
  Account(this.auth, this.todos);

  final SupabaseAuth auth;
  final Todos todos;

  Future<List<Todo>> open(String email, String password) async {
    await auth.signInWithPassword(email: email, password: password);
    // From here every call is made with the user's token.
    return todos.findByDoneOrderByCreatedAtDesc(false);
  }
}
```

The generator writes the beans of `Todos`, `Avatars` and `Functions`. The query is one request, `GET /rest/v1/todos?done=eq.false&order=created_at.desc`, with the anon key as `apikey` and the user's token as the bearer token.

## What starts

- **`supabaseCredentials`** ([`SupabaseCredentials`](credentials.md)) and **`supabaseHttp`** (`SupabaseHttp`), the client under every part: the key and the token on each call, no redirect followed, an observation per call (`supabase.rest`, `supabase.auth`, `supabase.storage`, `supabase.functions`), logs without keys, tokens or query values.
- **`supabaseDataStore`**, the [data store](data.md) named `supabase`, when `spring.supabase.url` is set. The build knows it too: a repository on it with `@Lock`, a SQL `@Query` or `@Transactional` fails the build, with the fix in the message (with only `spring.supabase.db.url` set the build cannot tell the default store, and the check is at startup).
- **`supabaseAuth`** and **`supabaseAuthAdmin`** ([sign-in](auth.md)), unless `spring.supabase.auth.enabled` is `false`. The admin API is on a server only (a module of the `server` platform): a Flutter app and a browser build have none of its code.
- **`supabaseRealtime`** ([Realtime](realtime.md)), **`storageTemplate`** ([Storage](storage.md)), and the factories that make the beans of the `@RealtimeChannel`, `@StorageBucket` and `@EdgeFunctions` interfaces.
- **`supabaseKeyGenerator`** and **`supabaseCacheResolver`** ([caches](cache.md)).
- **`supabaseStartup`**: it checks `spring.supabase.url`, says once how the repositories reach the database, and in a Flutter app warns about each key that ships in it.
- **On a server only** (a module of the `server` platform): the defaults of Spring Security's resource server ([security](security.md)).

Each bean steps back for a bean of its type declared by the application.

## What is inside

- [Configuration](configuration.md): every `spring.supabase.*` property.
- [Who a call is made as](credentials.md): `SupabaseCredentials`, `asServiceRole`, keys in a client application.
- [Data](data.md): the REST API or SQL, filters, pages, `@Version`, database functions with `@Procedure`, changes of rows, errors, row-level security.
- [Caches](cache.md): cache keys that carry the caller.
- [Security on a server](security.md): which tokens a server accepts, roles, the legacy secret.
- [Sign-in in a client application](auth.md): `SupabaseAuth`, the session, redirects and PKCE, the admin API.
- [Realtime](realtime.md): changes of rows, broadcast, presence, `@RealtimeChannel`.
- [Storage](storage.md): `StorageTemplate`, `@StorageBucket`, the path rules.
- [Edge Functions](functions.md): `@EdgeFunctions` interfaces.
- [An Edge Function in Dart](edge-function.md): a function of the project written with [spring_boot_starter_edge](../spring-boot-starter-edge/index.md).
- [Testing](testing.md): fake transports, and the levels of the package's own tests.

## Not there yet

- **Streamed and resumable uploads** (TUS): an upload is read whole before it is sent.
- **A `Resource` of a Storage object.**
- **`@MappedCollection`** on the REST API.
- **SpEL in the names of Edge Functions.**
- **A warning in the build's log** for a key in a Flutter app: the warning is at startup only.
- **A Supabase container** for an application's tests, and an example application.
- **Entities checked against the project's schema** at build time.
- In Auth: anonymous sign-in, multi-factor authentication, linking identities, SSO (SAML).

## Compared with Supabase's own packages

| `supabase_flutter` | Here |
|---|---|
| `Supabase.initialize(url:, anonKey:)` | `spring.supabase.url`, `spring.supabase.anon-key` |
| `supabase.from('todos').select().eq('done', false)` | a repository method, `findByDone(false)`; there is no query builder |
| `supabase.rpc('name', params: …)` | a repository method with `@Procedure('name')` ([Data](data.md#database-functions)) |
| `supabase.auth.signInWithPassword(…)` | `SupabaseAuth.signInWithPassword(…)`; the user is Spring Security's `Authentication` |
| `supabase.auth.onAuthStateChange` | `authenticationChanges`, `AuthenticationSuccessEvent`, `LogoutSuccessEvent` |
| `supabase.storage.from('avatars').upload(…)` | `StorageTemplate`, or a `@StorageBucket` interface |
| `supabase.functions.invoke('name')` | an `@EdgeFunctions` interface (a Feign client) |
| `supabase.from('todos').stream(primaryKey: ['id'])` | a repository method `watch…By`, a `Stream<List<Todo>>` kept up to date |
| `supabase.channel('room')…subscribe()` | `SupabaseRealtime.channel('room')` or a `@RealtimeChannel` interface: streams, joined while used |
| `AuthException`, `PostgrestException` | Spring Security's `AuthenticationException`s, the data starter's `DataAccessException`s |

- **One session**, Spring Security's: `@PreAuthorize`, the security context and every call to Supabase see the same user.
- **On a server too**: a request's bearer token is passed on to the database, and the resource server's settings come with the starter.
- **Cache keys carry the caller**, by default.

## In Spring (Java)

Spring has no Supabase support. The parts follow what Spring has for other services: Spring Data repositories, Spring Security's resource server and `Authentication`, `S3Template` of Spring Cloud AWS for Storage, Spring Cloud OpenFeign for the functions.

## See also

- [spring_boot_starter_data](../spring-boot-starter-data/index.md)
- [spring_boot_starter_security](../spring-boot-starter-security/index.md)
- [spring_security_core](../spring-security-core/index.md)
- [spring_boot_starter_websocket](../spring-boot-starter-websocket/index.md)
- [spring_boot_starter_feign](../spring-boot-starter-feign/index.md)
- [What a build contains](optimizations.md)
