# Signing keys rotation

> The active and previous signing keys with a button to rotate them.

- Block: [signing-keys](https://bettersupabase.com/blocks/signing-keys.md)
- Kind: component
- Data: loaded on the server through the block's client
- Page: https://bettersupabase.com/recipes/signing-keys-rotation

## Install the block

```bash
npx better-supabase add signing-keys
```

## Web (Next.js)

Add the shadcn components:

```bash
npx shadcn add alert badge button card empty skeleton table
```

From `apps/examples/nextjs/src/features/signing-keys/components/signing-keys-rotation.tsx` (https://github.com/ScaleDockHQ/better-supabase/blob/main/apps/examples/nextjs/src/features/signing-keys/components/signing-keys-rotation.tsx):

```tsx
type SigningKeysState =
  | { readonly kind: "ok"; readonly overview: SigningKeysOverview }
  | { readonly kind: "error" }
  | { readonly kind: "no-organization" };

async function loadSigningKeysState(): Promise<SigningKeysState> {
  try {
    const overview = await loadSigningKeys();

    return overview ? { kind: "ok", overview } : { kind: "no-organization" };
  } catch (error) {
    unstable_rethrow(error);

    return { kind: "error" };
  }
}

// oxlint-disable-next-line typescript/require-await -- a Server Action must be async, and refresh() returns nothing to await
async function retry() {
  "use server";
  refresh();
}

/**
 * Render inside `<Suspense>`: the organization's active signing key and
 * the retired ones still published, with a rotate button. The keys are
 * service-role only, so this checks `organization.update` before it reads.
 */
export async function SigningKeysRotation() {
  const [session, t] = await Promise.all([
    getSession(),
    getExtracted("signingKeys"),
  ]);

  if (!can(session, SIGNING_KEYS_PERMISSION)) {
    forbidden();
  }

  const state = await loadSigningKeysState();

  if (state.kind === "no-organization") {
    return null;
  }

  const rows =
    state.kind === "ok"
      ? [
          ...(state.overview.active
            ? [{ ...state.overview.active, active: true }]
            : []),
          ...state.overview.previous.map((key) => ({ ...key, active: false })),
        ]
      : [];

  return (
    <Card data-recipe="signing-keys-rotation">
      <CardHeader>
        <CardTitle>{t("Signing keys")}</CardTitle>
        <CardDescription>
          {t(
            "The keys that sign this organization's tokens. Private keys stay in Vault; receivers check signatures against the published JWKS.",
          )}
        </CardDescription>
        {rows.length > 0 ? (
          <CardAction>
            <RotateSigningKeyButton first={false} />
          </CardAction>
        ) : null}
      </CardHeader>
      <CardContent>
        {state.kind === "error" ? (
          <Alert variant="destructive">
            <TriangleAlertIcon />
            <AlertTitle>{t("The signing keys didn't load")}</AlertTitle>
            <AlertDescription>{t("Try again in a moment.")}</AlertDescription>
            <AlertAction>
              <form action={retry}>
                <Button size="sm" variant="outline" type="submit">
                  {t("Retry")}
                </Button>
              </form>
            </AlertAction>
          </Alert>
        ) : rows.length === 0 ? (
          <Empty className="border">
            <EmptyHeader>
              <EmptyMedia variant="icon">
                <KeyRoundIcon />
              </EmptyMedia>
              <EmptyTitle>{t("No signing key yet")}</EmptyTitle>
              <EmptyDescription>
                {t("Create one before the organization signs any tokens.")}
              </EmptyDescription>
            </EmptyHeader>
            <EmptyContent>
              <RotateSigningKeyButton first />
            </EmptyContent>
          </Empty>
        ) : (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t("Key ID")}</TableHead>
                <TableHead>{t("Algorithm")}</TableHead>
                <TableHead>{t("Status")}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {rows.map((key) => (
                <TableRow key={key.kid}>
                  <TableCell className="font-mono text-xs">{key.kid}</TableCell>
                  <TableCell className="text-sm">{key.algorithm}</TableCell>
                  <TableCell>
                    {key.active ? (
                      <Badge variant="success-light">{t("Active")}</Badge>
                    ) : (
                      <Badge variant="secondary">{t("Previous")}</Badge>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        )}
      </CardContent>
    </Card>
  );
}

export function SigningKeysRotationSkeleton() {
  return <Skeleton className="h-40 rounded-xl" aria-busy="true" />;
}
```

## Prompt

Paste this into a coding agent to build the recipe in your app.

### Web

```text
Build "Signing keys rotation" in a React web app that uses shadcn/ui components. The active and previous signing keys with a button to rotate them.

It uses the better-supabase `signing-keys` block (Signing keys). It loads its data on the server through the block's client.

Steps:

1. If the app doesn't have the block yet, add the SQL with `npx better-supabase add signing-keys` and apply the migration.
2. Add the shadcn components the recipe uses: `npx shadcn add alert badge button card empty skeleton table`.
3. The recipe needs no glue: it calls the block's client on the server.
4. Write the component. Load the data on the server with the block's client, starting from the recipe's snippet (`apps/examples/nextjs/src/features/signing-keys/components/signing-keys-rotation.tsx`). Adapt it to the app's existing components, styling and data loading instead of copying it as is.
5. Check the result against the recipe and the block's docs: it typechecks, it reads the same block data, and it handles the loading and empty states the snippet handles.

Read the full code first:

- Recipe: https://bettersupabase.com/recipes/signing-keys-rotation.md
- Block docs: https://bettersupabase.com/docs/blocks/signing-keys
```
