Skip to content

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

Extract project creation form into its own component (#47957)

Joshen Lim22b3419a281c
diff --git a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.tsx b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.tsx
index e3a6a51075c..e6f16ba25c0 100644
--- a/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.tsx
+++ b/apps/studio/components/interfaces/Account/AccessTokens/Scoped/ViewTokenSheet.tsx
@@ -22,6 +22,7 @@ import { formatAccessText, getRealAccess } from '../AccessToken.utils'
import { useOrgAndProjectData } from '../hooks/useOrgAndProjectData'
import { DocsButton } from '@/components/ui/DocsButton'
import { useScopedAccessTokenQuery } from '@/data/scoped-access-tokens/scoped-access-token-query'
+import { DOCS_URL } from '@/lib/constants'
interface ViewTokenSheetProps {
visible: boolean
@@ -110,7 +111,7 @@ export function ViewTokenSheet({ visible, tokenId, onClose }: ViewTokenSheetProp
<p className="truncate" title={`Manage access for ${token?.name}`}>
View access for {token?.name}
</p>
- <DocsButton href="https://supabase.com/docs/reference/api/introduction" />
+ <DocsButton href={`${DOCS_URL}/reference/api/introduction`} />
</SheetHeader>
<ScrollArea className="flex-1 max-h-[calc(100vh-60px)]">
<div className="space-y-8 px-5 sm:px-6 py-6">
diff --git a/apps/studio/components/interfaces/Auth/AuthProvidersForm/index.tsx b/apps/studio/components/interfaces/Auth/AuthProvidersForm/index.tsx
index 9d801843c98..4950b329c37 100644
--- a/apps/studio/components/interfaces/Auth/AuthProvidersForm/index.tsx
+++ b/apps/studio/components/interfaces/Auth/AuthProvidersForm/index.tsx
@@ -18,6 +18,7 @@ import { AlertError } from '@/components/ui/AlertError'
import { ResourceList } from '@/components/ui/Resource/ResourceList'
import { HorizontalShimmerWithIcon } from '@/components/ui/Shimmers'
import { useAuthConfigQuery } from '@/data/auth/auth-config-query'
+import { DOCS_URL } from '@/lib/constants'
export const AuthProvidersForm = () => {
const { ref: projectRef } = useParams()
@@ -59,7 +60,7 @@ export const AuthProvidersForm = () => {
hour.
</p>
<Button asChild variant="default" className="w-min" icon={<ExternalLink />}>
- <Link href="https://supabase.com/docs/guides/platform/going-into-prod#security">
+ <Link href={`${DOCS_URL}/guides/platform/going-into-prod#security`}>
View security recommendations
</Link>
</Button>
@@ -89,17 +90,17 @@ export const AuthProvidersForm = () => {
: provider
let isActive = false
if (providerSchema.title === 'SAML 2.0') {
- isActive = authConfig && (authConfig as any)['SAML_ENABLED']
+ isActive = authConfig && authConfig['SAML_ENABLED']
} else if (providerSchema.title === 'LinkedIn (OIDC)') {
- isActive = authConfig && (authConfig as any)['EXTERNAL_LINKEDIN_OIDC_ENABLED']
+ isActive = authConfig && authConfig['EXTERNAL_LINKEDIN_OIDC_ENABLED']
} else if (providerSchema.title === 'Slack (OIDC)') {
- isActive = authConfig && (authConfig as any)['EXTERNAL_SLACK_OIDC_ENABLED']
+ isActive = authConfig && authConfig['EXTERNAL_SLACK_OIDC_ENABLED']
} else if (providerSchema.title.includes('Web3')) {
- isActive = authConfig && (authConfig as any)['EXTERNAL_WEB3_SOLANA_ENABLED']
+ isActive = authConfig && authConfig['EXTERNAL_WEB3_SOLANA_ENABLED']
} else if (providerSchema.title.includes('X / Twitter (OAuth 2.0)')) {
isActive = authConfig && (authConfig as any)['EXTERNAL_X_ENABLED']
} else if (providerSchema.title === 'Twitter (Deprecated)') {
- isActive = authConfig && (authConfig as any)['EXTERNAL_TWITTER_ENABLED']
+ isActive = authConfig && authConfig['EXTERNAL_TWITTER_ENABLED']
} else {
isActive =
authConfig &&
diff --git a/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsx b/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsx
index aa472c7d04c..947e24b4c75 100644
--- a/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsx
+++ b/apps/studio/components/interfaces/ConnectSheet/ConnectStepsSection.tsx
@@ -286,10 +286,7 @@ export function ConnectStepsSection({ steps, state, projectKeys }: ConnectStepsS
title="MCP for self-hosted Supabase requires extra setup"
description="The configuration below points at the hosted Supabase MCP server. To use MCP against your self-hosted instance, follow the self-hosted MCP guide."
actions={[
- <DocsButton
- key="docs"
- href="https://supabase.com/docs/guides/self-hosting/enable-mcp"
- />,
+ <DocsButton key="docs" href={`${DOCS_URL}/guides/self-hosting/enable-mcp`} />,
]}
/>
)}
diff --git a/apps/studio/components/interfaces/ConnectSheet/content/steps/direct-connection/content.tsx b/apps/studio/components/interfaces/ConnectSheet/content/steps/direct-connection/content.tsx
index 64687afd842..6c1be4ba4b9 100644
--- a/apps/studio/components/interfaces/ConnectSheet/content/steps/direct-connection/content.tsx
+++ b/apps/studio/components/interfaces/ConnectSheet/content/steps/direct-connection/content.tsx
@@ -28,12 +28,14 @@ import {
} from '@/components/interfaces/ConnectSheet/ConnectionString.utils'
import { PasswordEncodingNote } from '@/components/interfaces/ConnectSheet/PasswordEncodingNote'
import { ResetDbPasswordDialog } from '@/components/interfaces/Settings/Database/DatabaseSettings/ResetDbPasswordDialog'
+import { InlineLink } from '@/components/ui/InlineLink'
import { usePgbouncerConfigQuery } from '@/data/database/pgbouncer-config-query'
import { useSupavisorConfigurationQuery } from '@/data/database/supavisor-configuration-query'
import { useReadReplicasQuery } from '@/data/read-replicas/replicas-query'
import { useProjectAddonsQuery } from '@/data/subscriptions/project-addons-query'
import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'
import { useIsHighAvailability } from '@/hooks/misc/useSelectedProject'
+import { DOCS_URL } from '@/lib/constants'
import { pluckObjectFields } from '@/lib/helpers'
import { useTrack } from '@/lib/telemetry/track'
@@ -275,14 +277,11 @@ function DirectConnectionContent({ state, deploymentMode }: StepContentProps) {
{showSelfHostedDirectNotice && (
<p className="text-sm text-foreground-light">
Manually{' '}
- <a
- href="https://supabase.com/docs/guides/self-hosting/docker#exposing-your-postgres-database"
- target="_blank"
- rel="noopener noreferrer"
- className="underline hover:text-foreground"
+ <InlineLink
+ href={`${DOCS_URL}/guides/self-hosting/docker#exposing-your-postgres-database`}
>
configurable
- </a>{' '}
+ </InlineLink>{' '}
for self-hosted Supabase.
</p>
)}
diff --git a/apps/studio/components/interfaces/ErrorHandling/README.md b/apps/studio/components/interfaces/ErrorHandling/README.md
index dda0f17e2ab..41b1067dbab 100644
--- a/apps/studio/components/interfaces/ErrorHandling/README.md
+++ b/apps/studio/components/interfaces/ErrorHandling/README.md
@@ -73,6 +73,7 @@ import {
FixWithAITroubleshootingSection,
TroubleshootingGuideSection,
} from '../TroubleshootingSections'
+import { DOCS_URL } from '@/lib/constants'
const ERROR_TYPE = 'your-error'
const BUILD_PROMPT = () => `Describe the issue for the AI assistant.`
@@ -89,7 +90,7 @@ export function YourErrorTroubleshooting() {
<TroubleshootingGuideSection
number={1}
errorType={ERROR_TYPE}
- href="https://supabase.com/docs/guides/..."
+ href={`${DOCS_URL}/guides/...`}
/>
<FixWithAITroubleshootingSection
number={2}
diff --git a/apps/studio/components/interfaces/ErrorHandling/errorMappings/ConnectionTimeout.tsx b/apps/studio/components/interfaces/ErrorHandling/errorMappings/ConnectionTimeout.tsx
index 7ad79acc3b7..48aa5738e5c 100644
--- a/apps/studio/components/interfaces/ErrorHandling/errorMappings/ConnectionTimeout.tsx
+++ b/apps/studio/components/interfaces/ErrorHandling/errorMappings/ConnectionTimeout.tsx
@@ -5,6 +5,7 @@ import {
TroubleshootingGuideSection,
} from '../TroubleshootingSections'
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
+import { DOCS_URL } from '@/lib/constants'
import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state'
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
@@ -30,7 +31,7 @@ export function ConnectionTimeoutTroubleshooting() {
<TroubleshootingGuideSection
number={2}
errorType={ERROR_TYPE}
- href="https://supabase.com/docs/guides/troubleshooting/failed-to-run-sql-query-connection-terminated-due-to-connection-timeout"
+ href={`${DOCS_URL}/guides/troubleshooting/failed-to-run-sql-query-connection-terminated-due-to-connection-timeout`}
description="Follow step-by-step instructions for diagnosing connection timeout issues."
/>
<FixWithAITroubleshootingSection
diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.utils.ts b/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.utils.ts
index 4fe81af6f92..6012a7c4f33 100644
--- a/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.utils.ts
+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.utils.ts
@@ -8,6 +8,7 @@ import {
unixMicroToIsoTimestamp,
} from '@/components/interfaces/Settings/Logs/Logs.utils'
import type { AlertErrorProps } from '@/components/ui/AlertError'
+import { DOCS_URL } from '@/lib/constants'
dayjs.extend(relativeTime)
@@ -72,7 +73,7 @@ export const getDisplayErrorMessage = (group: RecentErrorGroup): string => {
return summarizeErrorMessage(group.message)
}
-const TROUBLESHOOTING_DOCS_BASE = 'https://supabase.com/docs/guides/troubleshooting'
+const TROUBLESHOOTING_DOCS_BASE = `${DOCS_URL}/guides/troubleshooting`
export const buildTroubleshootingDocsUrl = ({ statusCode }: { statusCode?: string }): string => {
const numericStatusCode = Number(statusCode)
diff --git a/apps/studio/components/interfaces/Integrations/GraphQL/constants.ts b/apps/studio/components/interfaces/Integrations/GraphQL/constants.ts
index e5e4ef531d7..96224e2be00 100644
--- a/apps/studio/components/interfaces/Integrations/GraphQL/constants.ts
+++ b/apps/studio/components/interfaces/Integrations/GraphQL/constants.ts
@@ -1,3 +1,5 @@
+import { DOCS_URL } from '@/lib/constants'
+
export const PG_GRAPHQL_EXTENSION_NAME = 'pg_graphql'
/**
@@ -7,4 +9,4 @@ export const PG_GRAPHQL_EXTENSION_NAME = 'pg_graphql'
*/
export const DEFAULT_INTROSPECTION_SCHEMA = 'public'
-export const PG_GRAPHQL_CONFIG_DOCS_URL = 'https://supabase.com/docs/guides/graphql#supabase-studio'
+export const PG_GRAPHQL_CONFIG_DOCS_URL = `${DOCS_URL}/guides/graphql#supabase-studio`
diff --git a/apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx b/apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx
index fc1a8981af1..f6fe9c81b13 100644
--- a/apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx
+++ b/apps/studio/components/interfaces/JwtSecrets/jwt-settings.tsx
@@ -72,6 +72,7 @@ import { useJwtSecretUpdatingStatusQuery } from '@/data/config/jwt-secret-updati
import { useProjectPostgrestConfigQuery } from '@/data/config/project-postgrest-config-query'
import { useLegacyJWTSigningKeyQuery } from '@/data/jwt-signing-keys/legacy-jwt-signing-key-query'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
+import { DOCS_URL } from '@/lib/constants'
import { uuidv4 } from '@/lib/helpers'
const MAX_JWT_EXP = 604800
@@ -504,9 +505,9 @@ export const JWTSettings = () => {
{disableLegacyJwtSecretRotation ? (
<Button variant="default" icon={<ExternalLink className="size-4" />} asChild>
<Link
- href="https://supabase.com/docs/guides/auth/signing-keys#getting-started"
+ href={`${DOCS_URL}/guides/auth/signing-keys#getting-started`}
target="_blank"
- rel="noreferrer"
+ rel="noopener noreferrer"
>
Read the full migration guide
</Link>
diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreationForm.tsx b/apps/studio/components/interfaces/ProjectCreation/ProjectCreationForm.tsx
new file mode 100644
index 00000000000..78c064b7d20
--- /dev/null
+++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreationForm.tsx
@@ -0,0 +1,688 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useFeatureFlags, useFlag, useParams } from 'common'
+import Link from 'next/link'
+import { useRouter } from 'next/router'
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { useForm, useFormState } from 'react-hook-form'
+import { type CloudProvider } from 'shared-data'
+import { toast } from 'sonner'
+import { Button, Form, useWatch } from 'ui'
+import { Admonition } from 'ui-patterns/admonition'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+import { z } from 'zod'
+
+import { AdvancedConfiguration } from './AdvancedConfiguration'
+import { ComputeSizeSelector } from './ComputeSizeSelector'
+import { DatabasePasswordInput } from './DatabasePasswordInput'
+import { DisabledWarningDueToIncident } from './DisabledWarningDueToIncident'
+import { FreeProjectLimitWarning } from './FreeProjectLimitWarning'
+import { InternalOnlyConfiguration } from './InternalOnlyConfiguration'
+import { OrganizationSelector } from './OrganizationSelector'
+import { extractPostgresVersionDetails } from './PostgresVersionSelector'
+import { sizes } from './ProjectCreation.constants'
+import { FormSchema } from './ProjectCreation.schema'
+import {
+ instanceLabel,
+ monthlyInstancePrice,
+ smartRegionToExactRegion,
+} from './ProjectCreation.utils'
+import { ProjectCreationFooter } from './ProjectCreationFooter'
+import { ProjectNameInput } from './ProjectNameInput'
+import { RegionSelector } from './RegionSelector'
+import { SecurityOptions } from './SecurityOptions'
+import { AUTO_ENABLE_RLS_EVENT_TRIGGER_SQL } from '@/components/interfaces/Database/Triggers/EventTriggersList/EventTriggers.constants'
+import {
+ GitHubRepositoryField,
+ useGitHubRepositoryOptions,
+} from '@/components/interfaces/Settings/Integrations/GithubIntegration/GitHubRepositoryField'
+import Panel from '@/components/ui/Panel'
+import { useAvailableOrioleImageVersion } from '@/data/config/project-creation-postgres-versions-query'
+import { useOverdueInvoicesQuery } from '@/data/invoices/invoices-overdue-query'
+import { useDefaultRegionQuery } from '@/data/misc/get-default-region-query'
+import { useAuthorizedAppsQuery } from '@/data/oauth/authorized-apps-query'
+import { useFreeProjectLimitCheckQuery } from '@/data/organizations/free-project-limit-check-query'
+import { useOrganizationAvailableRegionsQuery } from '@/data/organizations/organization-available-regions-query'
+import { useOrganizationsQuery } from '@/data/organizations/organizations-query'
+import { DesiredInstanceSize } from '@/data/projects/new-project.constants'
+import {
+ OrgProject,
+ useOrgProjectsInfiniteQuery,
+} from '@/data/projects/org-projects-infinite-query'
+import {
+ ProjectCreateVariables,
+ useProjectCreateMutation,
+} from '@/data/projects/project-create-mutation'
+import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'
+import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
+import {
+ isInDataApiRevokeTreatment,
+ useDataApiRevokeOnCreateDefaultEnabled,
+} from '@/hooks/misc/useDataApiRevokeOnCreateDefault'
+import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
+import { useLastVisitedOrganization } from '@/hooks/misc/useLastVisitedOrganization'
+import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
+import { usePHFlag } from '@/hooks/ui/useFlag'
+import { DOCS_URL, PROJECT_STATUS, PROVIDERS, useDefaultProvider } from '@/lib/constants'
+import { useProfile } from '@/lib/profile'
+import { classifyApiError, classifyValidationError } from '@/lib/telemetry/funnel-errors'
+import { useTrack } from '@/lib/telemetry/track'
+import { useTrackFunnelError } from '@/lib/telemetry/use-track-funnel-error'
+
+const sizesWithNoCostConfirmationRequired: DesiredInstanceSize[] = ['micro', 'small']
+
+export const ProjectCreationForm = () => {
+ const track = useTrack()
+ const trackFunnelError = useTrackFunnelError()
+ const router = useRouter()
+ const { slug, projectName } = useParams()
+ const defaultProvider = useDefaultProvider()
+ const { profile } = useProfile()
+
+ const { data: currentOrg } = useSelectedOrganizationQuery()
+ const isFreePlan = currentOrg?.plan?.id === 'free'
+ const canChooseInstanceSize = !isFreePlan
+
+ const { lastVisitedOrganization } = useLastVisitedOrganization()
+ const { can: isAdmin } = useAsyncCheckPermissions(PermissionAction.CREATE, 'projects')
+ const { can: canCreateGitHubConnection } = useAsyncCheckPermissions(
+ PermissionAction.CREATE,
+ 'integrations.github_connections'
+ )
+ const showAdvancedConfig = useIsFeatureEnabled('project_creation:show_advanced_config')
+ const { hasAccess: hasAccessToGitHubIntegration } = useCheckEntitlements(
+ 'integrations.github_connections'
+ )
+
+ const { hasLoaded: flagsLoaded } = useFeatureFlags()
+ const projectCreationDisabled = useFlag('disableProjectCreationAndUpdate')
+ const showInternalOnlyConfiguration = useFlag('newProjectInternalOnlyConfiguration')
+
+ // Read the raw flag for telemetry — coerce-undefined-to-false would record false for
+ // users whose flags haven't loaded yet. The raw value preserves undefined (omitted from
+ // PostHog) so we only record an actual value (boolean true/false, or a variant string
+ // like 'test'/'control' post-multivariate migration) once the flag has resolved.
+ const dataApiRevokeOnCreateDefaultFlag = usePHFlag<boolean | string>(
+ 'dataApiRevokeOnCreateDefault'
+ )
+ const isDataApiRevokeOnCreateDefault = useDataApiRevokeOnCreateDefaultEnabled()
+
+ const isNotOnHigherPlan = !['team', 'enterprise', 'platform'].includes(currentOrg?.plan.id ?? '')
+
+ const [allProjects, setAllProjects] = useState<OrgProject[] | undefined>(undefined)
+ const [isComputeCostsConfirmationModalVisible, setIsComputeCostsConfirmationModalVisible] =
+ useState(false)
+
+ const form = useForm<z.infer<typeof FormSchema>>({
+ resolver: zodResolver(FormSchema),
+ mode: 'onChange',
+ defaultValues: {
+ organization: slug,
+ projectName: projectName || '',
+ highAvailability: false,
+ postgresVersion: '',
+ instanceType: '',
+ cloudProvider: PROVIDERS[defaultProvider].id,
+ dbPass: '',
+ dbPassStrength: 0,
+ dbPassStrengthMessage: '',
+ dbRegion: undefined,
+ githubRepositoryId: '',
+ githubInstallationId: undefined,
+ githubRepositoryName: '',
+ instanceSize: canChooseInstanceSize ? sizes[0] : undefined,
+ dataApi: true,
+ dataApiDefaultPrivileges: !isDataApiRevokeOnCreateDefault,
+ enableRlsEventTrigger: false,
+ postgresVersionSelection: '',
+ useOrioleDb: false,
+ },
+ })
+ const { getFieldState, resetField, setValue } = form
+ const {
+ instanceSize: watchedInstanceSize,
+ cloudProvider,
+ dbRegion,
+ githubRepositoryName,
+ organization,
+ projectName: watchedProjectName,
+ highAvailability,
+ } = useWatch({ control: form.control })
+ const { dirtyFields } = useFormState(form)
+ const isDbRegionDirty = dirtyFields.dbRegion
+ const smartRegionEnabled = cloudProvider !== 'AWS_NIMBUS'
+
+ // Read dirty state during render rather than depending on form.formState in the
+ // effect — form.formState is a Proxy that gets a new reference every render, which
+ // would re-fire this effect after each setValue and trigger an infinite loop.
+ const isDataApiDefaultPrivilegesDirty = getFieldState(
+ 'dataApiDefaultPrivileges',
+ form.formState
+ ).isDirty
+
+ // [Charis] Since the form is updated in a useEffect, there is an edge case
+ // when switching from free to paid, where canChooseInstanceSize is true for
+ // an in-between render, but watchedInstanceSize is still undefined from the
+ // form state carried over from the free plan. To avoid this, we set a
+ // default instance size in this case.
+ const instanceSize = canChooseInstanceSize ? (watchedInstanceSize ?? sizes[0]) : undefined
+ const { data: membersExceededLimit = [] } = useFreeProjectLimitCheckQuery(
+ { slug },
+ { enabled: isFreePlan }
+ )
+ const hasMembersExceedingFreeTierLimit = membersExceededLimit.length > 0
+ const freePlanWithExceedingLimits = isFreePlan && hasMembersExceedingFreeTierLimit
+
+ const { data: organizations = [], isSuccess: isOrganizationsSuccess } = useOrganizationsQuery()
+ const isEmptyOrganizations = isOrganizationsSuccess && organizations.length <= 0
+
+ const { data: approvedOAuthApps = [] } = useAuthorizedAppsQuery(
+ { slug },
+ { enabled: !isFreePlan && slug !== '_' }
+ )
+ const hasOAuthApps = approvedOAuthApps.length > 0
+
+ const { data: allOverdueInvoices = [] } = useOverdueInvoicesQuery({
+ enabled: isNotOnHigherPlan,
+ })
+ const overdueInvoices = allOverdueInvoices.filter((x) => x.organization_id === currentOrg?.id)
+ const hasOutstandingInvoices = isNotOnHigherPlan && overdueInvoices.length > 0
+
+ const { data: orgProjectsFromApi } = useOrgProjectsInfiniteQuery({ slug: currentOrg?.slug })
+ const allOrgProjects = useMemo(
+ () => orgProjectsFromApi?.pages.flatMap((page) => page.projects),
+ [orgProjectsFromApi?.pages]
+ )
+ const organizationProjects =
+ allProjects?.filter((project) => project.status !== PROJECT_STATUS.INACTIVE) ?? []
+ const availableComputeCredits = organizationProjects.length === 0 ? 10 : 0
+ const additionalMonthlySpend = isFreePlan
+ ? 0
+ : monthlyInstancePrice(instanceSize) - availableComputeCredits
+
+ const selectedCloudProvider = cloudProvider as CloudProvider
+ const { data: autoDefaultRegion, error: defaultRegionError } = useDefaultRegionQuery(
+ {
+ cloudProvider: selectedCloudProvider,
+ },
+ {
+ enabled: flagsLoaded && !smartRegionEnabled,
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchInterval: false,
+ refetchOnReconnect: false,
+ retry: false,
+ }
+ )
+
+ const { data: availableRegionsData, error: availableRegionsError } =
+ useOrganizationAvailableRegionsQuery(
+ {
+ slug: slug,
+ cloudProvider: PROVIDERS[cloudProvider as CloudProvider].id,
+ desiredInstanceSize: instanceSize as DesiredInstanceSize,
+ },
+ {
+ enabled: flagsLoaded && smartRegionEnabled,
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchInterval: false,
+ refetchOnReconnect: false,
+ }
+ )
+
+ const recommendedSmartRegion = smartRegionEnabled
+ ? availableRegionsData?.recommendations.smartGroup.name
+ : ''
+
+ const fixedDefaultRegion = PROVIDERS[selectedCloudProvider].default_region.displayName
+ const regionError = smartRegionEnabled ? availableRegionsError : defaultRegionError
+ const defaultRegion = smartRegionEnabled
+ ? availableRegionsData?.recommendations.smartGroup.name
+ : (autoDefaultRegion ?? fixedDefaultRegion)
+
+ const canCreateProject = isAdmin && !freePlanWithExceedingLimits && !hasOutstandingInvoices
+ const canConfigureGitHubOnCreate =
+ canCreateProject && hasAccessToGitHubIntegration && canCreateGitHubConnection
+
+ const dbRegionExact = smartRegionToExactRegion(dbRegion ?? '')
+
+ const availableOrioleVersion = useAvailableOrioleImageVersion(
+ {
+ cloudProvider: cloudProvider as CloudProvider,
+ dbRegion: smartRegionEnabled ? dbRegionExact : (dbRegion ?? ''),
+ organizationSlug: organization,
+ },
+ { enabled: currentOrg !== null }
+ )
+
+ const userPrimaryEmail = profile?.primary_email?.toLowerCase()
+ const isUserAtFreeProjectLimit = userPrimaryEmail
+ ? membersExceededLimit.some(
+ (member) => member.primary_email?.toLowerCase() === userPrimaryEmail
+ )
+ : false
+ const shouldShowFreeProjectInfo = !!currentOrg && !isFreePlan && !isUserAtFreeProjectLimit
+ const {
+ gitHubAuthorization,
+ githubRepos,
+ hasPartialResponseDueToSSO,
+ isLoading: isLoadingRepositoryOptions,
+ refetch: refetchRepositoryOptions,
+ } = useGitHubRepositoryOptions()
+
+ const {
+ mutate: createProject,
+ isPending: isCreatingNewProject,
+ isSuccess: isSuccessNewProject,
+ } = useProjectCreateMutation({
+ onSuccess: (res) => {
+ track(
+ 'project_creation_simple_version_submitted',
+ {
+ surface: 'main',
+ instanceSize: form.getValues('instanceSize'),
+ enableRlsEventTrigger: form.getValues('enableRlsEventTrigger'),
+ dataApiEnabled: form.getValues('dataApi'),
+ dataApiDefaultPrivilegesGranted: form.getValues('dataApiDefaultPrivileges'),
+ useOrioleDb: form.getValues('useOrioleDb'),
+ ...(dataApiRevokeOnCreateDefaultFlag !== undefined && {
+ dataApiRevokeOnCreateDefaultEnabled: dataApiRevokeOnCreateDefaultFlag,
+ }),
+ },
+ {
+ project: res.ref,
+ organization: res.organization_slug,
+ }
+ )
+ router.push(`/project/${res.ref}`)
+ },
+ onError: (error) => {
+ const toastId = toast.error(`Failed to create new project: ${error.message}`)
+ trackFunnelError(
+ 'project_creation',
+ classifyApiError('project_creation', error),
+ 'toast',
+ toastId
+ )
+ },
+ })
+
+ const onSubmitWithComputeCostsConfirmation = async (values: z.infer<typeof FormSchema>) => {
+ const launchingLargerInstance =
+ values.instanceSize &&
+ !sizesWithNoCostConfirmationRequired.includes(values.instanceSize as DesiredInstanceSize)
+
+ if (additionalMonthlySpend > 0 && (hasOAuthApps || launchingLargerInstance)) {
+ track('project_creation_simple_version_confirm_modal_opened', {
+ instanceSize: values.instanceSize,
+ })
+ setIsComputeCostsConfirmationModalVisible(true)
+ } else {
+ await onSubmit(values)
+ }
+ }
+
+ const onSubmit = async (values: z.infer<typeof FormSchema>) => {
+ if (!currentOrg) return console.error('Unable to retrieve current organization')
+
+ const {
+ cloudProvider,
+ projectName,
+ highAvailability,
+ dbPass,
+ dbRegion,
+ postgresVersion,
+ instanceType,
+ instanceSize,
+ dataApi,
+ dataApiDefaultPrivileges,
+ enableRlsEventTrigger,
+ postgresVersionSelection,
+ useOrioleDb,
+ githubInstallationId,
+ githubRepositoryId,
+ } = values
+
+ if (useOrioleDb && !availableOrioleVersion) {
+ const toastId = toast.error('No available OrioleDB image found, only Postgres is available')
+ trackFunnelError(
+ 'project_creation',
+ { errorCategory: 'validation', errorReason: 'oriole_unavailable' },
+ 'toast',
+ toastId
+ )
+ return
+ }
+
+ const { postgresEngine, releaseChannel } =
+ extractPostgresVersionDetails(postgresVersionSelection)
+
+ const { smartGroup = [], specific = [] } = availableRegionsData?.all ?? {}
+ const selectedRegion = smartRegionEnabled
+ ? (smartGroup.find((x) => x.name === dbRegion) ?? specific.find((x) => x.name === dbRegion))
+ : undefined
+ const parsedGitHubRepositoryId =
+ githubRepositoryId.length > 0 ? Number(githubRepositoryId) : undefined
+ const shouldIncludeGitHubFields =
+ githubInstallationId !== undefined && Number.isFinite(parsedGitHubRepositoryId)
+
+ const data: ProjectCreateVariables = {
+ dbPass,
+ cloudProvider,
+ organizationSlug: currentOrg.slug,
+ name: projectName,
+ highAvailability,
+ // gets ignored due to org billing subscription anyway
+ dbPricingTierId: 'tier_free',
+ // only set the compute size on pro+ plans. Free plans always use micro (nano in the future) size.
+ dbInstanceSize: isFreePlan ? undefined : (instanceSize as DesiredInstanceSize),
+ dataApiExposedSchemas: !dataApi ? [] : undefined,
+ dataApiUseApiSchema: false,
+ dataApiRevokeDefaultPrivileges: dataApi && !dataApiDefaultPrivileges,
+ postgresEngine: useOrioleDb ? availableOrioleVersion?.postgres_engine : postgresEngine,
+ releaseChannel: useOrioleDb ? availableOrioleVersion?.release_channel : releaseChannel,
+ ...(smartRegionEnabled ? { regionSelection: selectedRegion } : { dbRegion }),
+ dbSql: enableRlsEventTrigger ? AUTO_ENABLE_RLS_EVENT_TRIGGER_SQL : undefined,
+ ...(shouldIncludeGitHubFields
+ ? {
+ githubInstallationId,
+ githubRepositoryId: parsedGitHubRepositoryId,
+ }
+ : {}),
+ }
+
+ if (postgresVersion && !postgresVersion.match(/1[2-9]\..*/)) {
+ return toast.error(
+ `Invalid Postgres version, should start with a number between 12-19, a dot and additional characters, i.e. 15.2 or 15.2.0-3`
+ )
+ }
+
+ if (postgresVersion || instanceType) {
+ data['customSupabaseRequest'] = {
+ ami: {
+ ...(postgresVersion && {
+ search_tags: { 'tag:postgresVersion': postgresVersion },
+ }),
+ ...(instanceType && { instance_type: instanceType }),
+ },
+ }
+ }
+
+ createProject(data)
+ }
+
+ const hasTrackedFormExposed = useRef(false)
+ useEffect(() => {
+ if (hasTrackedFormExposed.current) return
+ if (!isOrganizationsSuccess || !canCreateProject || !currentOrg) return
+ hasTrackedFormExposed.current = true
+ track('project_creation_form_exposed', { surface: 'main' })
+ }, [isOrganizationsSuccess, canCreateProject, currentOrg, track])
+
+ useEffect(() => {
+ // Only set once to ensure compute credits dont change while project is being created
+ if (allOrgProjects && allOrgProjects.length > 0 && !allProjects) {
+ setAllProjects(allOrgProjects)
+ }
+ }, [allOrgProjects, allProjects, setAllProjects])
+
+ useEffect(() => {
+ // Handle no org: redirect to new org route
+ if (isEmptyOrganizations) {
+ router.push(`/new`)
+ }
+ }, [isEmptyOrganizations, router])
+
+ useEffect(() => {
+ // [Joshen] Cause slug depends on router which doesnt load immediately on render
+ // While the form data does load immediately
+ if (slug && slug !== '_') setValue('organization', slug)
+ if (projectName) setValue('projectName', projectName || '')
+ }, [slug, setValue, projectName])
+
+ useEffect(() => {
+ if (!isDbRegionDirty && defaultRegion) {
+ setValue('dbRegion', defaultRegion)
+ }
+ }, [defaultRegion, isDbRegionDirty, setValue])
+
+ useEffect(() => {
+ if (!isDbRegionDirty && recommendedSmartRegion) {
+ setValue('dbRegion', recommendedSmartRegion)
+ }
+ }, [recommendedSmartRegion, isDbRegionDirty, setValue])
+
+ useEffect(() => {
+ if (regionError && fixedDefaultRegion) {
+ resetField('dbRegion', { defaultValue: fixedDefaultRegion })
+ }
+ }, [regionError, resetField, fixedDefaultRegion])
+
+ useEffect(() => {
+ if (highAvailability && cloudProvider !== 'AWS_K8S') {
+ setValue('cloudProvider', 'AWS_K8S')
+ }
+ }, [highAvailability, cloudProvider, setValue])
+
+ useEffect(() => {
+ if (watchedInstanceSize !== instanceSize) {
+ setValue('instanceSize', instanceSize, {
+ shouldDirty: false,
+ shouldValidate: false,
+ shouldTouch: false,
+ })
+ }
+ }, [instanceSize, watchedInstanceSize, setValue])
+
+ useEffect(() => {
+ if (!githubRepositoryName) return
+ if ((watchedProjectName ?? '').trim().length > 0) return
+
+ const repoName = githubRepositoryName.split('/').at(-1) ?? githubRepositoryName
+ setValue('projectName', repoName.trim(), {
+ shouldValidate: true,
+ })
+ }, [githubRepositoryName, watchedProjectName, setValue])
+
+ useEffect(() => {
+ if (dataApiRevokeOnCreateDefaultFlag === undefined) return
+ if (isDataApiDefaultPrivilegesDirty) return
+ setValue(
+ 'dataApiDefaultPrivileges',
+ !isInDataApiRevokeTreatment(dataApiRevokeOnCreateDefaultFlag),
+ {
+ shouldDirty: false,
+ }
+ )
+ }, [dataApiRevokeOnCreateDefaultFlag, isDataApiDefaultPrivilegesDirty, setValue])
+
+ useEffect(() => {
+ // This is to make the database.new redirect work correctly. The database.new redirect should be set to supabase.com/dashboard/new/last-visited-org
+ if (slug === 'last-visited-org') {
+ if (lastVisitedOrganization) {
+ router.replace(`/new/${lastVisitedOrganization}`, undefined, { shallow: true })
+ } else {
+ router.replace(`/new/_`, undefined, { shallow: true })
+ }
+ }
+ }, [slug, lastVisitedOrganization, router])
+
+ return (
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(onSubmitWithComputeCostsConfirmation, (errors) =>
+ trackFunnelError(
+ 'project_creation',
+ classifyValidationError('project_creation', errors),
+ 'form'
+ )
+ )}
+ >
+ <Panel
+ loading={!isOrganizationsSuccess}
+ title={
+ <div key="panel-title">
+ <h3>Create a new project</h3>
+ <p className="text-sm text-foreground-lighter text-balance">
+ Your project will have its own dedicated instance and full Postgres database. An API
+ will be set up so you can easily interact with your new database.
+ </p>
+ </div>
+ }
+ footer={
+ <ProjectCreationFooter
+ form={form}
+ canCreateProject={canCreateProject}
+ instanceSize={instanceSize}
+ organizationProjects={organizationProjects}
+ isCreatingNewProject={isCreatingNewProject}
+ isSuccessNewProject={isSuccessNewProject}
+ />
+ }
+ >
+ <>
+ {projectCreationDisabled ? (
+ <DisabledWarningDueToIncident title="Project creation is currently disabled" />
+ ) : (
+ <div className="divide-y divide-border-border">
+ <OrganizationSelector form={form} />
+
+ {canCreateProject && (
+ <>
+ {canConfigureGitHubOnCreate && (
+ <Panel.Content>
+ <GitHubRepositoryField
+ form={form}
+ name="githubRepositoryId"
+ installationIdField="githubInstallationId"
+ repositoryNameField="githubRepositoryName"
+ label="GitHub (optional)"
+ description={
+ <>
+ Ideal for agent-first workflows: update your schema in code, push it
+ to GitHub, and Supabase deploys the changes automatically.{' '}
+ <a
+ href="https://supabase.com/docs/guides/deployment/branching/github-integration"
+ target="_blank"
+ rel="noreferrer noopener"
+ className="text-link"
+ >
+ Learn more
+ </a>
+ </>
+ }
+ disabled={isCreatingNewProject}
+ repositories={githubRepos}
+ gitHubAuthorization={gitHubAuthorization}
+ hasPartialResponseDueToSSO={hasPartialResponseDueToSSO}
+ isLoading={isLoadingRepositoryOptions}
+ refetch={refetchRepositoryOptions}
+ onConnectClick={() => track('project_creation_github_connect_clicked')}
+ />
+ </Panel.Content>
+ )}
+ <ProjectNameInput form={form} />
+
+ {canChooseInstanceSize && <ComputeSizeSelector form={form} />}
+
+ <DatabasePasswordInput form={form} />
+
+ <RegionSelector
+ form={form}
+ instanceSize={instanceSize as DesiredInstanceSize}
+ />
+
+ <SecurityOptions form={form} />
+
+ {showInternalOnlyConfiguration && <InternalOnlyConfiguration form={form} />}
+
+ {showAdvancedConfig && !!availableOrioleVersion && (
+ <AdvancedConfiguration form={form} />
+ )}
+
+ {shouldShowFreeProjectInfo ? (
+ <Admonition
+ className="rounded-none border-0"
+ type="note"
+ title="Need a free project?"
+ description={
+ <p>
+ You can have up to 2 free projects across all organizations.{' '}
+ <Link className="underline text-foreground" href="/new">
+ Create a free organization
+ </Link>{' '}
+ to use them.
+ </p>
+ }
+ />
+ ) : null}
+ </>
+ )}
+
+ {freePlanWithExceedingLimits ? (
+ isAdmin &&
+ slug && (
+ <FreeProjectLimitWarning membersExceededLimit={membersExceededLimit || []} />
+ )
+ ) : hasOutstandingInvoices ? (
+ <Panel.Content>
+ <Admonition
+ type="default"
+ title="Your organization has overdue invoices"
+ description={
+ <div className="space-y-3">
+ <p className="text-sm leading-normal">
+ Please resolve all outstanding invoices first before creating a new
+ project
+ </p>
+
+ <div>
+ <Button asChild variant="default">
+ <Link href={`/org/${slug}/billing#invoices`}>View invoices</Link>
+ </Button>
+ </div>
+ </div>
+ }
+ />
+ </Panel.Content>
+ ) : null}
+ </div>
+ )}
+ </>
+ </Panel>
+
+ <ConfirmationModal
+ size="large"
+ variant="warning"
+ loading={isCreatingNewProject}
+ visible={isComputeCostsConfirmationModalVisible}
+ title="Confirm compute costs"
+ confirmLabel="I understand"
+ onCancel={() => setIsComputeCostsConfirmationModalVisible(false)}
+ onConfirm={async () => {
+ const values = form.getValues()
+ await onSubmit(values)
+ setIsComputeCostsConfirmationModalVisible(false)
+ }}
+ >
+ <div className="text-sm text-foreground-light space-y-1">
+ <p>
+ Launching a project on compute size "{instanceLabel(instanceSize)}" increases your
+ monthly costs by ${additionalMonthlySpend}, independent of how actively you use it. By
+ clicking "I understand", you agree to the additional costs.{' '}
+ <Link
+ href={`${DOCS_URL}/guides/platform/manage-your-usage/compute`}
+ target="_blank"
+ className="underline"
+ >
+ Compute Costs
+ </Link>{' '}
+ are non-refundable.
+ </p>
+ </div>
+ </ConfirmationModal>
+ </form>
+ </Form>
+ )
+}
diff --git a/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.tsx b/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.tsx
index 759d36847e5..1876bc1035e 100644
--- a/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.tsx
+++ b/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.tsx
@@ -1,11 +1,13 @@
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import { toast } from 'sonner'
-import { TextArea } from 'ui'
+import { Card, CardContent, cn, TextArea } from 'ui'
+import { CollapsibleCardSection } from 'ui-patterns/CollapsibleCardSection'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { CANCELLATION_REASONS } from '@/components/interfaces/Billing/Billing.constants'
import { LogicalBackupCliInstructions } from '@/components/layouts/ProjectLayout/LogicalBackupCliInstructions'
+import { InlineLink } from '@/components/ui/InlineLink'
import { TextConfirmModal } from '@/components/ui/TextConfirmModalWrapper'
import { useSendDowngradeFeedbackMutation } from '@/data/feedback/exit-survey-send'
import type { OrgProject } from '@/data/projects/org-projects-infinite-query'
@@ -14,6 +16,7 @@ import { useOrgSubscriptionQuery } from '@/data/subscriptions/org-subscription-q
import { useLastVisitedOrganization } from '@/hooks/misc/useLastVisitedOrganization'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
+import { DOCS_URL } from '@/lib/constants'
import type { Organization } from '@/types'
export const DeleteProjectModal = ({
@@ -125,14 +128,9 @@ export const DeleteProjectModal = ({
<>
{!isFree && 'All project data will be lost, and cannot be undone. '}
Read the{' '}
- <a
- href="https://supabase.com/docs/guides/platform/delete-project"
- target="_blank"
- rel="noopener noreferrer"
- className="underline hover:text-foreground"
- >
+ <InlineLink href={`${DOCS_URL}/guides/platform/delete-project`}>
documentation
- </a>{' '}
+ </InlineLink>{' '}
for prerequisites, implications, and recovery information.
</>
),
@@ -151,7 +149,19 @@ export const DeleteProjectModal = ({
}}
>
<div className="space-y-6">
- <LogicalBackupCliInstructions enabled={visible} showResetPassword={false} />
+ <Card>
+ <CardContent
+ className={cn(
+ '[&>div>button]:tracking-normal',
+ '[&>div>button]:text-foreground [&>div>button]:hover:text-foreground',
+ '[&>div>button]:data-open:text-foreground [&>div>button]:text-sm'
+ )}
+ >
+ <CollapsibleCardSection title="Back up your database with the Supabase CLI">
+ <LogicalBackupCliInstructions enabled={visible} showResetPassword={false} />
+ </CollapsibleCardSection>
+ </CardContent>
+ </Card>
{/*
[Joshen] This is basically ExitSurvey.tsx, ideally we have one shared component but the one
@@ -181,6 +191,7 @@ export const DeleteProjectModal = ({
].join(' ')}
>
<input
+ aria-label="reasons"
type="radio"
name="options"
value={option.value}
@@ -197,6 +208,7 @@ export const DeleteProjectModal = ({
<FormItemLayout isReactForm={false} label={textareaLabel}>
<TextArea
+ autoFocus
name="message"
rows={3}
value={message}
diff --git a/apps/studio/components/layouts/ProjectLayout/LogicalBackupCliInstructions.tsx b/apps/studio/components/layouts/ProjectLayout/LogicalBackupCliInstructions.tsx
index 72fd70f7365..b66b04bc01b 100644
--- a/apps/studio/components/layouts/ProjectLayout/LogicalBackupCliInstructions.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/LogicalBackupCliInstructions.tsx
@@ -3,6 +3,7 @@ import { useParams } from 'common'
import { useRouter } from 'next/router'
import { cn } from 'ui'
import { CodeBlock } from 'ui-patterns/CodeBlock'
+import { InfoTooltip } from 'ui-patterns/info-tooltip'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
import {
@@ -67,18 +68,58 @@ export const LogicalBackupCliInstructions = ({
return (
<div className={cn('space-y-3', className)}>
<div className="space-y-1">
- <h4 className="text-sm font-medium">Back up your database with the Supabase CLI</h4>
<p className="text-sm text-foreground-light">
- Use your direct connection string — replace {DB_PASSWORD_PLACEHOLDER} with your database
- password.{' '}
- <InlineLink href={`${DOCS_URL}/guides/platform/backups`}>Backup documentation</InlineLink>
- .
+ Use your direct connection string to backup your database, replacing{' '}
+ <code className="text-code-inline !break-keep">{DB_PASSWORD_PLACEHOLDER}</code> with your
+ database password. Percent-encode any reserved character in your password before using it
+ in the URL
+ <span className="inline-flex align-text-bottom ml-2">
+ <InfoTooltip side="bottom" className="max-w-64">
+ <p>Examples:</p>
+ <ul className="list-disc pl-6">
+ <li>
+ <span className="flex items-center gap-x-1">
+ <code className="text-code-inline">%</code>
+ <span>&nbsp;→&nbsp;</span>
+ <code className="text-code-inline">%25</code>
+ </span>
+ </li>
+ <li>
+ <span className="flex items-center gap-x-1">
+ <code className="text-code-inline">@</code>
+ <span>&nbsp;→&nbsp;</span>
+ <code className="text-code-inline">%40</code>
+ </span>
+ </li>
+ <li>
+ <span className="flex items-center gap-x-1">
+ <code className="text-code-inline">:</code>
+ <span>&nbsp;→&nbsp;</span>
+ <code className="text-code-inline">%3A</code>
+ </span>
+ </li>
+ <li>
+ <span className="flex items-center gap-x-1">
+ <code className="text-code-inline">/</code>
+ <span>&nbsp;→&nbsp;</span>
+ <code className="text-code-inline">%2F</code>
+ </span>
+ </li>
+ <li>
+ <span className="flex items-center gap-x-1">
+ <code className="text-code-inline">#</code>
+ <span>&nbsp;→&nbsp;</span>
+ <code className="text-code-inline">%23</code>
+ </span>
+ </li>
+ </ul>
+ </InfoTooltip>
+ </span>
</p>
<p className="text-sm text-foreground-light">
- Any reserved character in your password must be percent-encoded in the URL (e.g.{' '}
- <code>@</code>&nbsp;→&nbsp;<code>%40</code>, <code>:</code>&nbsp;→&nbsp;<code>%3A</code>,{' '}
- <code>/</code>&nbsp;→&nbsp;<code>%2F</code>, <code>#</code>&nbsp;→&nbsp;<code>%23</code>).
- Encode <code>%</code> as <code>%25</code> first.
+ See the{' '}
+ <InlineLink href={`${DOCS_URL}/guides/platform/backups`}>Backup documentation</InlineLink>{' '}
+ for details.
</p>
</div>
diff --git a/apps/studio/components/layouts/ProjectLayout/PauseFailedState.tsx b/apps/studio/components/layouts/ProjectLayout/PauseFailedState.tsx
index 51f3be119b2..9cdc69c21d3 100644
--- a/apps/studio/components/layouts/ProjectLayout/PauseFailedState.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/PauseFailedState.tsx
@@ -9,6 +9,7 @@ import {
DialogContent,
DialogHeader,
DialogSection,
+ DialogSectionSeparator,
DialogTitle,
DropdownMenu,
DropdownMenuContent,
@@ -152,10 +153,13 @@ export const PauseFailedState = () => {
</div>
<Dialog open={showCliBackup} onOpenChange={setShowCliBackup}>
- <DialogContent size="medium">
+ <DialogContent size="medium" onOpenAutoFocus={(e) => e.preventDefault()}>
<DialogHeader>
- <DialogTitle>Back up your database</DialogTitle>
+ <DialogTitle>Back up your database with the Supabase CLI</DialogTitle>
</DialogHeader>
+
+ <DialogSectionSeparator />
+
<DialogSection>
<LogicalBackupCliInstructions showResetPassword={false} />
</DialogSection>
diff --git a/apps/studio/components/layouts/ProjectLayout/RestoreFailedState.tsx b/apps/studio/components/layouts/ProjectLayout/RestoreFailedState.tsx
index e6383fb4a14..2855c96f40a 100644
--- a/apps/studio/components/layouts/ProjectLayout/RestoreFailedState.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/RestoreFailedState.tsx
@@ -9,6 +9,7 @@ import {
DialogContent,
DialogHeader,
DialogSection,
+ DialogSectionSeparator,
DialogTitle,
DropdownMenu,
DropdownMenuContent,
@@ -154,10 +155,13 @@ export const RestoreFailedState = () => {
</div>
<Dialog open={showCliBackup} onOpenChange={setShowCliBackup}>
- <DialogContent size="medium">
+ <DialogContent size="medium" onOpenAutoFocus={(e) => e.preventDefault()}>
<DialogHeader>
- <DialogTitle>Back up your database</DialogTitle>
+ <DialogTitle>Back up your database with the Supabase CLI</DialogTitle>
</DialogHeader>
+
+ <DialogSectionSeparator />
+
<DialogSection>
<LogicalBackupCliInstructions showResetPassword={false} />
</DialogSection>
diff --git a/apps/studio/pages/account/tokens/scoped.tsx b/apps/studio/pages/account/tokens/scoped.tsx
index 61fa4dcd655..15ac0f3ef11 100644
--- a/apps/studio/pages/account/tokens/scoped.tsx
+++ b/apps/studio/pages/account/tokens/scoped.tsx
@@ -11,6 +11,7 @@ import AccountLayout from '@/components/layouts/AccountLayout/AccountLayout'
import { AppLayout } from '@/components/layouts/AppLayout/AppLayout'
import { DefaultLayout } from '@/components/layouts/DefaultLayout'
import { NewScopedAccessToken } from '@/data/scoped-access-tokens/scoped-access-token-create-mutation'
+import { DOCS_URL } from '@/lib/constants'
import type { NextPageWithLayout } from '@/types'
const ScopedTokens: NextPageWithLayout = () => {
@@ -42,19 +43,15 @@ const ScopedTokens: NextPageWithLayout = () => {
<div className="flex items-center gap-x-2">
<Button asChild variant="default" icon={<ExternalLink />}>
<a
- href="https://supabase.com/docs/reference/api/introduction"
+ href={`${DOCS_URL}/reference/api/introduction`}
target="_blank"
- rel="noreferrer"
+ rel="noopener noreferrer"
>
API Docs
</a>
</Button>
<Button asChild variant="default" icon={<ExternalLink />}>
- <a
- href="https://supabase.com/docs/reference/cli/start"
- target="_blank"
- rel="noreferrer"
- >
+ <a href={`${DOCS_URL}/reference/cli/start`} target="_blank" rel="noopener noreferrer">
CLI docs
</a>
</Button>
diff --git a/apps/studio/pages/new/[slug].tsx b/apps/studio/pages/new/[slug].tsx
index 4212349eae1..43de71a3fd7 100644
--- a/apps/studio/pages/new/[slug].tsx
+++ b/apps/studio/pages/new/[slug].tsx
@@ -1,526 +1,21 @@
-import { zodResolver } from '@hookform/resolvers/zod'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useFeatureFlags, useFlag, useParams } from 'common'
import Head from 'next/head'
-import Link from 'next/link'
-import { useRouter } from 'next/router'
-import { PropsWithChildren, useEffect, useMemo, useRef, useState } from 'react'
-import { useForm, useFormState } from 'react-hook-form'
-import { type CloudProvider } from 'shared-data'
-import { toast } from 'sonner'
-import { Button, Form, useWatch } from 'ui'
-import { Admonition } from 'ui-patterns/admonition'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
-import { z } from 'zod'
+import { PropsWithChildren } from 'react'
-import { AUTO_ENABLE_RLS_EVENT_TRIGGER_SQL } from '@/components/interfaces/Database/Triggers/EventTriggersList/EventTriggers.constants'
-import { AdvancedConfiguration } from '@/components/interfaces/ProjectCreation/AdvancedConfiguration'
-import { ComputeSizeSelector } from '@/components/interfaces/ProjectCreation/ComputeSizeSelector'
-import { DatabasePasswordInput } from '@/components/interfaces/ProjectCreation/DatabasePasswordInput'
-import { DisabledWarningDueToIncident } from '@/components/interfaces/ProjectCreation/DisabledWarningDueToIncident'
-import { FreeProjectLimitWarning } from '@/components/interfaces/ProjectCreation/FreeProjectLimitWarning'
-import { InternalOnlyConfiguration } from '@/components/interfaces/ProjectCreation/InternalOnlyConfiguration'
-import { OrganizationSelector } from '@/components/interfaces/ProjectCreation/OrganizationSelector'
-import { extractPostgresVersionDetails } from '@/components/interfaces/ProjectCreation/PostgresVersionSelector'
-import { sizes } from '@/components/interfaces/ProjectCreation/ProjectCreation.constants'
-import { FormSchema } from '@/components/interfaces/ProjectCreation/ProjectCreation.schema'
-import {
- instanceLabel,
- monthlyInstancePrice,
- smartRegionToExactRegion,
-} from '@/components/interfaces/ProjectCreation/ProjectCreation.utils'
-import { ProjectCreationFooter } from '@/components/interfaces/ProjectCreation/ProjectCreationFooter'
-import { ProjectNameInput } from '@/components/interfaces/ProjectCreation/ProjectNameInput'
-import { RegionSelector } from '@/components/interfaces/ProjectCreation/RegionSelector'
-import { SecurityOptions } from '@/components/interfaces/ProjectCreation/SecurityOptions'
-import {
- GitHubRepositoryField,
- useGitHubRepositoryOptions,
-} from '@/components/interfaces/Settings/Integrations/GithubIntegration/GitHubRepositoryField'
+import { ProjectCreationForm } from '@/components/interfaces/ProjectCreation/ProjectCreationForm'
import { DefaultLayout } from '@/components/layouts/DefaultLayout'
import { WizardLayoutWithoutAuth } from '@/components/layouts/WizardLayout'
-import Panel from '@/components/ui/Panel'
-import { useAvailableOrioleImageVersion } from '@/data/config/project-creation-postgres-versions-query'
-import { useOverdueInvoicesQuery } from '@/data/invoices/invoices-overdue-query'
-import { useDefaultRegionQuery } from '@/data/misc/get-default-region-query'
-import { useAuthorizedAppsQuery } from '@/data/oauth/authorized-apps-query'
-import { useFreeProjectLimitCheckQuery } from '@/data/organizations/free-project-limit-check-query'
-import { useOrganizationAvailableRegionsQuery } from '@/data/organizations/organization-available-regions-query'
-import { useOrganizationsQuery } from '@/data/organizations/organizations-query'
-import { DesiredInstanceSize } from '@/data/projects/new-project.constants'
-import {
- OrgProject,
- useOrgProjectsInfiniteQuery,
-} from '@/data/projects/org-projects-infinite-query'
-import {
- ProjectCreateVariables,
- useProjectCreateMutation,
-} from '@/data/projects/project-create-mutation'
import { useCustomContent } from '@/hooks/custom-content/useCustomContent'
-import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'
-import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
-import {
- isInDataApiRevokeTreatment,
- useDataApiRevokeOnCreateDefaultEnabled,
-} from '@/hooks/misc/useDataApiRevokeOnCreateDefault'
-import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
-import { useLastVisitedOrganization } from '@/hooks/misc/useLastVisitedOrganization'
-import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { withAuth } from '@/hooks/misc/withAuth'
-import { usePHFlag } from '@/hooks/ui/useFlag'
-import { DOCS_URL, PROJECT_STATUS, PROVIDERS, useDefaultProvider } from '@/lib/constants'
import { buildStudioPageTitle } from '@/lib/page-title'
-import { useProfile } from '@/lib/profile'
-import { classifyApiError, classifyValidationError } from '@/lib/telemetry/funnel-errors'
-import { useTrack } from '@/lib/telemetry/track'
-import { useTrackFunnelError } from '@/lib/telemetry/use-track-funnel-error'
import type { NextPageWithLayout } from '@/types'
-const sizesWithNoCostConfirmationRequired: DesiredInstanceSize[] = ['micro', 'small']
-
const Wizard: NextPageWithLayout = () => {
- const track = useTrack()
- const trackFunnelError = useTrackFunnelError()
- const router = useRouter()
- const { slug, projectName } = useParams()
const { appTitle } = useCustomContent(['app:title'])
- const defaultProvider = useDefaultProvider()
- const { profile } = useProfile()
const pageTitle = buildStudioPageTitle({
section: 'New Project',
brand: appTitle || 'Supabase',
})
- const { data: currentOrg } = useSelectedOrganizationQuery()
- const isFreePlan = currentOrg?.plan?.id === 'free'
- const canChooseInstanceSize = !isFreePlan
-
- const { lastVisitedOrganization } = useLastVisitedOrganization()
- const { can: isAdmin } = useAsyncCheckPermissions(PermissionAction.CREATE, 'projects')
- const { can: canCreateGitHubConnection } = useAsyncCheckPermissions(
- PermissionAction.CREATE,
- 'integrations.github_connections'
- )
- const showAdvancedConfig = useIsFeatureEnabled('project_creation:show_advanced_config')
- const { hasAccess: hasAccessToGitHubIntegration } = useCheckEntitlements(
- 'integrations.github_connections'
- )
-
- const { hasLoaded: flagsLoaded } = useFeatureFlags()
- const projectCreationDisabled = useFlag('disableProjectCreationAndUpdate')
- const showInternalOnlyConfiguration = useFlag('newProjectInternalOnlyConfiguration')
-
- // Read the raw flag for telemetry — coerce-undefined-to-false would record false for
- // users whose flags haven't loaded yet. The raw value preserves undefined (omitted from
- // PostHog) so we only record an actual value (boolean true/false, or a variant string
- // like 'test'/'control' post-multivariate migration) once the flag has resolved.
- const dataApiRevokeOnCreateDefaultFlag = usePHFlag<boolean | string>(
- 'dataApiRevokeOnCreateDefault'
- )
- const isDataApiRevokeOnCreateDefault = useDataApiRevokeOnCreateDefaultEnabled()
-
- const isNotOnHigherPlan = !['team', 'enterprise', 'platform'].includes(currentOrg?.plan.id ?? '')
-
- // This is to make the database.new redirect work correctly. The database.new redirect should be set to supabase.com/dashboard/new/last-visited-org
- if (slug === 'last-visited-org') {
- if (lastVisitedOrganization) {
- router.replace(`/new/${lastVisitedOrganization}`, undefined, { shallow: true })
- } else {
- router.replace(`/new/_`, undefined, { shallow: true })
- }
- }
-
- const [allProjects, setAllProjects] = useState<OrgProject[] | undefined>(undefined)
- const [isComputeCostsConfirmationModalVisible, setIsComputeCostsConfirmationModalVisible] =
- useState(false)
-
- const form = useForm<z.infer<typeof FormSchema>>({
- resolver: zodResolver(FormSchema),
- mode: 'onChange',
- defaultValues: {
- organization: slug,
- projectName: projectName || '',
- highAvailability: false,
- postgresVersion: '',
- instanceType: '',
- cloudProvider: PROVIDERS[defaultProvider].id,
- dbPass: '',
- dbPassStrength: 0,
- dbPassStrengthMessage: '',
- dbRegion: undefined,
- githubRepositoryId: '',
- githubInstallationId: undefined,
- githubRepositoryName: '',
- instanceSize: canChooseInstanceSize ? sizes[0] : undefined,
- dataApi: true,
- dataApiDefaultPrivileges: !isDataApiRevokeOnCreateDefault,
- enableRlsEventTrigger: false,
- postgresVersionSelection: '',
- useOrioleDb: false,
- },
- })
- const { getFieldState, resetField, setValue } = form
- const {
- instanceSize: watchedInstanceSize,
- cloudProvider,
- dbRegion,
- githubRepositoryName,
- organization,
- projectName: watchedProjectName,
- highAvailability,
- } = useWatch({ control: form.control })
- const { dirtyFields } = useFormState(form)
- const isDbRegionDirty = dirtyFields.dbRegion
- const smartRegionEnabled = cloudProvider !== 'AWS_NIMBUS'
-
- // Read dirty state during render rather than depending on form.formState in the
- // effect — form.formState is a Proxy that gets a new reference every render, which
- // would re-fire this effect after each setValue and trigger an infinite loop.
- const isDataApiDefaultPrivilegesDirty = getFieldState(
- 'dataApiDefaultPrivileges',
- form.formState
- ).isDirty
-
- // [Charis] Since the form is updated in a useEffect, there is an edge case
- // when switching from free to paid, where canChooseInstanceSize is true for
- // an in-between render, but watchedInstanceSize is still undefined from the
- // form state carried over from the free plan. To avoid this, we set a
- // default instance size in this case.
- const instanceSize = canChooseInstanceSize ? (watchedInstanceSize ?? sizes[0]) : undefined
- const { data: membersExceededLimit = [] } = useFreeProjectLimitCheckQuery(
- { slug },
- { enabled: isFreePlan }
- )
- const hasMembersExceedingFreeTierLimit = membersExceededLimit.length > 0
- const freePlanWithExceedingLimits = isFreePlan && hasMembersExceedingFreeTierLimit
-
- const { data: organizations = [], isSuccess: isOrganizationsSuccess } = useOrganizationsQuery()
- const isEmptyOrganizations = isOrganizationsSuccess && organizations.length <= 0
-
- const { data: approvedOAuthApps = [] } = useAuthorizedAppsQuery(
- { slug },
- { enabled: !isFreePlan && slug !== '_' }
- )
- const hasOAuthApps = approvedOAuthApps.length > 0
-
- const { data: allOverdueInvoices = [] } = useOverdueInvoicesQuery({
- enabled: isNotOnHigherPlan,
- })
- const overdueInvoices = allOverdueInvoices.filter((x) => x.organization_id === currentOrg?.id)
- const hasOutstandingInvoices = isNotOnHigherPlan && overdueInvoices.length > 0
-
- const { data: orgProjectsFromApi } = useOrgProjectsInfiniteQuery({ slug: currentOrg?.slug })
- const allOrgProjects = useMemo(
- () => orgProjectsFromApi?.pages.flatMap((page) => page.projects),
- [orgProjectsFromApi?.pages]
- )
- const organizationProjects =
- allProjects?.filter((project) => project.status !== PROJECT_STATUS.INACTIVE) ?? []
- const availableComputeCredits = organizationProjects.length === 0 ? 10 : 0
- const additionalMonthlySpend = isFreePlan
- ? 0
- : monthlyInstancePrice(instanceSize) - availableComputeCredits
-
- const selectedCloudProvider = cloudProvider as CloudProvider
- const { data: autoDefaultRegion, error: defaultRegionError } = useDefaultRegionQuery(
- {
- cloudProvider: selectedCloudProvider,
- },
- {
- enabled: flagsLoaded && !smartRegionEnabled,
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchInterval: false,
- refetchOnReconnect: false,
- retry: false,
- }
- )
-
- const { data: availableRegionsData, error: availableRegionsError } =
- useOrganizationAvailableRegionsQuery(
- {
- slug: slug,
- cloudProvider: PROVIDERS[cloudProvider as CloudProvider].id,
- desiredInstanceSize: instanceSize as DesiredInstanceSize,
- },
- {
- enabled: flagsLoaded && smartRegionEnabled,
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchInterval: false,
- refetchOnReconnect: false,
- }
- )
-
- const recommendedSmartRegion = smartRegionEnabled
- ? availableRegionsData?.recommendations.smartGroup.name
- : ''
-
- const fixedDefaultRegion = PROVIDERS[selectedCloudProvider].default_region.displayName
- const regionError =
- smartRegionEnabled && defaultProvider !== 'AWS_NIMBUS'
- ? availableRegionsError
- : defaultRegionError
- const defaultRegion = smartRegionEnabled
- ? availableRegionsData?.recommendations.smartGroup.name
- : (autoDefaultRegion ?? fixedDefaultRegion)
-
- const canCreateProject = isAdmin && !freePlanWithExceedingLimits && !hasOutstandingInvoices
- const canConfigureGitHubOnCreate =
- canCreateProject && hasAccessToGitHubIntegration && canCreateGitHubConnection
-
- const dbRegionExact = smartRegionToExactRegion(dbRegion ?? '')
-
- const availableOrioleVersion = useAvailableOrioleImageVersion(
- {
- cloudProvider: cloudProvider as CloudProvider,
- dbRegion: smartRegionEnabled ? dbRegionExact : (dbRegion ?? ''),
- organizationSlug: organization,
- },
- { enabled: currentOrg !== null }
- )
-
- const userPrimaryEmail = profile?.primary_email?.toLowerCase()
- const isUserAtFreeProjectLimit = userPrimaryEmail
- ? membersExceededLimit.some(
- (member) => member.primary_email?.toLowerCase() === userPrimaryEmail
- )
- : false
- const shouldShowFreeProjectInfo = !!currentOrg && !isFreePlan && !isUserAtFreeProjectLimit
- const {
- gitHubAuthorization,
- githubRepos,
- hasPartialResponseDueToSSO,
- isLoading: isLoadingRepositoryOptions,
- refetch: refetchRepositoryOptions,
- } = useGitHubRepositoryOptions()
-
- const {
- mutate: createProject,
- isPending: isCreatingNewProject,
- isSuccess: isSuccessNewProject,
- } = useProjectCreateMutation({
- onSuccess: (res) => {
- track(
- 'project_creation_simple_version_submitted',
- {
- surface: 'main',
- instanceSize: form.getValues('instanceSize'),
- enableRlsEventTrigger: form.getValues('enableRlsEventTrigger'),
- dataApiEnabled: form.getValues('dataApi'),
- dataApiDefaultPrivilegesGranted: form.getValues('dataApiDefaultPrivileges'),
- useOrioleDb: form.getValues('useOrioleDb'),
- ...(dataApiRevokeOnCreateDefaultFlag !== undefined && {
- dataApiRevokeOnCreateDefaultEnabled: dataApiRevokeOnCreateDefaultFlag,
- }),
- },
- {
- project: res.ref,
- organization: res.organization_slug,
- }
- )
- router.push(`/project/${res.ref}`)
- },
- onError: (error) => {
- const toastId = toast.error(`Failed to create new project: ${error.message}`)
- trackFunnelError(
- 'project_creation',
- classifyApiError('project_creation', error),
- 'toast',
- toastId
- )
- },
- })
-
- const onSubmitWithComputeCostsConfirmation = async (values: z.infer<typeof FormSchema>) => {
- const launchingLargerInstance =
- values.instanceSize &&
- !sizesWithNoCostConfirmationRequired.includes(values.instanceSize as DesiredInstanceSize)
-
- if (additionalMonthlySpend > 0 && (hasOAuthApps || launchingLargerInstance)) {
- track('project_creation_simple_version_confirm_modal_opened', {
- instanceSize: values.instanceSize,
- })
- setIsComputeCostsConfirmationModalVisible(true)
- } else {
- await onSubmit(values)
- }
- }
-
- const onSubmit = async (values: z.infer<typeof FormSchema>) => {
- if (!currentOrg) return console.error('Unable to retrieve current organization')
-
- const {
- cloudProvider,
- projectName,
- highAvailability,
- dbPass,
- dbRegion,
- postgresVersion,
- instanceType,
- instanceSize,
- dataApi,
- dataApiDefaultPrivileges,
- enableRlsEventTrigger,
- postgresVersionSelection,
- useOrioleDb,
- githubInstallationId,
- githubRepositoryId,
- } = values
-
- if (useOrioleDb && !availableOrioleVersion) {
- const toastId = toast.error('No available OrioleDB image found, only Postgres is available')
- trackFunnelError(
- 'project_creation',
- { errorCategory: 'validation', errorReason: 'oriole_unavailable' },
- 'toast',
- toastId
- )
- return
- }
-
- const { postgresEngine, releaseChannel } =
- extractPostgresVersionDetails(postgresVersionSelection)
-
- const { smartGroup = [], specific = [] } = availableRegionsData?.all ?? {}
- const selectedRegion = smartRegionEnabled
- ? (smartGroup.find((x) => x.name === dbRegion) ?? specific.find((x) => x.name === dbRegion))
- : undefined
- const parsedGitHubRepositoryId =
- githubRepositoryId.length > 0 ? Number(githubRepositoryId) : undefined
- const shouldIncludeGitHubFields =
- githubInstallationId !== undefined && Number.isFinite(parsedGitHubRepositoryId)
-
- const data: ProjectCreateVariables = {
- dbPass,
- cloudProvider,
- organizationSlug: currentOrg.slug,
- name: projectName,
- highAvailability,
- // gets ignored due to org billing subscription anyway
- dbPricingTierId: 'tier_free',
- // only set the compute size on pro+ plans. Free plans always use micro (nano in the future) size.
- dbInstanceSize: isFreePlan ? undefined : (instanceSize as DesiredInstanceSize),
- dataApiExposedSchemas: !dataApi ? [] : undefined,
- dataApiUseApiSchema: false,
- dataApiRevokeDefaultPrivileges: dataApi && !dataApiDefaultPrivileges,
- postgresEngine: useOrioleDb ? availableOrioleVersion?.postgres_engine : postgresEngine,
- releaseChannel: useOrioleDb ? availableOrioleVersion?.release_channel : releaseChannel,
- ...(smartRegionEnabled ? { regionSelection: selectedRegion } : { dbRegion }),
- dbSql: enableRlsEventTrigger ? AUTO_ENABLE_RLS_EVENT_TRIGGER_SQL : undefined,
- ...(shouldIncludeGitHubFields
- ? {
- githubInstallationId,
- githubRepositoryId: parsedGitHubRepositoryId,
- }
- : {}),
- }
-
- if (postgresVersion && !postgresVersion.match(/1[2-9]\..*/)) {
- toast.error(
- `Invalid Postgres version, should start with a number between 12-19, a dot and additional characters, i.e. 15.2 or 15.2.0-3`
- )
- }
-
- if (postgresVersion || instanceType) {
- data['customSupabaseRequest'] = {
- ami: {
- ...(postgresVersion && {
- search_tags: { 'tag:postgresVersion': postgresVersion },
- }),
- ...(instanceType && { instance_type: instanceType }),
- },
- }
- }
-
- createProject(data)
- }
-
- const hasTrackedFormExposed = useRef(false)
- useEffect(() => {
- if (hasTrackedFormExposed.current) return
- if (!isOrganizationsSuccess || !canCreateProject || !currentOrg) return
- hasTrackedFormExposed.current = true
- track('project_creation_form_exposed', { surface: 'main' })
- }, [isOrganizationsSuccess, canCreateProject, currentOrg, track])
-
- useEffect(() => {
- // Only set once to ensure compute credits dont change while project is being created
- if (allOrgProjects && allOrgProjects.length > 0 && !allProjects) {
- setAllProjects(allOrgProjects)
- }
- }, [allOrgProjects, allProjects, setAllProjects])
-
- useEffect(() => {
- // Handle no org: redirect to new org route
- if (isEmptyOrganizations) {
- router.push(`/new`)
- }
- }, [isEmptyOrganizations, router])
-
- useEffect(() => {
- // [Joshen] Cause slug depends on router which doesnt load immediately on render
- // While the form data does load immediately
- if (slug && slug !== '_') setValue('organization', slug)
- if (projectName) setValue('projectName', projectName || '')
- }, [slug, setValue, projectName])
-
- useEffect(() => {
- if (!isDbRegionDirty && defaultRegion) {
- setValue('dbRegion', defaultRegion)
- }
- }, [defaultRegion, isDbRegionDirty, setValue])
-
- useEffect(() => {
- if (!isDbRegionDirty && recommendedSmartRegion) {
- setValue('dbRegion', recommendedSmartRegion)
- }
- }, [recommendedSmartRegion, isDbRegionDirty, setValue])
-
- useEffect(() => {
- if (regionError && fixedDefaultRegion) {
- resetField('dbRegion', { defaultValue: fixedDefaultRegion })
- }
- }, [regionError, resetField, fixedDefaultRegion])
-
- useEffect(() => {
- if (highAvailability && cloudProvider !== 'AWS_K8S') {
- setValue('cloudProvider', 'AWS_K8S')
- }
- }, [highAvailability, cloudProvider, setValue])
-
- useEffect(() => {
- if (watchedInstanceSize !== instanceSize) {
- setValue('instanceSize', instanceSize, {
- shouldDirty: false,
- shouldValidate: false,
- shouldTouch: false,
- })
- }
- }, [instanceSize, watchedInstanceSize, setValue])
-
- useEffect(() => {
- if (!githubRepositoryName) return
- if ((watchedProjectName ?? '').trim().length > 0) return
-
- const repoName = githubRepositoryName.split('/').at(-1) ?? githubRepositoryName
- setValue('projectName', repoName.trim(), {
- shouldValidate: true,
- })
- }, [githubRepositoryName, watchedProjectName, setValue])
-
- useEffect(() => {
- if (dataApiRevokeOnCreateDefaultFlag === undefined) return
- if (isDataApiDefaultPrivilegesDirty) return
- setValue(
- 'dataApiDefaultPrivileges',
- !isInDataApiRevokeTreatment(dataApiRevokeOnCreateDefaultFlag),
- {
- shouldDirty: false,
- }
- )
- }, [dataApiRevokeOnCreateDefaultFlag, isDataApiDefaultPrivilegesDirty, setValue])
-
return (
<>
{/* Wizard layouts set the visual header but not the browser tab title. */}
@@ -528,181 +23,7 @@ const Wizard: NextPageWithLayout = () => {
<title>{pageTitle}</title>
<meta name="description" content="Supabase Studio" />
</Head>
- <Form {...form}>
- <form
- onSubmit={form.handleSubmit(onSubmitWithComputeCostsConfirmation, (errors) =>
- trackFunnelError(
- 'project_creation',
- classifyValidationError('project_creation', errors),
- 'form'
- )
- )}
- >
- <Panel
- loading={!isOrganizationsSuccess}
- title={
- <div key="panel-title">
- <h3>Create a new project</h3>
- <p className="text-sm text-foreground-lighter text-balance">
- Your project will have its own dedicated instance and full Postgres database. An
- API will be set up so you can easily interact with your new database.
- </p>
- </div>
- }
- footer={
- <ProjectCreationFooter
- form={form}
- canCreateProject={canCreateProject}
- instanceSize={instanceSize}
- organizationProjects={organizationProjects}
- isCreatingNewProject={isCreatingNewProject}
- isSuccessNewProject={isSuccessNewProject}
- />
- }
- >
- <>
- {projectCreationDisabled ? (
- <DisabledWarningDueToIncident title="Project creation is currently disabled" />
- ) : (
- <div className="divide-y divide-border-border">
- <OrganizationSelector form={form} />
-
- {canCreateProject && (
- <>
- {canConfigureGitHubOnCreate && (
- <Panel.Content>
- <GitHubRepositoryField
- form={form}
- name="githubRepositoryId"
- installationIdField="githubInstallationId"
- repositoryNameField="githubRepositoryName"
- label="GitHub (optional)"
- description={
- <>
- Ideal for agent-first workflows: update your schema in code, push it
- to GitHub, and Supabase deploys the changes automatically.{' '}
- <a
- href="https://supabase.com/docs/guides/deployment/branching/github-integration"
- target="_blank"
- rel="noreferrer noopener"
- className="text-link"
- >
- Learn more
- </a>
- </>
- }
- disabled={isCreatingNewProject}
- repositories={githubRepos}
- gitHubAuthorization={gitHubAuthorization}
- hasPartialResponseDueToSSO={hasPartialResponseDueToSSO}
- isLoading={isLoadingRepositoryOptions}
- refetch={refetchRepositoryOptions}
- onConnectClick={() => track('project_creation_github_connect_clicked')}
- />
- </Panel.Content>
- )}
- <ProjectNameInput form={form} />
-
- {canChooseInstanceSize && <ComputeSizeSelector form={form} />}
-
- <DatabasePasswordInput form={form} />
-
- <RegionSelector
- form={form}
- instanceSize={instanceSize as DesiredInstanceSize}
- />
-
- <SecurityOptions form={form} />
-
- {showInternalOnlyConfiguration && <InternalOnlyConfiguration form={form} />}
-
- {showAdvancedConfig && !!availableOrioleVersion && (
- <AdvancedConfiguration form={form} />
- )}
-
- {shouldShowFreeProjectInfo ? (
- <Admonition
- className="rounded-none border-0"
- type="note"
- title="Need a free project?"
- description={
- <p>
- You can have up to 2 free projects across all organizations.{' '}
- <Link className="underline text-foreground" href="/new">
- Create a free organization
- </Link>{' '}
- to use them.
- </p>
- }
- />
- ) : null}
- </>
- )}
-
- {freePlanWithExceedingLimits ? (
- isAdmin &&
- slug && (
- <FreeProjectLimitWarning membersExceededLimit={membersExceededLimit || []} />
- )
- ) : hasOutstandingInvoices ? (
- <Panel.Content>
- <Admonition
- type="default"
- title="Your organization has overdue invoices"
- description={
- <div className="space-y-3">
- <p className="text-sm leading-normal">
- Please resolve all outstanding invoices first before creating a new
- project
- </p>
-
- <div>
- <Button asChild variant="default">
- <Link href={`/org/${slug}/billing#invoices`}>View invoices</Link>
- </Button>
- </div>
- </div>
- }
- />
- </Panel.Content>
- ) : null}
- </div>
- )}
- </>
- </Panel>
-
- <ConfirmationModal
- size="large"
- loading={false}
- visible={isComputeCostsConfirmationModalVisible}
- title="Confirm compute costs"
- confirmLabel="I understand"
- onCancel={() => setIsComputeCostsConfirmationModalVisible(false)}
- onConfirm={async () => {
- const values = form.getValues()
- await onSubmit(values)
- setIsComputeCostsConfirmationModalVisible(false)
- }}
- variant={'warning'}
- >
- <div className="text-sm text-foreground-light space-y-1">
- <p>
- Launching a project on compute size "{instanceLabel(instanceSize)}" increases your
- monthly costs by ${additionalMonthlySpend}, independent of how actively you use it.
- By clicking "I understand", you agree to the additional costs.{' '}
- <Link
- href={`${DOCS_URL}/guides/platform/manage-your-usage/compute`}
- target="_blank"
- className="underline"
- >
- Compute Costs
- </Link>{' '}
- are non-refundable.
- </p>
- </div>
- </ConfirmationModal>
- </form>
- </Form>
+ <ProjectCreationForm />
</>
)
}
diff --git a/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx b/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
index 416583a36f8..36f6dcaae2e 100644
--- a/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
+++ b/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
@@ -22,7 +22,7 @@ import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { usePreventNavigationOnUnsavedChanges } from '@/hooks/ui/usePreventNavigationOnUnsavedChanges'
-import { BASE_PATH } from '@/lib/constants'
+import { BASE_PATH, DOCS_URL } from '@/lib/constants'
import { useTrack } from '@/lib/telemetry/track'
const CodePage = () => {
@@ -176,7 +176,7 @@ const CodePage = () => {
</li>
<li>
3. Or use the{' '}
- <InlineLink href="https://supabase.com/docs/reference/api/v1-deploy-a-function">
+ <InlineLink href={`${DOCS_URL}/reference/api/v1-deploy-a-function`}>
Management API
</InlineLink>
</li>