Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

adds unstyled add custom domains flow

Alaister Youngd55842612013
diff --git a/studio/components/interfaces/Settings/API/CustomDomainConfig.tsx b/studio/components/interfaces/Settings/API/CustomDomainConfig.tsx
index 85209c0c90c..15ea58b416c 100644
--- a/studio/components/interfaces/Settings/API/CustomDomainConfig.tsx
+++ b/studio/components/interfaces/Settings/API/CustomDomainConfig.tsx
@@ -1,20 +1,168 @@
-import { IconAlertCircle } from 'ui'
-
+import {
+ FormActions,
+ FormPanel,
+ FormSection,
+ FormSectionContent,
+ FormSectionLabel,
+} from 'components/ui/Forms'
import Panel from 'components/ui/Panel'
-import { useParams, useStore } from 'hooks'
+import { useProjectSettingsQuery } from 'data/config/project-settings-query'
+import { useCustomDomainActivateMutation } from 'data/custom-domains/custom-domains-activate-mutation'
+import { useCustomDomainCreateMutation } from 'data/custom-domains/custom-domains-create-mutation'
import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
+import { useCustomDomainReverifyMutation } from 'data/custom-domains/custom-domains-reverify-mutation'
+import { useParams, useStore } from 'hooks'
+import { Alert, Button, Form, IconAlertCircle, IconCloudLightning, IconRefreshCw, Input } from 'ui'
+import * as yup from 'yup'
+
+const FORM_ID = 'custom-domains-form'
+
+const schema = yup.object({
+ domain: yup.string().required('Custom domain is required'),
+})
const CustomDomainConfig = () => {
const { ui } = useStore()
const { ref } = useParams()
- const { isError, data } = useCustomDomainsQuery({ projectRef: ref })
+ const { isLoading: isSettingsLoading, data: settings } = useProjectSettingsQuery({
+ projectRef: ref,
+ })
+
+ const {
+ isLoading: isCustomDomainsLoading,
+ isError,
+ error,
+ isSuccess,
+ data,
+ } = useCustomDomainsQuery(
+ { projectRef: ref },
+ {
+ retry: false,
+ refetchOnWindowFocus: false,
+ }
+ )
+
+ const isLoading = isSettingsLoading || isCustomDomainsLoading
+
+ const isNoHostnameConfiguredError =
+ isError &&
+ (error as any)?.code === 400 &&
+ (error as any)?.message?.includes('custom hostname configuration')
+
+ const isUnknownError = isError && !isNoHostnameConfiguredError
+
+ const { mutateAsync: createCustomDomain } = useCustomDomainCreateMutation()
+
+ const onCreateCustomDomain = async (values: yup.InferType<typeof schema>) => {
+ if (!ref) {
+ throw new Error('Project ref is required')
+ }
+
+ try {
+ const something = await createCustomDomain({
+ projectRef: ref,
+ customDomain: values.domain,
+ })
+
+ console.log('something:', something)
+ } catch (error) {
+ console.log('asf error:', error)
+ }
+ }
+
+ const { mutate: reverifyCustomDomain, isLoading: isReverifyLoading } =
+ useCustomDomainReverifyMutation()
+
+ const onReverifyCustomDomain = () => {
+ if (!ref) {
+ throw new Error('Project ref is required')
+ }
+
+ reverifyCustomDomain({ projectRef: ref })
+ }
+
+ const { mutate: activateCustomDomain, isLoading: isActivateLoading } =
+ useCustomDomainActivateMutation()
+
+ const onActivateCustomDomain = () => {
+ if (!ref) {
+ throw new Error('Project ref is required')
+ }
+
+ activateCustomDomain({ projectRef: ref })
+ }
+
+ if (isNoHostnameConfiguredError) {
+ return (
+ <Form
+ id={FORM_ID}
+ initialValues={{ domain: '' }}
+ validationSchema={schema}
+ onSubmit={onCreateCustomDomain}
+ >
+ {({ isSubmitting, handleReset, values, initialValues }: any) => {
+ const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)
+
+ return (
+ <>
+ <FormPanel
+ disabled={true}
+ header={<p>Custom Domains</p>}
+ footer={
+ <div className="flex py-4 px-8">
+ <FormActions
+ form={FORM_ID}
+ isSubmitting={isSubmitting}
+ submitText="Add"
+ hasChanges={hasChanges}
+ handleReset={handleReset}
+ disabled={!true}
+ helper={
+ !true
+ ? "You need additional permissions to update your project's custom domain settings"
+ : undefined
+ }
+ />
+ </div>
+ }
+ >
+ <FormSection header={<FormSectionLabel>Add Custom Domain</FormSectionLabel>}>
+ <FormSectionContent loading={false}>
+ <Input
+ id="domain"
+ className="w-full"
+ type="text"
+ name="domain"
+ placeholder="subdomain.example.com"
+ />
+
+ <Alert
+ withIcon
+ variant="info"
+ title="Setup CNAME record before adding a custom domain"
+ >
+ Create a CNAME record in your DNS provider pointing to{' '}
+ <code>{settings?.autoApiService.app_config.endpoint ?? 'Loading...'}</code>,
+ then add your custom domain above.
+ </Alert>
+ </FormSectionContent>
+ </FormSection>
+ </FormPanel>
+ </>
+ )
+ }}
+ </Form>
+ )
+ }
return (
<>
- <Panel title={<h5 className="mb-0">Custom Domain</h5>}>
+ <Panel title={<h5 className="mb-0">Custom Domains</h5>}>
<Panel.Content className="space-y-6 border-t border-panel-border-interior-light dark:border-panel-border-interior-dark">
- {isError && (
+ {isLoading && <div>Loading...</div>}
+
+ {isUnknownError && (
<div className="flex items-center justify-center space-x-2 py-8">
<IconAlertCircle size={16} strokeWidth={1.5} />
<p className="text-sm text-scale-1100">
@@ -23,7 +171,64 @@ const CustomDomainConfig = () => {
</div>
)}
- <div>coming soon...</div>
+ {isSuccess && (
+ <div className="flex flex-col">
+ {data.customDomain.verification_errors?.includes(
+ 'custom hostname does not CNAME to this zone.'
+ ) && (
+ <div>
+ cname {data.customDomain.hostname}: {settings?.autoApiService.app_config.endpoint}
+ </div>
+ )}
+
+ {data.customDomain.ownership_verification && (
+ <div>
+ {data.customDomain.ownership_verification.type} -{' '}
+ {data.customDomain.ownership_verification.name}:{' '}
+ {data.customDomain.ownership_verification.value}
+ </div>
+ )}
+
+ {data.customDomain.ssl.status === 'pending_validation' && (
+ <div>
+ txt {data.customDomain.ssl.txt_name}: {data.customDomain.ssl.txt_value}
+ </div>
+ )}
+
+ <Button
+ icon={<IconRefreshCw />}
+ onClick={onReverifyCustomDomain}
+ loading={isReverifyLoading}
+ >
+ Verify
+ </Button>
+
+ {data.status === '4_origin_setup_completed' && (
+ <Button
+ icon={
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ viewBox="0 0 24 24"
+ strokeWidth={1}
+ stroke="currentColor"
+ className="w-4 h-4"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ d="M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z"
+ />
+ </svg>
+ }
+ onClick={onActivateCustomDomain}
+ loading={isActivateLoading}
+ >
+ Activate
+ </Button>
+ )}
+ </div>
+ )}
</Panel.Content>
</Panel>
diff --git a/studio/components/ui/Forms/FormActions.tsx b/studio/components/ui/Forms/FormActions.tsx
index ff5806e0802..d5f4789ceac 100644
--- a/studio/components/ui/Forms/FormActions.tsx
+++ b/studio/components/ui/Forms/FormActions.tsx
@@ -7,6 +7,7 @@ interface Props {
helper?: React.ReactNode // Helper text to show alongside actions
disabled?: boolean
isSubmitting?: boolean
+ submitText?: string
}
const FormActions = ({
@@ -16,6 +17,7 @@ const FormActions = ({
helper,
disabled = false,
isSubmitting,
+ submitText = 'Save',
}: Props) => {
const isDisabled = isSubmitting || disabled || (!hasChanges && hasChanges !== undefined)
@@ -39,7 +41,7 @@ const FormActions = ({
disabled={isDisabled}
loading={isSubmitting}
>
- Save
+ {submitText}
</Button>
</div>
</div>
diff --git a/studio/data/config/keys.ts b/studio/data/config/keys.ts
new file mode 100644
index 00000000000..875848a4247
--- /dev/null
+++ b/studio/data/config/keys.ts
@@ -0,0 +1,3 @@
+export const configKeys = {
+ settings: (projectRef: string | undefined) => ['projects', projectRef, 'settings'] as const,
+}
diff --git a/studio/data/config/project-settings-query.ts b/studio/data/config/project-settings-query.ts
new file mode 100644
index 00000000000..ad473e32e38
--- /dev/null
+++ b/studio/data/config/project-settings-query.ts
@@ -0,0 +1,122 @@
+import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'
+import { get } from 'lib/common/fetch'
+import { API_URL } from 'lib/constants'
+import { useCallback } from 'react'
+import { configKeys } from './keys'
+
+export type ProjectSettingsVariables = {
+ projectRef?: string
+}
+
+export type Project = {
+ id: number
+ name: string
+ ref: string
+ status: string
+ db_host: string
+ db_name: string
+ db_user: string
+ db_schema: string
+ db_port: number
+ db_ssl: boolean
+ services: Service[]
+}
+
+export type App = {
+ id: number
+ name: string
+}
+
+export type AppConfig = {
+ endpoint: string
+ db_schema: string
+ realtime_multitenant_enabled: boolean
+}
+
+export type Service = {
+ id: number
+ name: string
+ app_config: AppConfig
+ app: App
+ service_api_keys: ServiceApiKey[]
+}
+
+export type ServiceApiKey = {
+ api_key_encrypted: string
+ tags: string
+ name: string
+}
+
+export type AutoApiService = Service & {
+ endpoint: string
+ restUrl: string
+ project: Project
+ defaultApiKey: string
+ serviceApiKey: string
+}
+
+export type ProjectSettingsResponse = {
+ project: Project
+ autoApiService: AutoApiService
+}
+
+export async function getProjectSettings(
+ { projectRef }: ProjectSettingsVariables,
+ signal?: AbortSignal
+) {
+ if (!projectRef) {
+ throw new Error('projectRef is required')
+ }
+
+ const response = await get(`${API_URL}/props/project/${projectRef}/api`, {
+ signal,
+ })
+ if (response.error) {
+ throw response.error
+ }
+
+ return response as ProjectSettingsResponse
+}
+
+export type ProjectSettingsData = Awaited<ReturnType<typeof getProjectSettings>>
+export type ProjectSettingsError = unknown
+
+export const useProjectSettingsQuery = <TData = ProjectSettingsData>(
+ { projectRef }: ProjectSettingsVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseQueryOptions<ProjectSettingsData, ProjectSettingsError, TData> = {}
+) =>
+ useQuery<ProjectSettingsData, ProjectSettingsError, TData>(
+ configKeys.settings(projectRef),
+ ({ signal }) => getProjectSettings({ projectRef }, signal),
+ {
+ enabled: enabled && typeof projectRef !== 'undefined',
+ refetchInterval(data, query) {
+ if (!data) {
+ return false
+ }
+
+ const { autoApiService } = data as unknown as ProjectSettingsData
+
+ const apiKeys = autoApiService?.service_api_keys ?? []
+ const interval = apiKeys.length === 0 ? 2000 : 0
+
+ return interval
+ },
+ ...options,
+ }
+ )
+
+export const useProjectSettingsPrefetch = ({ projectRef }: ProjectSettingsVariables) => {
+ const client = useQueryClient()
+
+ return useCallback(() => {
+ if (projectRef) {
+ client.prefetchQuery(configKeys.settings(projectRef), ({ signal }) =>
+ getProjectSettings({ projectRef }, signal)
+ )
+ }
+ }, [projectRef])
+}
diff --git a/studio/data/custom-domains/custom-domains-activate-mutation.ts b/studio/data/custom-domains/custom-domains-activate-mutation.ts
new file mode 100644
index 00000000000..3e36c765187
--- /dev/null
+++ b/studio/data/custom-domains/custom-domains-activate-mutation.ts
@@ -0,0 +1,50 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { post } from 'lib/common/fetch'
+import { customDomainKeys } from './keys'
+
+export type CustomDomainActivateVariables = {
+ projectRef: string
+}
+
+export async function activateCustomDomain({ projectRef }: CustomDomainActivateVariables) {
+ if (!projectRef) {
+ throw new Error('projectRef is required')
+ }
+
+ const response = await post(
+ `${process.env.NEXT_PUBLIC_API_ADMIN_URL}/projects/${projectRef}/custom-hostname/activate`,
+ {}
+ )
+ if (response.error) {
+ throw response.error
+ }
+
+ console.log('activate response:', response)
+ return response
+}
+
+type CustomDomainActivateData = Awaited<ReturnType<typeof activateCustomDomain>>
+
+export const useCustomDomainActivateMutation = ({
+ onSuccess,
+ ...options
+}: Omit<
+ UseMutationOptions<CustomDomainActivateData, unknown, CustomDomainActivateVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<CustomDomainActivateData, unknown, CustomDomainActivateVariables>(
+ (vars) => activateCustomDomain(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+
+ await queryClient.invalidateQueries(customDomainKeys.list(projectRef))
+
+ await onSuccess?.(data, variables, context)
+ },
+ ...options,
+ }
+ )
+}
diff --git a/studio/data/custom-domains/custom-domains-create-mutation.ts b/studio/data/custom-domains/custom-domains-create-mutation.ts
new file mode 100644
index 00000000000..a5c414d773f
--- /dev/null
+++ b/studio/data/custom-domains/custom-domains-create-mutation.ts
@@ -0,0 +1,55 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { post } from 'lib/common/fetch'
+import { customDomainKeys } from './keys'
+
+export type CustomDomainCreateVariables = {
+ projectRef: string
+ customDomain: string
+}
+
+export async function createCustomDomain({
+ projectRef,
+ customDomain,
+}: CustomDomainCreateVariables) {
+ if (!projectRef) {
+ throw new Error('projectRef is required')
+ }
+
+ const response = await post(
+ `${process.env.NEXT_PUBLIC_API_ADMIN_URL}/projects/${projectRef}/custom-hostname/initialize`,
+ {
+ custom_hostname: customDomain,
+ }
+ )
+ if (response.error) {
+ throw response.error
+ }
+
+ return { customDomain }
+}
+
+type CustomDomainCreateData = Awaited<ReturnType<typeof createCustomDomain>>
+
+export const useCustomDomainCreateMutation = ({
+ onSuccess,
+ ...options
+}: Omit<
+ UseMutationOptions<CustomDomainCreateData, unknown, CustomDomainCreateVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<CustomDomainCreateData, unknown, CustomDomainCreateVariables>(
+ (vars) => createCustomDomain(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+
+ await queryClient.invalidateQueries(customDomainKeys.list(projectRef))
+
+ await onSuccess?.(data, variables, context)
+ },
+ ...options,
+ }
+ )
+}
diff --git a/studio/data/custom-domains/custom-domains-query.ts b/studio/data/custom-domains/custom-domains-query.ts
index 1efa9ff82bb..78c41c3426a 100644
--- a/studio/data/custom-domains/custom-domains-query.ts
+++ b/studio/data/custom-domains/custom-domains-query.ts
@@ -7,6 +7,61 @@ export type CustomDomainsVariables = {
projectRef?: string
}
+type CustomDomainStatus =
+ | '1_not_started'
+ | '2_initiated'
+ | '3_challenge_verified'
+ | '4_origin_setup_completed'
+ | '5_services_reconfigured'
+
+type Settings = {
+ http2: string
+ tls_1_3: string
+ min_tls_version: string
+}
+
+type Ssl = {
+ id: string
+ type: string
+ method: string
+ status: string
+ txt_name?: string
+ txt_value?: string
+ settings: Settings
+ wildcard: boolean
+ bundle_method: string
+ certificate_authority: string
+ validation_records?: {
+ status: string
+ txt_name: string
+ txt_value: string
+ }[]
+}
+
+type OwnershipVerification = {
+ name: string
+ type: string
+ value: string
+}
+
+type OwnershipVerificationHttp = {
+ http_url: string
+ http_body: string
+}
+
+export type CustomDomainResponse = {
+ id: string
+ ssl: Ssl
+ status: string
+ hostname: string
+ created_at: string
+ custom_metadata: any
+ verification_errors?: string[]
+ custom_origin_server: string
+ ownership_verification?: OwnershipVerification
+ ownership_verification_http?: OwnershipVerificationHttp
+}
+
export async function getCustomDomains(
{ projectRef }: CustomDomainsVariables,
signal?: AbortSignal
@@ -15,17 +70,27 @@ export async function getCustomDomains(
throw new Error('projectRef is required')
}
- const response = await get(
+ const response = (await get(
`${process.env.NEXT_PUBLIC_API_ADMIN_URL}/projects/${projectRef}/custom-hostname`,
{
signal,
}
- )
+ )) as {
+ data: {
+ errors: any[]
+ result: CustomDomainResponse
+ success: boolean
+ messages: any[]
+ }
+ status: CustomDomainStatus
+ error: unknown
+ }
+
if (response.error) {
throw response.error
}
- return { customDomains: response }
+ return { customDomain: response?.data?.result, status: response.status }
}
export type CustomDomainsData = Awaited<ReturnType<typeof getCustomDomains>>
diff --git a/studio/data/custom-domains/custom-domains-reverify-mutation.ts b/studio/data/custom-domains/custom-domains-reverify-mutation.ts
new file mode 100644
index 00000000000..8b7e2c8c671
--- /dev/null
+++ b/studio/data/custom-domains/custom-domains-reverify-mutation.ts
@@ -0,0 +1,49 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { post } from 'lib/common/fetch'
+import { customDomainKeys } from './keys'
+
+export type CustomDomainReverifyVariables = {
+ projectRef: string
+}
+
+export async function reverifyCustomDomain({ projectRef }: CustomDomainReverifyVariables) {
+ if (!projectRef) {
+ throw new Error('projectRef is required')
+ }
+
+ const response = await post(
+ `${process.env.NEXT_PUBLIC_API_ADMIN_URL}/projects/${projectRef}/custom-hostname/reverify`,
+ {}
+ )
+ if (response.error) {
+ throw response.error
+ }
+
+ return response
+}
+
+type CustomDomainReverifyData = Awaited<ReturnType<typeof reverifyCustomDomain>>
+
+export const useCustomDomainReverifyMutation = ({
+ onSuccess,
+ ...options
+}: Omit<
+ UseMutationOptions<CustomDomainReverifyData, unknown, CustomDomainReverifyVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<CustomDomainReverifyData, unknown, CustomDomainReverifyVariables>(
+ (vars) => reverifyCustomDomain(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+
+ await queryClient.invalidateQueries(customDomainKeys.list(projectRef))
+
+ await onSuccess?.(data, variables, context)
+ },
+ ...options,
+ }
+ )
+}