Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Display plan selector after the completed onboarding

Blue Mouse0d796240e469
diff --git a/web/app/pages/Auth/Signin/Signin.tsx b/web/app/pages/Auth/Signin/Signin.tsx
index d5b688e4b..ec2225589 100644
--- a/web/app/pages/Auth/Signin/Signin.tsx
+++ b/web/app/pages/Auth/Signin/Signin.tsx
@@ -225,9 +225,15 @@ const Signin = () => {
setIsAuthenticated(true)
setTotalMonthlyEvents(totalMonthlyEvents)
- // Redirect to onboarding if user hasn't completed it
if (!user.hasCompletedOnboarding) {
navigate(routes.onboarding)
+ } else if (
+ !isSelfhosted &&
+ (!user.planCode ||
+ user.planCode === 'trial' ||
+ user.planCode === 'none')
+ ) {
+ navigate(routes.checkout)
} else {
navigate(routes.dashboard)
}
@@ -304,6 +310,13 @@ const Signin = () => {
if (!user.hasCompletedOnboarding) {
navigate(routes.onboarding)
+ } else if (
+ !isSelfhosted &&
+ (!user.planCode ||
+ user.planCode === 'trial' ||
+ user.planCode === 'none')
+ ) {
+ navigate(routes.checkout)
} else {
navigate(routes.dashboard)
}
diff --git a/web/app/pages/Auth/Signup/Signup.tsx b/web/app/pages/Auth/Signup/Signup.tsx
index 7973cfd65..9fefb4a08 100644
--- a/web/app/pages/Auth/Signup/Signup.tsx
+++ b/web/app/pages/Auth/Signup/Signup.tsx
@@ -23,8 +23,6 @@ import {
HAVE_I_BEEN_PWNED_URL,
isSelfhosted,
TRIAL_DAYS,
- PLAN_LIMITS,
- STANDARD_PLANS,
} from '~/lib/constants'
import { SSOProvider, SSOHashSuccessResponse } from '~/lib/models/Auth'
import { useAuth } from '~/providers/AuthProvider'
@@ -33,7 +31,6 @@ import type { SignupActionData } from '~/routes/signup'
import Button from '~/ui/Button'
import Checkbox from '~/ui/Checkbox'
import Input from '~/ui/Input'
-import { Switch } from '~/ui/Switch'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
import { cn, delay, openBrowserWindow } from '~/utils/generic'
@@ -41,7 +38,6 @@ import routes from '~/utils/routes'
import { MIN_PASSWORD_CHARS } from '~/utils/validator'
const HASH_CHECK_FREQUENCY = 1000
-const INITIAL_VISIBLE_PLANS = 3
const featureIcons = [
ChartBarIcon,
@@ -50,8 +46,6 @@ const featureIcons = [
SparkleIcon,
]
-const formatEventsLong = (value: number) => value.toLocaleString('en-US')
-
const featureKeys = [
'realTimeAnalytics',
'eventTracking',
@@ -69,18 +63,6 @@ const Signup = () => {
const [tos, setTos] = useState(false)
const [checkIfLeaked, setCheckIfLeaked] = useState(true)
- const [selectedPlan, setSelectedPlan] = useState<string>('100k')
- const [selectedBillingFrequency, setSelectedBillingFrequency] = useState<
- 'monthly' | 'yearly'
- >('monthly')
- const [showAllPlans, setShowAllPlans] = useState(false)
-
- // Save selected plan to cookies for the next step
- useEffect(() => {
- document.cookie = `swetrix_selected_plan=${selectedPlan}; path=/; max-age=86400`
- document.cookie = `swetrix_selected_billing=${selectedBillingFrequency}; path=/; max-age=86400`
- }, [selectedPlan, selectedBillingFrequency])
-
const [isSsoLoading, setIsSsoLoading] = useState(false)
const [clearedErrors, setClearedErrors] = useState<Set<string>>(new Set())
@@ -217,7 +199,6 @@ const Signup = () => {
setIsAuthenticated(true)
setTotalMonthlyEvents(totalMonthlyEvents)
- // Redirect to onboarding if user hasn't completed it
if (!user.hasCompletedOnboarding) {
navigate(routes.onboarding)
} else {
@@ -263,101 +244,6 @@ const Signup = () => {
)}
</div>
- {!isSelfhosted && (
- <div className='mb-8'>
- <div className='mb-3 flex items-center justify-between'>
- <Text as='p' size='sm' colour='secondary'>
- {t('auth.signup.changePlanLater')}
- </Text>
- <button
- type='button'
- onClick={() =>
- setSelectedBillingFrequency((f) =>
- f === 'monthly' ? 'yearly' : 'monthly',
- )
- }
- className='flex shrink-0 cursor-pointer items-center gap-2 rounded-lg border border-gray-200 px-2.5 py-1.5 transition-colors hover:bg-gray-100 dark:border-slate-700 dark:hover:bg-slate-800'
- >
- <span className='text-xs font-medium text-gray-700 dark:text-gray-200'>
- {t('pricing.billedYearly')}
- </span>
- <span className='rounded-md bg-emerald-100 px-1.5 py-0.5 text-xs font-semibold text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-300'>
- -17%
- </span>
- <Switch
- checked={selectedBillingFrequency === 'yearly'}
- visualOnly
- />
- </button>
- </div>
-
- <div className='space-y-2'>
- {STANDARD_PLANS.slice(
- 0,
- showAllPlans ? undefined : INITIAL_VISIBLE_PLANS,
- ).map((planCode) => {
- const tier =
- PLAN_LIMITS[planCode as keyof typeof PLAN_LIMITS]
- if (!tier) return null
- const isSelected = selectedPlan === planCode
- const price =
- selectedBillingFrequency === 'monthly'
- ? tier.price?.USD?.monthly
- : tier.price?.USD?.yearly
- const priceLabel =
- selectedBillingFrequency === 'monthly'
- ? t('pricing.perMonth')
- : t('pricing.perYear')
-
- return (
- <button
- key={planCode}
- type='button'
- onClick={() => setSelectedPlan(planCode)}
- className={cn(
- 'flex w-full items-center justify-between rounded-xl px-4 py-3 text-left ring-1 transition-all duration-150',
- isSelected
- ? 'ring-2 ring-indigo-500 dark:ring-slate-200'
- : 'ring-gray-200 hover:ring-gray-300 dark:ring-slate-700 dark:hover:ring-slate-600',
- )}
- >
- <Text as='span' size='base' weight='semibold'>
- ${price}
- <Text
- as='span'
- size='sm'
- colour='muted'
- weight='medium'
- >
- /{priceLabel}
- </Text>
- </Text>
- <Text as='span' size='sm' colour='muted'>
- {t('pricing.upToXEvents', {
- amount: formatEventsLong(tier.monthlyUsageLimit),
- })}
- </Text>
- </button>
- )
- })}
- </div>
-
- <div className='mt-3'>
- <button
- type='button'
- onClick={() => setShowAllPlans((v) => !v)}
- className='rounded-full bg-gray-100 px-3.5 py-1.5 text-xs font-semibold text-gray-700 transition-colors hover:bg-gray-200 dark:bg-slate-800 dark:text-gray-300 dark:hover:bg-slate-700'
- >
- {showAllPlans
- ? t('common.showLess')
- : t('common.showMore', {
- count: STANDARD_PLANS.length - INITIAL_VISIBLE_PLANS,
- })}
- </button>
- </div>
- </div>
- )}
-
<div
className={cn(
'grid gap-3',
diff --git a/web/app/pages/Checkout/Checkout.tsx b/web/app/pages/Checkout/Checkout.tsx
new file mode 100644
index 000000000..3af31341d
--- /dev/null
+++ b/web/app/pages/Checkout/Checkout.tsx
@@ -0,0 +1,400 @@
+import {
+ RocketLaunchIcon,
+ BellIcon,
+ CreditCardIcon,
+ ShieldCheckIcon,
+ CheckIcon,
+} from '@phosphor-icons/react'
+import { useEffect, useState } from 'react'
+import { Trans, useTranslation } from 'react-i18next'
+import { useNavigate, useLoaderData } from 'react-router'
+import { toast } from 'sonner'
+
+import {
+ BillingFrequency,
+ PADDLE_JS_URL,
+ PADDLE_VENDOR_ID,
+ paddleLanguageMapping,
+ PLAN_LIMITS,
+ STANDARD_PLANS,
+ TRIAL_DAYS,
+} from '~/lib/constants'
+import { getCookie } from '~/utils/cookie'
+import { useAuth } from '~/providers/AuthProvider'
+import { useTheme } from '~/providers/ThemeProvider'
+import type { CheckoutLoaderData } from '~/routes/checkout'
+import Button from '~/ui/Button'
+import { Text } from '~/ui/Text'
+import { Switch } from '~/ui/Switch'
+import { cn, loadScript } from '~/utils/generic'
+import routes from '~/utils/routes'
+
+const INITIAL_VISIBLE_PLANS = 3
+const formatEventsLong = (value: number) => value.toLocaleString('en-US')
+
+const Checkout = () => {
+ const { t, i18n } = useTranslation('common')
+ const { theme } = useTheme()
+ const { user } = useAuth()
+ const navigate = useNavigate()
+ const { metainfo } = useLoaderData<CheckoutLoaderData>()
+
+ const [selectedPlan, setSelectedPlan] = useState<string>(() => {
+ if (typeof document === 'undefined') return '100k'
+ return getCookie('swetrix_selected_plan') || '100k'
+ })
+ const [selectedBillingFrequency, setSelectedBillingFrequency] = useState<'monthly' | 'yearly'>(() => {
+ if (typeof document === 'undefined') return 'monthly'
+ return getCookie('swetrix_selected_billing') === 'yearly'
+ ? 'yearly'
+ : 'monthly'
+ })
+ const [showAllPlans, setShowAllPlans] = useState(false)
+
+ const [isPaddleLoaded, setIsPaddleLoaded] = useState(false)
+ const [hasCompletedCheckout, setHasCompletedCheckout] = useState(false)
+ const [isCheckoutOpen, setIsCheckoutOpen] = useState(false)
+
+ const tier = PLAN_LIMITS[selectedPlan as keyof typeof PLAN_LIMITS]
+ const monthlyPrice = tier?.price?.USD?.monthly
+ const yearlyPrice = tier?.price?.USD?.yearly
+ const displayPrice =
+ selectedBillingFrequency === 'yearly'
+ ? Math.round((yearlyPrice || 0) / 12)
+ : monthlyPrice
+
+ useEffect(() => {
+ document.cookie = `swetrix_selected_plan=${selectedPlan}; path=/; max-age=86400`
+ document.cookie = `swetrix_selected_billing=${selectedBillingFrequency}; path=/; max-age=86400`
+ }, [selectedPlan, selectedBillingFrequency])
+
+ useEffect(() => {
+ loadScript(PADDLE_JS_URL)
+
+ const interval = setInterval(() => {
+ if ((window as any)?.Paddle) {
+ ;(window as any).Paddle.Setup({
+ vendor: PADDLE_VENDOR_ID,
+ eventCallback: (eventData: any) => {
+ if (eventData?.event === 'Checkout.Complete') {
+ setHasCompletedCheckout(true)
+ }
+ },
+ })
+ setIsPaddleLoaded(true)
+ clearInterval(interval)
+ }
+ }, 200)
+
+ return () => clearInterval(interval)
+ }, [])
+
+ useEffect(() => {
+ if (hasCompletedCheckout) {
+ const timer = setTimeout(() => {
+ navigate(routes.dashboard)
+ }, 2000)
+ return () => clearTimeout(timer)
+ }
+ }, [hasCompletedCheckout, navigate])
+
+ const handleStartCheckout = () => {
+ if (!isPaddleLoaded || !(window as any).Paddle) {
+ toast.error(
+ 'Payment script is still loading. Please try again.',
+ )
+ return
+ }
+
+ if (!tier) return
+
+ const product =
+ selectedBillingFrequency === BillingFrequency.monthly
+ ? (tier as any).pid
+ : (tier as any).ypid
+
+ setIsCheckoutOpen(true)
+ ;(window as any).Paddle.Checkout.open({
+ product,
+ method: 'inline',
+ frameTarget: 'checkout-container',
+ frameInitialHeight: 416,
+ frameStyle:
+ 'width:100%; min-width:312px; background-color: transparent; border: none; border-radius: 10px;',
+ email: user?.email,
+ passthrough: JSON.stringify({ uid: user?.id }),
+ locale: paddleLanguageMapping[i18n.language] || i18n.language,
+ displayModeTheme: theme,
+ country: metainfo.country,
+ })
+
+ setTimeout(() => {
+ document
+ .querySelector('#checkout-container')
+ ?.scrollIntoView({ behavior: 'smooth' })
+ }, 500)
+ }
+
+ const today = new Date()
+ const trialEndDate = new Date()
+ trialEndDate.setDate(today.getDate() + TRIAL_DAYS)
+
+ const dateFormatter = new Intl.DateTimeFormat(i18n.language, {
+ month: 'long',
+ day: 'numeric',
+ year: 'numeric',
+ })
+
+ const formattedEndDate = dateFormatter.format(trialEndDate)
+
+ return (
+ <div className='flex min-h-screen flex-col items-center justify-center bg-gray-50 p-4 dark:bg-slate-950 lg:p-8'>
+ <div className='w-full max-w-5xl grid grid-cols-1 lg:grid-cols-[1fr_400px] gap-12 lg:gap-16 items-start'>
+
+ {/* Left Column */}
+ <div className='flex flex-col gap-8'>
+ <div>
+ <Text as='h1' size='3xl' weight='bold' tracking='tight'>
+ {t('checkout.title')}
+ </Text>
+
+ <div className='mt-6 flex flex-col gap-3'>
+ <div className='flex items-center gap-3'>
+ <CheckIcon className='size-5 shrink-0 text-emerald-500' weight='bold' />
+ <Text as='p' size='base'>
+ {t('checkout.freeTrialAnytime', { days: TRIAL_DAYS })}
+ </Text>
+ </div>
+ <div className='flex items-center gap-3'>
+ <CheckIcon className='size-5 shrink-0 text-emerald-500' weight='bold' />
+ <Text as='p' size='base'>
+ {t('checkout.willRemind')}
+ </Text>
+ </div>
+ </div>
+ </div>
+
+ <div>
+ <div className='mb-3 flex items-center justify-between'>
+ <Text as='p' size='sm' colour='secondary'>
+ Select your plan
+ </Text>
+ <button
+ type='button'
+ onClick={() =>
+ setSelectedBillingFrequency((f) =>
+ f === 'monthly' ? 'yearly' : 'monthly',
+ )
+ }
+ className='flex shrink-0 cursor-pointer items-center gap-2 rounded-lg border border-gray-200 px-2.5 py-1.5 transition-colors hover:bg-gray-100 dark:border-slate-700 dark:hover:bg-slate-800'
+ >
+ <span className='text-xs font-medium text-gray-700 dark:text-gray-200'>
+ {t('pricing.billedYearly')}
+ </span>
+ <span className='rounded-md bg-emerald-100 px-1.5 py-0.5 text-xs font-semibold text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-300'>
+ -17%
+ </span>
+ <Switch
+ checked={selectedBillingFrequency === 'yearly'}
+ visualOnly
+ />
+ </button>
+ </div>
+
+ <div className='space-y-2'>
+ {STANDARD_PLANS.slice(
+ 0,
+ showAllPlans ? undefined : INITIAL_VISIBLE_PLANS,
+ ).map((planCode) => {
+ const planTier = PLAN_LIMITS[planCode as keyof typeof PLAN_LIMITS]
+ if (!planTier) return null
+ const isSelected = selectedPlan === planCode
+ const price =
+ selectedBillingFrequency === 'monthly'
+ ? planTier.price?.USD?.monthly
+ : planTier.price?.USD?.yearly
+ const priceLabel =
+ selectedBillingFrequency === 'monthly'
+ ? t('pricing.perMonth')
+ : t('pricing.perYear')
+
+ return (
+ <button
+ key={planCode}
+ type='button'
+ onClick={() => setSelectedPlan(planCode)}
+ className={cn(
+ 'flex w-full items-center justify-between rounded-xl px-4 py-3 text-left ring-1 transition-all duration-150',
+ isSelected
+ ? 'ring-2 ring-indigo-500 bg-white shadow-sm dark:bg-slate-900 dark:ring-slate-200'
+ : 'ring-gray-200 bg-white hover:ring-gray-300 dark:bg-slate-900 dark:ring-slate-700 dark:hover:ring-slate-600',
+ )}
+ >
+ <Text as='span' size='base' weight='semibold'>
+ ${price}
+ <Text as='span' size='sm' colour='muted' weight='medium'>
+ /{priceLabel}
+ </Text>
+ </Text>
+ <Text as='span' size='sm' colour='muted'>
+ {t('pricing.upToXEvents', {
+ amount: formatEventsLong(planTier.monthlyUsageLimit),
+ })}
+ </Text>
+ </button>
+ )
+ })}
+ </div>
+
+ <div className='mt-3'>
+ <button
+ type='button'
+ onClick={() => setShowAllPlans((v) => !v)}
+ className='rounded-full bg-gray-100 px-3.5 py-1.5 text-xs font-semibold text-gray-700 transition-colors hover:bg-gray-200 dark:bg-slate-800 dark:text-gray-300 dark:hover:bg-slate-700'
+ >
+ {showAllPlans
+ ? t('common.showLess')
+ : t('common.showMore', {
+ count: STANDARD_PLANS.length - INITIAL_VISIBLE_PLANS,
+ })}
+ </button>
+ </div>
+ </div>
+
+ <div className='flex flex-col gap-4 border-t border-gray-200 pt-6 dark:border-slate-800'>
+ <div className='flex items-center justify-between'>
+ <Text as='p' size='base'>
+ {t('checkout.dueEnd', { date: formattedEndDate })}
+ </Text>
+ <Text as='p' size='base' weight='semibold'>
+ ${displayPrice}
+ </Text>
+ </div>
+ <div className='flex items-center justify-between'>
+ <Text as='p' size='base' weight='bold'>
+ {t('checkout.dueToday', { days: TRIAL_DAYS })}
+ </Text>
+ <Text as='p' size='base' weight='bold' className='text-emerald-600 dark:text-emerald-500'>
+ {t('checkout.free')}
+ </Text>
+ </div>
+ </div>
+
+ <div className='pt-2'>
+ {hasCompletedCheckout ? (
+ <div className='rounded-xl border border-emerald-200 bg-emerald-50 p-4 text-center dark:border-emerald-800 dark:bg-emerald-900/20'>
+ <div className='flex items-center justify-center gap-2'>
+ <ShieldCheckIcon className='size-5 text-emerald-600 dark:text-emerald-400' />
+ <Text
+ as='p'
+ size='sm'
+ weight='semibold'
+ className='text-emerald-700 dark:text-emerald-300'
+ >
+ {t('common.success')}! Redirecting...
+ </Text>
+ </div>
+ </div>
+ ) : (
+ <>
+ {!isCheckoutOpen && (
+ <Button
+ className='w-full justify-center'
+ onClick={handleStartCheckout}
+ primary
+ giant
+ >
+ {t('checkout.next')}
+ </Button>
+ )}
+
+ <div id='checkout-container' className='min-h-0 w-full' />
+
+ {!isCheckoutOpen && (
+ <Text as='p' size='xs' colour='muted' className='mt-4 text-center'>
+ <Trans
+ t={t}
+ i18nKey='checkout.termsDesc'
+ components={{
+ privacy: (
+ <a
+ href={routes.privacy}
+ target='_blank'
+ rel='noopener noreferrer'
+ className='font-medium underline decoration-dashed hover:decoration-solid'
+ />
+ ),
+ }}
+ />
+ </Text>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+
+ {/* Right Column (Timeline) */}
+ <div className='hidden lg:block lg:pt-16'>
+ <div className='rounded-2xl bg-white p-6 shadow-xs ring-1 ring-gray-200 dark:bg-slate-900 dark:ring-slate-700/80'>
+ <div className='flex items-start gap-5'>
+ <div className='relative flex flex-col items-center'>
+ <div className='flex size-10 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-900/30'>
+ <RocketLaunchIcon className='size-5 text-emerald-600 dark:text-emerald-400' />
+ </div>
+ <div className='my-1 h-12 w-1 rounded-full bg-emerald-100 dark:bg-emerald-900/30' />
+ </div>
+ <div className='pt-2'>
+ <Text as='p' size='sm' weight='bold'>
+ {t('onboarding.selectPlan.timeline.today')}
+ </Text>
+ <Text as='p' size='sm' colour='secondary' className='mt-1'>
+ {t('onboarding.selectPlan.timeline.todayDesc')}
+ </Text>
+ </div>
+ </div>
+
+ <div className='flex items-start gap-5'>
+ <div className='relative flex flex-col items-center'>
+ <div className='flex size-10 items-center justify-center rounded-full bg-amber-50 ring-1 ring-amber-100 dark:bg-amber-900/10 dark:ring-amber-900/30'>
+ <BellIcon className='size-5 text-amber-500 dark:text-amber-400' />
+ </div>
+ <div className='my-1 h-12 w-1 rounded-full bg-gray-100 dark:bg-slate-800' />
+ </div>
+ <div className='pt-2'>
+ <Text as='p' size='sm' weight='semibold'>
+ {t('onboarding.selectPlan.timeline.reminder', {
+ days: TRIAL_DAYS - 2,
+ })}
+ </Text>
+ <Text as='p' size='sm' colour='secondary' className='mt-1'>
+ {t('onboarding.selectPlan.timeline.reminderDesc')}
+ </Text>
+ </div>
+ </div>
+
+ <div className='flex items-start gap-5'>
+ <div className='relative flex flex-col items-center'>
+ <div className='flex size-10 items-center justify-center rounded-full bg-blue-50 ring-1 ring-blue-100 dark:bg-blue-900/10 dark:ring-blue-900/30'>
+ <CreditCardIcon className='size-5 text-blue-500 dark:text-blue-400' />
+ </div>
+ </div>
+ <div className='pt-2'>
+ <Text as='p' size='sm' weight='semibold'>
+ {t('onboarding.selectPlan.timeline.charge', {
+ days: TRIAL_DAYS,
+ })}
+ </Text>
+ <Text as='p' size='sm' colour='secondary' className='mt-1'>
+ {t('onboarding.selectPlan.timeline.chargeDesc')}
+ </Text>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ </div>
+ </div>
+ )
+}
+
+export default Checkout
diff --git a/web/app/pages/Checkout/index.tsx b/web/app/pages/Checkout/index.tsx
new file mode 100644
index 000000000..ed3da5028
--- /dev/null
+++ b/web/app/pages/Checkout/index.tsx
@@ -0,0 +1 @@
+export { default } from './Checkout'
diff --git a/web/app/pages/Onboarding/Onboarding.tsx b/web/app/pages/Onboarding/Onboarding.tsx
index 30c4451d5..e424cc47a 100644
--- a/web/app/pages/Onboarding/Onboarding.tsx
+++ b/web/app/pages/Onboarding/Onboarding.tsx
@@ -9,9 +9,6 @@ import {
FileTextIcon,
ClockIcon,
FolderPlusIcon,
- BellIcon,
- CreditCardIcon,
- RocketLaunchIcon,
} from '@phosphor-icons/react'
import { useState, useEffect, useRef, useCallback } from 'react'
import { Trans, useTranslation } from 'react-i18next'
@@ -20,18 +17,11 @@ import { toast } from 'sonner'
import { useAuthProxy } from '~/hooks/useAuthProxy'
import {
- BillingFrequency,
BROWSER_LOGO_MAP,
CONFIRMATION_TIMEOUT,
DOCS_URL,
INTEGRATIONS_URL,
isSelfhosted,
- PADDLE_JS_URL,
- PADDLE_VENDOR_ID,
- paddleLanguageMapping,
- PLAN_LIMITS,
- STANDARD_PLANS,
- TRIAL_DAYS,
whitelist,
languages,
languageFlag,
@@ -43,7 +33,6 @@ import { changeLanguage } from '~/i18n'
import { getSnippet } from '~/modals/TrackingSnippet'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
-import { Switch } from '~/ui/Switch'
import type {
OnboardingActionData,
OnboardingLoaderData,
@@ -58,7 +47,7 @@ import Alert from '~/ui/Alert'
import { Text } from '~/ui/Text'
import Textarea from '~/ui/Textarea'
import { trackCustom } from '~/utils/analytics'
-import { cn, loadScript } from '~/utils/generic'
+import { cn } from '~/utils/generic'
import routes from '~/utils/routes'
const MAX_PROJECT_NAME_LENGTH = 50
@@ -77,7 +66,6 @@ type OnboardingStep =
| 'feature_traffic'
| 'feature_errors'
| 'feature_sessions'
- | 'select_plan'
| 'create_project'
| 'setup_tracking'
| 'verify_email'
@@ -89,14 +77,10 @@ const getSteps = (): OnboardingStep[] => {
'feature_traffic',
'feature_errors',
'feature_sessions',
+ 'create_project',
+ 'setup_tracking',
]
- if (!isSelfhosted) {
- baseSteps.push('select_plan')
- }
-
- baseSteps.push('create_project', 'setup_tracking')
-
if (!isSelfhosted) {
baseSteps.push('verify_email')
}
@@ -104,18 +88,6 @@ const getSteps = (): OnboardingStep[] => {
return baseSteps
}
-const formatEvents = (limit: number): string => {
- if (limit >= 1_000_000) {
- const m = limit / 1_000_000
- return `${m % 1 === 0 ? m : m.toFixed(1)}M`
- }
- if (limit >= 1_000) {
- const k = limit / 1_000
- return `${k % 1 === 0 ? k : k.toFixed(1)}K`
- }
- return limit.toString()
-}
-
const STEPS = getSteps()
const slideVariants = {
@@ -475,24 +447,6 @@ const Onboarding = () => {
() => !!getCookie(CONFIRMATION_TIMEOUT),
)
- // Plan selection state
- const [selectedBillingFrequency, setSelectedBillingFrequency] = useState<
- 'monthly' | 'yearly'
- >(() => {
- if (typeof document === 'undefined') return 'monthly'
- return getCookie('swetrix_selected_billing') === 'yearly'
- ? 'yearly'
- : 'monthly'
- })
- const [selectedPlan, setSelectedPlan] = useState<string>(() => {
- if (typeof document === 'undefined') return '100k'
- return getCookie('swetrix_selected_plan') || '100k'
- })
- const [isPaddleLoaded, setIsPaddleLoaded] = useState(false)
- const [hasCompletedCheckout, setHasCompletedCheckout] = useState(
- () => user?.planCode !== 'trial' && user?.planCode !== 'none'
- )
-
const currentStep = STEPS[currentStepIndex]
const isLoading =
fetcher.state === 'submitting' || fetcher.state === 'loading'
@@ -517,7 +471,7 @@ const Onboarding = () => {
loadUser()
} else if (intent === 'complete-onboarding') {
loadUser()
- navigate(routes.dashboard)
+ navigate(isSelfhosted ? routes.dashboard : routes.checkout)
} else if (intent === 'confirm-email') {
setCookie(CONFIRMATION_TIMEOUT, true, 600)
setHasResentEmail(true)
@@ -534,29 +488,6 @@ const Onboarding = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fetcher.data, fetcher.submit, loadUser, logout, navigate])
- useEffect(() => {
- if (isSelfhosted) return
-
- loadScript(PADDLE_JS_URL)
-
- const interval = setInterval(() => {
- if ((window as any)?.Paddle) {
- ;(window as any).Paddle.Setup({
- vendor: PADDLE_VENDOR_ID,
- eventCallback: (eventData: any) => {
- if (eventData?.event === 'Checkout.Complete') {
- setHasCompletedCheckout(true)
- }
- },
- })
- setIsPaddleLoaded(true)
- clearInterval(interval)
- }
- }, 200)
-
- return () => clearInterval(interval)
- }, [])
-
useEffect(() => {
if (!isWaitingForEvents || !project) return
@@ -926,123 +857,6 @@ const Onboarding = () => {
</div>
)}
- {currentStep === 'select_plan' && (
- <div>
- <Text
- as='h1'
- size='3xl'
- weight='bold'
- tracking='tight'
- className='mb-2'
- >
- {t('onboarding.selectPlan.title')}
- </Text>
- <Text as='p' colour='secondary' className='mb-6'>
- {t('onboarding.selectPlan.subtitle')}
- </Text>
-
- {selectedPlan && PLAN_LIMITS[selectedPlan as keyof typeof PLAN_LIMITS] && (
- <div className='mb-6 flex items-center justify-between rounded-xl bg-indigo-50 p-4 ring-1 ring-indigo-200 dark:bg-indigo-900/20 dark:ring-indigo-800'>
- <div>
- <Text as='p' size='sm' weight='medium' className='text-indigo-900 dark:text-indigo-100'>
- {PLAN_LIMITS[selectedPlan as keyof typeof PLAN_LIMITS].monthlyUsageLimit.toLocaleString()} {t('pricing.eventsPerMonth')}
- </Text>
- <Text as='p' size='xs' className='text-indigo-700 dark:text-indigo-300'>
- {selectedBillingFrequency === 'yearly' ? t('pricing.billedYearly') : t('pricing.monthlyBilling')}
- </Text>
- </div>
- <div className='text-right'>
- <Text as='p' size='lg' weight='bold' className='text-indigo-900 dark:text-indigo-100'>
- ${selectedBillingFrequency === 'yearly'
- ? Math.round((PLAN_LIMITS[selectedPlan as keyof typeof PLAN_LIMITS].price?.USD?.yearly || 0) / 12)
- : PLAN_LIMITS[selectedPlan as keyof typeof PLAN_LIMITS].price?.USD?.monthly}
- <Text as='span' size='xs' weight='medium' className='text-indigo-700 dark:text-indigo-300'>
- /mo
- </Text>
- </Text>
- </div>
- </div>
- )}
-
- <div className='mb-6 rounded-xl ring-1 ring-gray-200 dark:ring-slate-700'>
- <div className='p-5'>
- <div className='flex items-start gap-4'>
- <div className='relative flex flex-col items-center'>
- <div className='flex size-8 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-900/30'>
- <RocketLaunchIcon className='size-4 text-emerald-600 dark:text-emerald-400' />
- </div>
- <div className='mt-1 h-8 w-px bg-gray-200 dark:bg-slate-700' />
- </div>
- <div className='pt-1'>
- <Text
- as='p'
- size='sm'
- weight='semibold'
- >
- {t('onboarding.selectPlan.timeline.today')}
- </Text>
- <Text as='p' size='xs' colour='muted'>
- {t(
- 'onboarding.selectPlan.timeline.todayDesc',
- )}
- </Text>
- </div>
- </div>
-
- <div className='flex items-start gap-4'>
- <div className='relative flex flex-col items-center'>
- <div className='flex size-8 items-center justify-center rounded-full bg-amber-100 dark:bg-amber-900/30'>
- <BellIcon className='size-4 text-amber-600 dark:text-amber-400' />
- </div>
- <div className='mt-1 h-8 w-px bg-gray-200 dark:bg-slate-700' />
- </div>
- <div className='pt-1'>
- <Text
- as='p'
- size='sm'
- weight='semibold'
- >
- {t('onboarding.selectPlan.timeline.reminder', { days: TRIAL_DAYS - 2 })}
- </Text>
- <Text as='p' size='xs' colour='muted'>
- {t(
- 'onboarding.selectPlan.timeline.reminderDesc',
- )}
- </Text>
- </div>
- </div>
-
- <div className='flex items-start gap-4'>
- <div className='relative flex flex-col items-center'>
- <div className='flex size-8 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900/30'>
- <CreditCardIcon className='size-4 text-blue-600 dark:text-blue-400' />
- </div>
- </div>
- <div className='pt-1'>
- <Text
- as='p'
- size='sm'
- weight='semibold'
- >
- {t('onboarding.selectPlan.timeline.charge', { days: TRIAL_DAYS })}
- </Text>
- <Text as='p' size='xs' colour='muted'>
- {t(
- 'onboarding.selectPlan.timeline.chargeDesc',
- )}
- </Text>
- </div>
- </div>
- </div>
- </div>
-
- <div
- id='checkout-container'
- className='mt-6 min-h-[100px]'
- />
- </div>
- )}
-
{currentStep === 'create_project' && (
<form onSubmit={handleCreateProject}>
<Text
@@ -1326,66 +1140,6 @@ const Onboarding = () => {
{t('common.next')}
</Button>
)}
- {currentStep === 'select_plan' && (
- <>
- {hasCompletedCheckout ? (
- <Button onClick={goNext} primary large>
- {t('common.continue')}
- </Button>
- ) : (
- <Button
- onClick={() => {
- if (!isPaddleLoaded || !(window as any).Paddle) {
- toast.error(
- 'Payment script is still loading. Please try again.',
- )
- return
- }
-
- const tier =
- PLAN_LIMITS[
- selectedPlan as keyof typeof PLAN_LIMITS
- ]
- if (!tier) return
-
- const product =
- selectedBillingFrequency ===
- BillingFrequency.monthly
- ? (tier as any).pid
- : (tier as any).ypid
-
- ;(window as any).Paddle.Checkout.open({
- product,
- method: 'inline',
- frameTarget: 'checkout-container',
- frameInitialHeight: 416,
- frameStyle:
- 'width:100%; min-width:312px; background-color: transparent; border: none; border-radius: 10px;',
- email: user?.email,
- passthrough: JSON.stringify({
- uid: user?.id,
- }),
- locale:
- paddleLanguageMapping[i18n.language] ||
- i18n.language,
- displayModeTheme: theme,
- country: metainfo.country,
- })
-
- setTimeout(() => {
- document
- .querySelector('#checkout-container')
- ?.scrollIntoView({ behavior: 'smooth' })
- }, 500)
- }}
- primary
- large
- >
- {t('onboarding.selectPlan.startTrial')}
- </Button>
- )}
- </>
- )}
{currentStep === 'create_project' && (
<Button
onClick={() => handleCreateProject()}
diff --git a/web/app/routes/checkout.tsx b/web/app/routes/checkout.tsx
new file mode 100644
index 000000000..9969b2d10
--- /dev/null
+++ b/web/app/routes/checkout.tsx
@@ -0,0 +1,91 @@
+import { useTranslation } from 'react-i18next'
+import type { LoaderFunctionArgs, MetaFunction } from 'react-router'
+import { data, redirect } from 'react-router'
+import type { SitemapFunction } from 'remix-sitemap'
+
+import { getAuthenticatedUser, serverFetch } from '~/api/api.server'
+import { isSelfhosted } from '~/lib/constants'
+import { DEFAULT_METAINFO, Metainfo } from '~/lib/models/Metainfo'
+import Checkout from '~/pages/Checkout'
+import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'
+import {
+ redirectIfNotAuthenticated,
+ createHeadersWithCookies,
+} from '~/utils/session.server'
+
+export const sitemap: SitemapFunction = () => ({
+ exclude: true,
+})
+
+export const meta: MetaFunction = () => {
+ // eslint-disable-next-line react-hooks/rules-of-hooks
+ const { t } = useTranslation('common')
+
+ return [
+ ...getTitle(t('titles.checkout')),
+ ...getDescription(t('description.signup')),
+ ...getPreviewImage(),
+ ]
+}
+
+export interface CheckoutLoaderData {
+ metainfo: Metainfo
+}
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ if (isSelfhosted) {
+ return redirect('/onboarding', 302)
+ }
+
+ redirectIfNotAuthenticated(request)
+
+ const authResult = await getAuthenticatedUser(request)
+ const cookies: string[] = authResult?.cookies || []
+
+ const user = authResult?.user?.user
+
+ if (!user?.hasCompletedOnboarding) {
+ if (cookies.length > 0) {
+ return redirect('/onboarding', {
+ headers: createHeadersWithCookies(cookies),
+ })
+ }
+ return redirect('/onboarding')
+ }
+
+ // If the user already has a paid subscription, skip checkout
+ if (
+ user?.planCode &&
+ user.planCode !== 'trial' &&
+ user.planCode !== 'none'
+ ) {
+ if (cookies.length > 0) {
+ return redirect('/dashboard', {
+ headers: createHeadersWithCookies(cookies),
+ })
+ }
+ return redirect('/dashboard')
+ }
+
+ const metainfoResult = await serverFetch<Metainfo>(
+ request,
+ 'user/metainfo',
+ { skipAuth: true },
+ )
+ const metainfo = metainfoResult.data ?? DEFAULT_METAINFO
+ const allCookies = [...cookies, ...metainfoResult.cookies]
+
+ const loaderData: CheckoutLoaderData = { metainfo }
+
+ if (allCookies.length > 0) {
+ return data(loaderData, {
+ headers: createHeadersWithCookies(allCookies),
+ })
+ }
+
+ return loaderData
+}
+
+export default function CheckoutRoute() {
+ return <Checkout />
+}
diff --git a/web/app/routes/dashboard.tsx b/web/app/routes/dashboard.tsx
index 418804f0f..c32c87b41 100644
--- a/web/app/routes/dashboard.tsx
+++ b/web/app/routes/dashboard.tsx
@@ -8,6 +8,7 @@ import { data, redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
import { getAuthenticatedUser, serverFetch } from '~/api/api.server'
+import { isSelfhosted } from '~/lib/constants'
import { Project } from '~/lib/models/Project'
import Dashboard from '~/pages/Dashboard'
import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'
@@ -197,16 +198,29 @@ export async function loader({ request }: LoaderFunctionArgs) {
const authResult = await getAuthenticatedUser(request)
const authCookies = authResult?.cookies || []
- if (authResult?.user?.user && !authResult.user.user.hasCompletedOnboarding) {
+ const user = authResult?.user?.user
+ if (user && !user.hasCompletedOnboarding) {
if (authCookies.length > 0) {
return redirect('/onboarding', {
headers: createHeadersWithCookies(authCookies),
})
}
-
return redirect('/onboarding')
}
+ if (
+ !isSelfhosted &&
+ user &&
+ (!user.planCode || user.planCode === 'trial' || user.planCode === 'none')
+ ) {
+ if (authCookies.length > 0) {
+ return redirect('/checkout', {
+ headers: createHeadersWithCookies(authCookies),
+ })
+ }
+ return redirect('/checkout')
+ }
+
const url = new URL(request.url)
const page = parseInt(url.searchParams.get('page') || '1', 10)
const pageSize = parseInt(url.searchParams.get('pageSize') || '12', 10)
diff --git a/web/app/routes/login.tsx b/web/app/routes/login.tsx
index 34dc1f8d0..6eb2caf48 100644
--- a/web/app/routes/login.tsx
+++ b/web/app/routes/login.tsx
@@ -8,6 +8,7 @@ import type {
import { redirect, data } from 'react-router'
import { getAuthenticatedUser, loginUser, serverFetch } from '~/api/api.server'
+import { isSelfhosted } from '~/lib/constants'
import Signin from '~/pages/Auth/Signin'
import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'
import {
@@ -35,8 +36,15 @@ export async function loader({ request }: LoaderFunctionArgs) {
const authResult = await getAuthenticatedUser(request)
if (authResult) {
- if (!authResult.user.user.hasCompletedOnboarding) {
+ const user = authResult.user.user
+
+ if (!user.hasCompletedOnboarding) {
return redirect('/onboarding')
+ } else if (
+ !isSelfhosted &&
+ (!user.planCode || user.planCode === 'trial' || user.planCode === 'none')
+ ) {
+ return redirect('/checkout')
}
return redirect('/dashboard')
}
@@ -82,7 +90,7 @@ export async function action({ request }: ActionFunctionArgs) {
const result = await serverFetch<{
accessToken: string
refreshToken: string
- user: { hasCompletedOnboarding: boolean }
+ user: { hasCompletedOnboarding: boolean; planCode?: string }
}>(request, '2fa/authenticate', {
method: 'POST',
body: { twoFactorAuthenticationCode },
@@ -104,9 +112,17 @@ export async function action({ request }: ActionFunctionArgs) {
!dontRemember,
)
- const redirectTo = user.hasCompletedOnboarding
- ? '/dashboard'
- : '/onboarding'
+ let redirectTo = '/dashboard'
+ if (user) {
+ if (!user.hasCompletedOnboarding) {
+ redirectTo = '/onboarding'
+ } else if (
+ !isSelfhosted &&
+ (!user.planCode || user.planCode === 'trial' || user.planCode === 'none')
+ ) {
+ redirectTo = '/checkout'
+ }
+ }
return redirect(redirectTo, {
headers: createHeadersWithCookies(cookies),
@@ -148,9 +164,18 @@ export async function action({ request }: ActionFunctionArgs) {
)
}
- const redirectTo = result.data?.user.hasCompletedOnboarding
- ? '/dashboard'
- : '/onboarding'
+ const loggedInUser = result.data?.user
+ let redirectTo = '/dashboard'
+ if (loggedInUser) {
+ if (!loggedInUser.hasCompletedOnboarding) {
+ redirectTo = '/onboarding'
+ } else if (
+ !isSelfhosted &&
+ (!loggedInUser.planCode || loggedInUser.planCode === 'trial' || loggedInUser.planCode === 'none')
+ ) {
+ redirectTo = '/checkout'
+ }
+ }
return redirect(redirectTo, {
headers: createHeadersWithCookies(result.cookies),
diff --git a/web/app/routes/onboarding.tsx b/web/app/routes/onboarding.tsx
index 2e148ef39..10e6bf8e4 100644
--- a/web/app/routes/onboarding.tsx
+++ b/web/app/routes/onboarding.tsx
@@ -8,6 +8,7 @@ import { data, redirect } from 'react-router'
import { SitemapFunction } from 'remix-sitemap'
import { getAuthenticatedUser, serverFetch } from '~/api/api.server'
+import { isSelfhosted } from '~/lib/constants'
import { DEFAULT_METAINFO, Metainfo } from '~/lib/models/Metainfo'
import { Project } from '~/lib/models/Project'
import { User } from '~/lib/models/User'
@@ -73,6 +74,20 @@ export async function loader({ request }: LoaderFunctionArgs) {
const allCookies = [...cookies, ...metainfoResult.cookies]
if (user?.user?.hasCompletedOnboarding) {
+ // Redirect to checkout if user hasn't subscribed yet
+ const userPlanCode = user.user.planCode
+ if (
+ !isSelfhosted &&
+ (!userPlanCode || userPlanCode === 'trial' || userPlanCode === 'none')
+ ) {
+ if (allCookies.length > 0) {
+ return redirect('/checkout', {
+ headers: createHeadersWithCookies(allCookies),
+ })
+ }
+ return redirect('/checkout')
+ }
+
if (allCookies.length > 0) {
return redirect('/dashboard', {
headers: createHeadersWithCookies(allCookies),
@@ -82,7 +97,10 @@ export async function loader({ request }: LoaderFunctionArgs) {
return redirect('/dashboard')
}
- const onboardingStep = user?.user?.onboardingStep as string | undefined
+ const rawOnboardingStep = user?.user?.onboardingStep as string | undefined
+ // Migrate users who were on the removed select_plan step
+ const onboardingStep =
+ rawOnboardingStep === 'select_plan' ? 'create_project' : rawOnboardingStep
if (
onboardingStep === 'setup_tracking' ||
diff --git a/web/app/routes/signup.tsx b/web/app/routes/signup.tsx
index 53256a00f..b6618ac3e 100644
--- a/web/app/routes/signup.tsx
+++ b/web/app/routes/signup.tsx
@@ -39,7 +39,9 @@ export async function loader({ request }: LoaderFunctionArgs) {
const authResult = await getAuthenticatedUser(request)
if (authResult) {
- if (!authResult.user.user.hasCompletedOnboarding) {
+ const user = authResult.user.user
+
+ if (!user.hasCompletedOnboarding) {
return redirect('/onboarding')
}
return redirect('/dashboard')
diff --git a/web/app/utils/routes.ts b/web/app/utils/routes.ts
index f2d846d6e..70deb8fd1 100644
--- a/web/app/utils/routes.ts
+++ b/web/app/utils/routes.ts
@@ -6,6 +6,7 @@ const routes = Object.freeze({
captchaLanding: '/captcha',
captchaDemo: '/captcha/demo',
onboarding: '/onboarding',
+ checkout: '/checkout',
reset_password: '/recovery',
new_password_form: '/password-reset/:id',
confirm_share: '/share/:id',
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 864bd59f4..070501203 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -2134,6 +2134,18 @@
"live": "You can see our live metrics on our <livedemo>public dashboard</livedemo>. You can also make your own Swetrix Dashboards public and adjust them to your needs."
}
},
+ "checkout": {
+ "title": "Start your free trial",
+ "subtitle": "Add payment details to start your {{days}}-day free trial. You won't be charged until your trial ends, and you can cancel anytime.",
+ "noChargeToday": "Your card will not be charged today.",
+ "willRemind": "We'll remind you before your trial ends",
+ "freeTrialAnytime": "Free {{days}} day trial, cancel any time",
+ "dueEnd": "Due {{date}}",
+ "dueToday": "Due today ({{days}} days free)",
+ "free": "$0",
+ "next": "Next",
+ "termsDesc": "By continuing, you agree to the Terms of Use applicable to Swetrix and confirm you have read our <privacy>Privacy Policy</privacy>."
+ },
"onboarding": {
"welcome": "Welcome to Swetrix",
"title": "Get started",
@@ -2252,7 +2264,8 @@
"cookiePolicy": "Cookie Policy",
"termsAndConditions": "Terms and Conditions",
"gaAlternative": "Cookieless Google Analytics alternative",
- "projectWithPassword": "Website analytics - password required"
+ "projectWithPassword": "Website analytics - password required",
+ "checkout": "Checkout"
},
"description": {
"default": "Swetrix is a privacy-first, cookieless Google Analytics alternative with real-time analytics, no sampling, and built-in performance & error monitoring.",