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(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 ( setCreateKeysDialogOpen(true)} disabled={createGrant.status !== 'granted'} tooltip={{ content: { side: 'bottom', text: getWriteGrantTooltip(createGrant.status, 'create', 'API keys'), }, }} > Create new API keys Create new API keys This will create a default publishable key and a default secret key both named{' '} default. These keys are required to connect your application to your Supabase project. Your existing legacy API keys ( anon and{' '} service_role) are not affected and remain valid until you disable them in a separate step. {error && ( )} Cancel Create keys ) }