# How to Protect Supabase Service Role Key in Next.js & Client Apps

> The Supabase service_role key bypasses all Row Level Security (RLS) rules. If leaked, an attacker has unrestricted admin access to your database. RealComposer keeps your service role key in the Secret Vault and exposes locked-down endpoints with strict output filtering.

- Canonical page: https://realcomposer.com/recipes/protect-supabase-service-role-key-nextjs
- Client platform: Next.js / React
- Upstream services: Supabase
- Category: Security & Secret Vault
- JSON version: https://realcomposer.com/recipes/protect-supabase-service-role-key-nextjs.json
- Install in RealComposer (free plan, pre-fills this pipeline): https://realcomposer.com/dashboard/pipelines/new?recipe=protect-supabase-service-role-key-nextjs&via=agent

## Problem: Service Role Keys Bypass All Database Security

Accidentally importing a service_role key into client components gives users full database permissions.

- Complete database exfiltration
- Bypassing Row Level Security (RLS)
- Malicious record updates

## Solution steps

1. **Keep Service Role Key in Vault**: Store SUPABASE_SERVICE_ROLE_KEY in RealComposer.

2. **Project Only Safe Fields**: Strip sensitive columns like password_hash or internal audit fields.

## Pipeline config

Import this config into a RealComposer pipeline. `{{secrets.NAME}}` values are read from the encrypted Secret Vault at request time, so the client never sees them.

```json
{
  "name": "Supabase Admin Proxy",
  "method": "GET",
  "cacheTtlSeconds": 30,
  "steps": [
    {
      "stepKey": "userQuery",
      "upstreamUrlTemplate": "https://xyz.supabase.co/rest/v1/users?id=eq.{{query.userId}}",
      "httpMethod": "GET",
      "headersTemplate": {
        "apikey": "{{secrets.SUPABASE_SERVICE_ROLE_KEY}}",
        "Authorization": "Bearer {{secrets.SUPABASE_SERVICE_ROLE_KEY}}"
      },
      "timeoutMs": 3000
    }
  ],
  "outputMapping": {
    "version": 1,
    "fields": [
      {
        "targetPath": "userId",
        "sourceStep": "userQuery",
        "sourcePath": "0.id"
      },
      {
        "targetPath": "email",
        "sourceStep": "userQuery",
        "sourcePath": "0.email"
      },
      {
        "targetPath": "role",
        "sourceStep": "userQuery",
        "sourcePath": "0.role"
      }
    ]
  }
}
```

## Call the pipeline

```bash
curl -X GET "https://realcomposer.com/v1/acme/user-admin-view?userId=u_1"
```

## Payload before and after

Raw upstream response:

```json
[
  {
    "id": "u_1",
    "email": "user@example.com",
    "role": "admin",
    "password_hash": "$2b$12$...",
    "ssn_last4": "1234"
  }
]
```

Slimmed RealComposer response:

```json
{
  "userId": "u_1",
  "email": "user@example.com",
  "role": "admin"
}
```

## FAQ

### Why use RealComposer instead of Supabase Edge Functions?

RealComposer requires zero code or Deno deployments and provides visual field trimming.
