# Working with branches

Learn how to develop and manage your Supabase branches

Learn how to develop and manage your Supabase branches.

This guide covers how to work with Supabase branches effectively, including migration management, seeding behavior, and development workflows.

## Subscribing to notifications

You can subscribe to webhook notifications when an action run completes on a persistent branch. The payload format follows the [webhook standards](https://www.standardwebhooks.com).

```json
{
  "type": "run.completed",
  "timestamp": "2025-10-17T02:27:18.705861793Z",
  "data": {
    "project_ref": "xuqpsshjxdecrwdyuxvs",
    "details_url": "/dashboard/project/xuqpsshjxdecrwdyuxvs/branches",
    "action_run": {
      "id": "d5f8b4298d0a4d37b99e255c7837e7af",
      "created_at": "2025-10-17T02:27:10.133329324Z",
      "steps": [
        {
          "name": "clone",
          "status": "exited",
          "updated_at": "2025-10-17T02:27:10.788435466Z"
        },
        {
          "name": "pull",
          "status": "exited",
          "updated_at": "2025-10-17T02:27:11.701742857Z"
        },
        {
          "name": "health",
          "status": "exited",
          "updated_at": "2025-10-17T02:27:12.79205717Z"
        },
        {
          "name": "configure",
          "status": "exited",
          "updated_at": "2025-10-17T02:27:13.726839657Z"
        },
        {
          "name": "migrate",
          "status": "exited",
          "updated_at": "2025-10-17T02:27:14.97017507Z"
        },
        {
          "name": "seed",
          "status": "exited",
          "updated_at": "2025-10-17T02:27:15.637684921Z"
        },
        {
          "name": "deploy",
          "status": "exited",
          "updated_at": "2025-10-17T02:27:18.604193114Z"
        }
      ]
    }
  }
}
```

We recommend registering a single webhooks processor that dispatches events to downstream services based on the payload type. The easiest way to do that is by deploying an Edge Function. For example, the following Edge Function listens for run completed events to notify a Slack channel.

```typescript name=supabase/functions/notify-slack/index.ts
// Setup type definitions for built-in Supabase Runtime APIs
import 'jsr:@supabase/functions-js/edge-runtime.d.ts'

console.log('Branching notification booted!')
const slack = Deno.env.get('SLACK_WEBHOOK_URL') ?? ''

Deno.serve(async (request) => {
  const body = await request.json()
  const blocks = [
    {
      type: 'header',
      text: {
        type: 'plain_text',
        text: `Action run ${body.data.action_run.failure ? 'failed' : 'completed'}`,
        emoji: true,
      },
    },
    {
      type: 'section',
      fields: [
        {
          type: 'mrkdwn',
          text: `*Branch ref:*\n${body.data.project_ref}`,
        },
        {
          type: 'mrkdwn',
          text: `*Run ID:*\n${body.data.action_run.id}`,
        },
      ],
    },
    {
      type: 'section',
      fields: [
        {
          type: 'mrkdwn',
          text: `*Started at:*\n${body.data.action_run.created_at}`,
        },
        {
          type: 'mrkdwn',
          text: `*Completed at:*\n${body.timestamp}`,
        },
      ],
    },
    {
      type: 'section',
      text: {
        type: 'mrkdwn',
        text: `<${body.data.details_url}|View logs>`,
      },
    },
  ]
  const resp = await fetch(slack, {
    method: 'POST',
    body: JSON.stringify({
      blocks,
    }),
  })
  const message = await resp.text()
  return new Response(
    JSON.stringify({
      message,
    }),
    {
      status: 200,
    }
  )
})
```

1. **Setup Slack webhook URL**

Create a [Slack webhook URL](https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/) and set it as Function secrets.

```markdown
supabase secrets set --project-ref <branch-ref> SLACK_WEBHOOK_URL=<your-webhook-url>
```

2. **Deploy your webhooks processor**

Create and deploy an Edge Function to process webhooks.

```markdown
supabase functions deploy --project-ref <branch-ref> --use-api notify-slack
```

3. **Update branch notification URL**

Update the notification URL of your target branch to point to your Edge Function.

```markdown
supabase branches update <branch-ref> --notify-url https://<branch-ref>.supabase.co/functions/v1/notify-slack
```

After completing the steps above, you should receive a Slack message whenever an action run completes on your target branch.

## Migration and seeding behavior

Migrations are run in sequential order. Each migration builds upon the previous one.

The preview branch inherits the migration history of your base project, so it only applies migrations that haven't been run yet. This can create an issue when rolling back migrations.

### Default privileges on branches

New branches are secure by default. They are created without [default privileges](/docs/guides/api/securing-your-api#default-privileges) on the `public` schema, regardless of the setting on your base project. New tables, functions, and sequences on a branch require explicit grants before `anon`, `authenticated`, or `service_role` can reach them through the Data API.

Your migrations control whether a branch re-enables these privileges. If your base project has default privileges enabled and your migration history was initialized by Supabase Branching or the Supabase CLI, the initial migration already contains the `alter default privileges` statements that grant access on `public`. Running it on a new branch restores the same access your base project has, so no changes are needed.

Two cases require manual intervention:

- You manage migrations outside Supabase and want to [keep default privileges enabled](#keep-default-privileges-enabled) on branches.
- You use Supabase managed migrations and want to [revoke default privileges](#revoke-default-privileges) on your base project and branches.

#### Keep default privileges enabled

If your migration history was not initialized by Supabase Branching or the Supabase CLI, your initial migration doesn't grant default privileges, so new branches start without them. To restore the same access your base project has:

1. **Turn on default privileges on your base project**

Open the [Data API settings](/dashboard/project/_/integrations/data_api/settings) in the Supabase Dashboard and turn on **Default privileges for new entities**.

2. **Add grants to your initial migration**

Insert the following statements at the start of your initial migration file. Subsequent migrations then inherit these privileges, so the final database state is unchanged.

```sql
alter default privileges for role postgres in schema public grant usage, select, update on sequences to anon, authenticated, service_role;
alter default privileges for role postgres in schema public grant execute on functions to anon, authenticated, service_role;
alter default privileges for role postgres in schema public grant select, insert, update, delete on tables to anon, authenticated, service_role;
```

3. **Repair the migration history of your base project**

Mark the updated migration as applied so it isn't rerun on your base project. See [Diagnosing and fixing sync errors](/docs/guides/deployment/database-migrations#diagnosing-and-fixing-sync-errors).

```bash
supabase migration repair --status applied <migration-timestamp>
```

#### Revoke default privileges

For improved security, we recommend not exposing the `public` schema automatically on your base project either. If your initial migration was generated by Supabase Branching or the Supabase CLI, it re-grants default privileges when it runs on a branch. To revoke them on your base project and branches:

1. **Turn off default privileges on your base project**

Open the [Data API settings](/dashboard/project/_/integrations/data_api/settings) in the Supabase Dashboard and turn off **Default privileges for new entities**.

2. **Add a new migration that revokes the grants**

Create a new migration file with the Supabase CLI. Don't edit the initial migration, because that affects subsequent migrations in your history.

```bash
supabase migration new revoke_default_privileges
```

Add the following statements to the generated file:

```sql
alter default privileges for role postgres in schema public revoke select, insert, update, delete on tables from anon, authenticated, service_role;
alter default privileges for role postgres in schema public revoke execute on functions from anon, authenticated, service_role, public;
alter default privileges for role postgres in schema public revoke usage, select, update on sequences from anon, authenticated, service_role;
```

3. **Commit and push**

Commit the new migration file and push it to your Git repository. The migration runs on your base project when merged and on every new branch, so both start without default privileges.

### Using ORM or custom seed scripts

If you want to use your own ORM for managing migrations and seed scripts, you will need to run them in GitHub Actions after the preview branch is ready. The branch credentials can be fetched using the following example GHA workflow.

```yaml name=.github/workflows/custom-orm.yaml
name: Custom ORM

on:
  pull_request:
    types:
      - opened
      - reopened
      - synchronize
    branches:
      - main
    paths:
      - 'supabase/**'

jobs:
  wait:
    runs-on: ubuntu-latest
    outputs:
      status: ${{ steps.check.outputs.conclusion }}
    steps:
      - uses: fountainhead/action-wait-for-check@v1.2.0
        id: check
        with:
          checkName: Supabase Preview
          ref: ${{ github.event.pull_request.head.sha || github.sha }}
          token: ${{ secrets.GITHUB_TOKEN }}

  migrate:
    needs:
      - wait
    if: ${{ needs.wait.outputs.status == 'success' }}
    runs-on: ubuntu-latest
    env:
      SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}
      SUPABASE_PROJECT_ID: ${{ secrets.SUPABASE_PROJECT_ID }}
    steps:
      - uses: supabase/setup-cli@v1
        with:
          version: latest
      - run: supabase --experimental branches get "$GITHUB_HEAD_REF" -o env >> $GITHUB_ENV
      - name: Custom ORM migration
        run: psql "$POSTGRES_URL_NON_POOLING" -c 'select 1'
```

### Rolling back migrations

You might want to roll back changes you've made in an earlier migration change. For example, you may have pushed a migration file containing schema changes you no longer want.

To fix this, push the latest changes, then delete the preview branch in Supabase and reopen it.

The new preview branch is a fresh clone of your base project and is reseeded from the `./supabase/seed.sql` file by default. Any additional data changes made on the old preview branch are lost.

To rerun migrations that your base project has already applied, reset the branch from the Supabase dashboard instead. A reset reruns all migrations in sequential order and drops existing data on the branch.

### Seeding behavior

Your Preview Branches are seeded with sample data using the same as [local seeding behavior](/docs/guides/local-development/seeding-your-database).

The database is only seeded once, when the preview branch is created. To rerun seeding, delete the preview branch and recreate it by closing, and reopening your pull request.

## Developing with branches

You can develop with branches using either local or remote development workflows.

### Local development workflow

1. Create a new Git branch for your feature
2. Make schema changes using the Supabase CLI
3. Generate migration files with `supabase db diff`
4. Test your changes locally
5. Commit and push to GitHub
6. Open a pull request to create a preview branch

If your project uses [declarative schemas](/docs/guides/local-development/declarative-database-schemas), edit your files in `supabase/schemas/` and generate migrations with `supabase db schema declarative sync` instead of `supabase db diff`, which on `pg-delta` never uses your schema files as its baseline. If your project hasn't enabled `pg-delta`, follow [Declarative schemas on the legacy `migra` engine](/docs/guides/local-development/declarative-database-schemas#declarative-schemas-on-the-legacy-migra-engine) instead. Branching applies only committed migration files, so commit the schema files and the generated migrations together.

### Remote development workflow

1. Create a preview branch in the Supabase dashboard
2. Switch to the branch using the branch dropdown
3. Make schema changes in the dashboard
4. Pull changes locally using `supabase db pull`
5. Commit the generated migration files
6. Push to your Git repository

## Managing branch environments

### Switching between branches

Use the branch dropdown in the Supabase dashboard to switch between different branches. Each branch has its own:

- Database instance
- API endpoints
- Authentication settings
- Storage buckets

### Accessing branch credentials

Each branch has unique credentials that you can find in the dashboard:

1. Switch to your desired branch
2. Navigate to Settings > API
3. Copy the branch-specific URLs and keys

### Branch isolation

Branches are completely isolated from each other. Changes made in one branch don't affect others, including:

- Database schema and data
- Storage objects
- Edge Functions
- Auth configurations

## Next steps

- Learn about [branch configuration](/docs/guides/deployment/branching/configuration)
- Explore [integrations](/docs/guides/deployment/branching/integrations)
- Review [troubleshooting guide](/docs/guides/deployment/branching/troubleshooting)
