
# A function from an empty directory to Supabase

A Supabase Edge Function written in Dart, step by step: a small REST API
over a table of the project, run on a laptop first, then deployed. Every
step below was run as written, against the Supabase CLI's local stack;
the last step (the deploy to a hosted project) uses the CLI's documented
commands and was not.

What you need: the Dart SDK, the [Supabase CLI](https://supabase.com/docs/guides/local-development/cli/getting-started)
and, for the local stack, Docker.

## 1. The project

```bash
mkdir notes_function && cd notes_function
supabase init                  # makes supabase/config.toml
mkdir -p bin lib/src lib/resources test supabase/migrations
```

`pubspec.yaml`:

```yaml
name: notes_function
publish_to: none

environment:
  sdk: ^3.13.0

dependencies:
  spring_boot_starter_edge: ^0.9.0       # the function, with the web starter
  spring_boot_starter_security: ^0.9.0   # checks the project's tokens
  spring_boot_starter_supabase: ^0.9.0   # the project's tables as repositories

dev_dependencies:
  build_runner: ^2.17.0
  spring_core_dart_generator: ^0.9.0
  test: ^1.33.0
```

```bash
dart pub get
```

## 2. The application

`bin/main.dart`, the whole entry point:

```dart
import 'package:spring_boot_starter_edge/spring_boot_starter_edge.dart';

import 'spring_gen/main.spring.dart';

@SpringBootApplication()
void main() => runFetchApplication(() => springApplication);
```

`lib/src/note.dart`, a table and its repository:

```dart
import 'package:spring_boot_starter_supabase/spring_boot_starter_supabase.dart';

/// A row of the table `notes`.
@Introspected()
@Table('notes')
class Note {
  Note({required this.text, this.id});

  @Id()
  int? id;

  @NotBlank()
  String text;
}

/// The table through the project's REST API, as the caller: the policy of
/// the table decides which rows a user sees.
abstract interface class Notes implements ListCrudRepository<Note, int> {}
```

`lib/src/notes_controller.dart`, the endpoints and who may call them:

```dart
import 'package:notes_function/src/note.dart';
import 'package:spring_boot_starter_security/spring_boot_starter_security.dart';

@RestController()
class NotesController {
  NotesController(this.notes);

  final Notes notes;

  /// Open to everyone.
  @GetMapping('/health')
  Map<String, Object?> health() => {'status': 'UP'};

  /// The caller's notes.
  @GetMapping('/notes')
  Future<List<Note>> list() => notes.findAll();

  @PostMapping('/notes')
  @ResponseStatus(HttpStatus.created)
  Future<Note> add(@RequestBody() @Valid() Note note) => notes.save(note);

  /// Who calls, as read from the checked token.
  @GetMapping('/me')
  Map<String, Object?> me(Authentication caller) => {'id': caller.name};
}

@Configuration()
class SecurityConfig {
  @Bean()
  SecurityFilterChain api(HttpSecurity http) => http
      .authorizeHttpRequests(
        (auth) => auth
            .requestMatchers('/health')
            .permitAll()
            .anyRequest()
            .authenticated(),
      )
      .sessionManagement(
        (session) =>
            session.sessionCreationPolicy(SessionCreationPolicy.stateless),
      )
      .csrf((csrf) => csrf.disable())
      .oauth2ResourceServer((server) => server.jwt())
      .build();
}
```

The bearer tokens are the access tokens of the project's users: the
Supabase starter gives the resource server the project's keys, issuer
and audience. The function writes no rule about whose notes are whose:
it passes the caller's token on, and the table's policy decides.

`lib/resources/application.yml`:

```yaml
spring:
  application:
    name: notes
  main:
    banner-mode: off
  # In the function these come from the platform; here for `dart run`.
  supabase:
    url: ${SUPABASE_URL:http://127.0.0.1:54321}
    anon-key: ${SUPABASE_ANON_KEY:}
```

`supabase/migrations/20260101000000_notes.sql`, the table with its
policy:

```sql
create table public.notes (
  id bigint generated by default as identity primary key,
  text text not null,
  owner uuid not null default auth.uid()
);

alter table public.notes enable row level security;

create policy own_notes on public.notes
  for all to authenticated
  using (owner = (select auth.uid()))
  with check (owner = (select auth.uid()));

grant select, insert, update, delete on public.notes to authenticated;
```

Generate the application's code (again after every change of its beans):

```bash
dart run build_runner build
```

## 3. Run it as a server

The same `main` on the Dart VM is an ordinary server: the fastest way to
write and debug.

```bash
SERVER_PORT=8089 dart run bin/main.dart
curl localhost:8089/health        # {"status":"UP"}
curl -i localhost:8089/notes      # 401: no token
```

## 4. A test

`test/function_test.dart` calls the application as the platform does,
without a platform:

```dart
import 'package:spring_boot_starter_edge/spring_boot_starter_edge.dart';
import 'package:test/test.dart';

import '../bin/spring_gen/main.spring.dart';

void main() {
  final function = FetchApplication(() => springApplication);
  tearDownAll(function.close);

  Future<int> status(String path) async => (await function.fetch(
    FetchRequest('GET', Uri.parse('https://example.com$path')),
  )).status;

  test('health is open, the notes are not', () async {
    expect(await status('/health'), 200);
    expect(await status('/notes'), 401);
  });
}
```

```bash
dart test
```

## 5. Run it as a function, locally

Tell the platform that the application checks the tokens itself, in
`supabase/config.toml`. Without it the gateway answers 401 (`Missing
authorization header`) to every request without a token, also to
`/health`:

```toml
[functions.notes]
verify_jwt = false

# The local stack only: its functions reach the project at
# http://kong:8000, while its tokens name the address the clients use.
[edge_runtime.secrets]
SPRING_SUPABASE_AUTH_ISSUER = "http://127.0.0.1:54321/auth/v1"
```

Build the function into `supabase/functions/notes/`, then start the
stack (the stack must find the function when it starts; after the first
time a new build is picked up without a restart, once the instance that
served the old one has gone idle, about half a minute):

```bash
dart run spring_boot_starter_edge:build --platform supabase --name notes
supabase start
```

`supabase start` prints the address and the keys; `supabase status`
prints them again. With the anon key in `ANON_KEY`:

```bash
URL=http://127.0.0.1:54321
curl $URL/functions/v1/notes/health

# A user of the project, and their access token.
TOKEN=$(curl -s "$URL/auth/v1/signup" -H "apikey: $ANON_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"email": "ada@example.com", "password": "correct horse"}' | jq -r .access_token)

curl $URL/functions/v1/notes/me -H "Authorization: Bearer $TOKEN"
curl $URL/functions/v1/notes/notes -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' -d '{"text": "first"}'      # 201
curl $URL/functions/v1/notes/notes -H "Authorization: Bearer $TOKEN"
```

The name of the function (`notes`) is the first segment of its address
and not part of the mappings: `@GetMapping('/health')` answers
`/functions/v1/notes/health`. Another user who asks for the notes gets
an empty list: the policy of the table, not the function, hides them.

The function's log (its start, what the starter warns about, the errors)
is the log of the stack's Edge Runtime: `docker logs -f
supabase_edge_runtime_<project id>`.

Add `supabase/functions/notes/` to `.gitignore`: it is built, not
written.

## 6. Deploy it

```bash
supabase login
supabase link --project-ref <ref>          # <ref>.supabase.co

supabase db push                           # the migration of step 2
dart run spring_boot_starter_edge:build --platform supabase --name notes
supabase functions deploy notes
```

```bash
curl https://<ref>.supabase.co/functions/v1/notes/health
```

A hosted project needs nothing of `[edge_runtime.secrets]`: there the
functions and the tokens name the same address. What the application
reads from its environment besides the project's own variables is a
secret of the project: `supabase secrets set NAME=value`.

To deploy on every push instead:

```bash
dart run spring_boot_starter_edge:workflow --platform supabase --name notes
```

writes `.github/workflows/deploy-notes.yml`; give the repository the
secrets `SUPABASE_ACCESS_TOKEN` and `SUPABASE_PROJECT_REF`.

## What next

- [Deploying a function](deploying.md): the same for Cloudflare and AWS,
  WebAssembly (`--target wasm`), secrets, schedules.
- [What a function does differently](differences.md): no timers between
  requests (`@Scheduled`), nothing kept in memory between instances
  (caches, sessions, an in-memory rate limiter); what to use instead.
- A rate limit shared by every instance: `@RateLimiter` with the
  project's database function, as
  [`example/supabase/function`](https://github.com/farum-azula/spring_core_dart/tree/main/example/supabase/function)
  does.
