# 2. Connect hosted Supabase

> Link Supabase CLI to the correct project, review hosted migrations, and enable the custom access-token hook.

# Connect hosted Supabase

Link the repository to the intended hosted project, then prove the target is correct before applying any migration.

## Link and inspect

From the application root, authenticate and link using the project's normal CLI workflow. Discover the installed CLI's current syntax with `--help` if a command differs from the examples.

```bash
npx supabase --version
npx supabase link --help
npx supabase link --project-ref <project-ref>
npx supabase migration list --linked
```

Before continuing, compare the linked project reference with the value recorded in step 1. Do not rely on a remembered project name or the last project used on the machine.

## Preview the migration

Review the linked dry run:

```bash
npx supabase db push --linked --dry-run
```

Read the migration list and SQL changes. Stop if the dry run contains an unexpected migration, destructive statement, project reference, or schema owner.

Take an environment-appropriate database backup before the first production push or any migration that changes existing data.

## Apply and verify

Apply only the reviewed migrations:

```bash
npx supabase db push --linked
npx supabase migration list --linked
```

Regenerate types from the project's supported workflow if the hosted schema differs from the last locally generated types. Commit schema migrations and generated types together when the repository's ownership rules require it.

## Enable the access-token hook

The canonical migration installs `app.custom_access_token_hook`. After that migration exists in the hosted database:

1. Open **Authentication → Hooks** in the hosted Supabase project.
2. Select the custom access-token hook.
3. Choose `app.custom_access_token_hook`.
4. Save the setting.

The `[auth.hook.custom_access_token]` entry in local `supabase/config.toml` does not enable this hosted setting.

After changing roles or application metadata used by the hook, refresh the user's token or sign in again before expecting new claims. JWT claims are not retroactively rewritten in an already issued access token.

## Data API and RLS check

Confirm every table exposed through the Data API has Row Level Security enabled and policies matching its ownership model. Data API exposure and RLS are separate controls: exposure determines whether a role can reach the table; RLS determines which rows it can access.

Do not solve access errors by exposing private schemas, granting broad table access, or adding `SECURITY DEFINER` without reviewing the security model.

## Completion check

- The linked project reference matches the intended hosted project.
- The linked and local migration histories agree.
- The custom access-token hook is selected in the hosted Dashboard.
- No unexpected object is publicly exposed.

Next: [Configure environment variables](./03-environment-variables.md).
