Files
supabase/apps/studio/components/interfaces/APIKeys/CreateNewAPIKeysButton.tsx
T
Drew McLellan 433d95afd0 feat(studio): track usage on the API keys pages (#54070)
## Problem

Nothing is tracked on the API keys pages (new and legacy), so we can't
tell which keys people copy, how often they create or delete keys, or
how quickly projects disable legacy keys. Closes FE-5030.

## Solution

Adds five events, defined in `packages/common/telemetry-constants.ts`
and fired through `useTrack()`:

| Event | When | Properties |
| --- | --- | --- |
| `api_key_copied` | User copies a publishable, secret, or legacy
anon/service_role key with its Copy button. Keyboard copies aren't
counted. Not fired when blocked by permissions or when the copy fails. |
`keyType` |
| `api_key_reveal_clicked` | User reveals a secret or legacy
service_role key (not on hide) | `keyType` |
| `api_key_created` | Key created from the dialog, or by the first-time
setup (fires once per key) | `keyType`, `source` |
| `api_key_removed` | Key deleted after confirming in the modal |
`keyType` |
| `legacy_api_keys_updated` | Legacy keys disabled or re-enabled |
`enabled` |

- Create, delete, and legacy toggle fire in the mutation hook's
`onSuccess`, so failed attempts aren't counted and the event still fires
if the component unmounts mid-request. They're attributed to the
mutation's own project. Copy and reveal fire in the click handler.
- Delete is tracked in `SecretAPIKeys` / `PublishableAPIKeys`, where the
confirm modal and mutation live, not in the dropdown item.
- No key names or values in properties.
- `data-attr` added to the copy, reveal, create, delete, and docs
controls (static strings; Studio's PostHog autocapture is currently off,
so these send nothing today). `DocsButton` gets an optional `data-attr`
prop.
- `ui-patterns` `Input` gets optional `onReveal` and `onCopied`
callbacks. `onCopied` fires only for the Copy button, so legacy and new
keys count copies the same way.
- The empty-state sample keys are `inert`, so their buttons don't copy
or track.
- New `getLegacyApiKeyType` helper maps the legacy `anon` /
`service_role` tags to the event's `keyType`.

Tests cover copy, reveal, the no-event-on-hide and denied-grant cases,
the legacy toggle, and the key-type helper. Success paths for the create
dialogs and delete aren't covered.

## How to test

- [ ] Open `/project/[ref]/settings/api-keys`, copy a publishable and a
secret key, reveal a secret key, and check `api_key_copied` and
`api_key_reveal_clicked` in PostHog (staging) with the expected
`keyType`
- [ ] Create and delete a publishable and a secret key and check
`api_key_created` / `api_key_removed`
- [ ] On the legacy page, copy anon and service_role, reveal
service_role, then disable and re-enable the keys and check
`legacy_api_keys_updated`
2026-11-26 11:24:05 +00:00

131 lines
4.1 KiB
TypeScript

import { useParams } from 'common'
import { useState } from 'react'
import { toast } from 'sonner'
import {
AlertDialog,
AlertDialogAction,
AlertDialogBody,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { useAPIKeyCreateMutation } from '@/data/api-keys/api-key-create-mutation'
import { getWriteGrantToastMessage, getWriteGrantTooltip, useGrant } from '@/lib/grants'
import { useTrack } from '@/lib/telemetry/track'
export const CreateNewAPIKeysButton = () => {
const { ref: projectRef } = useParams()
const track = useTrack()
const [createKeysDialogOpen, setCreateKeysDialogOpen] = useState(false)
const [error, setError] = useState<string | null>(null)
const createGrant = useGrant('POST /v1/projects/{ref}/api-keys', { projectRef })
const { mutateAsync: createAPIKey } = useAPIKeyCreateMutation({ onError: () => {} })
const handleCreateNewApiKeys = async () => {
if (!projectRef) return
if (!createGrant.grant) {
toast.error(getWriteGrantToastMessage(createGrant.status, 'create', 'API keys'))
return
}
try {
setError(null)
// Create publishable key
try {
await createAPIKey({
projectRef,
grant: createGrant.grant,
type: 'publishable',
name: 'default',
})
track(
'api_key_created',
{ keyType: 'publishable', source: 'initial_setup' },
{ project: projectRef }
)
} catch (error: any) {
setError(`Failed to create the default publishable key: ${error.message}`)
throw error
}
// Create secret key
try {
await createAPIKey({
projectRef,
grant: createGrant.grant,
type: 'secret',
name: 'default',
})
track(
'api_key_created',
{ keyType: 'secret', source: 'initial_setup' },
{ project: projectRef }
)
} catch (error: any) {
setError(
`The default publishable key was created, but the default secret key failed: ${error.message}`
)
throw error
}
setCreateKeysDialogOpen(false)
toast.success('Successfully created a new set of API keys!')
} catch (error) {
console.error('Failed to create API keys:', error)
throw error
}
}
return (
<AlertDialog open={createKeysDialogOpen} onOpenChange={setCreateKeysDialogOpen}>
<ButtonTooltip
variant="primary"
onClick={() => setCreateKeysDialogOpen(true)}
disabled={createGrant.status !== 'granted'}
tooltip={{
content: {
side: 'bottom',
text: getWriteGrantTooltip(createGrant.status, 'create', 'API keys'),
},
}}
>
Create new API keys
</ButtonTooltip>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Create new API keys</AlertDialogTitle>
<AlertDialogDescription>
This will create a default publishable key and a default secret key both named{' '}
<code className="break-keep!">default</code>. These keys are required to connect your
application to your Supabase project. Your existing legacy API keys (
<code className="break-keep!">anon</code> and{' '}
<code className="break-keep!">service_role</code>) are not affected and remain valid
until you disable them in a separate step.
</AlertDialogDescription>
</AlertDialogHeader>
{error && (
<AlertDialogBody>
<Admonition type="destructive" title="Unable to create API keys" description={error} />
</AlertDialogBody>
)}
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction data-attr="api-key-create-initial" onClick={handleCreateNewApiKeys}>
Create keys
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}