π 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Migrate from no-credit card free trial to requiring users enter credit card details first
Blue Mouse5a1469677db7
diff --git a/backend/apps/cloud/src/common/templates/en/customer_sign-up.html b/backend/apps/cloud/src/common/templates/en/customer_sign-up.htmlindex 62eb0694c..12366812a 100644--- a/backend/apps/cloud/src/common/templates/en/customer_sign-up.html+++ b/backend/apps/cloud/src/common/templates/en/customer_sign-up.html@@ -1,9 +1,29 @@-Hello and welcome to Swetrix! We're excited to have you with us.<br />-Swetrix is an ethical and powerful web analytics platform that respects your-privacy and data.<br /><br />-To get started, please <a href="{{url}}">click here</a> verify your email-address.<br /><br />-If youβre having trouble with the link above, copy and paste the URL below-directly into your web browser:<br />+Welcome to Swetrix! We're thrilled to have you on board.<br /><br />++Swetrix is an ethical, cookieless web analytics platform. We help you understand your website traffic, track errors, and make data-driven decisions without invading your users' privacy.<br /><br />++<b>Your 14-day free trial has started.</b> You have full access to all features during your trial. Here's what happens next:<br />+<ul>+ <li><b>Today</b> β Explore all features with no limits</li>+ <li><b>Day 12</b> β We'll send you a reminder before your trial ends</li>+ <li><b>Day 14</b> β Your subscription begins automatically, unless you cancel</li>+</ul>++You can manage your subscription or cancel anytime from your <a href="https://swetrix.com/billing" target="_blank">Billing page</a>.<br /><br />++<b>Get started:</b><br />+<ul>+ <li><a href="https://swetrix.com/dashboard" target="_blank">Go to your Dashboard</a></li>+ <li><a href="https://swetrix.com/docs" target="_blank">Read the Setup Guide</a></li>+ <li><a href="https://swetrix.com/docs/integrations" target="_blank">Browse Integrations</a></li>+</ul>++To verify your email address, please <a href="{{url}}">click here</a>.<br /><br />++If you're having trouble with the link above, copy and paste this URL into your browser:<br />{{url}}<br /><br />-If you did not request this email, feel free to ignore it :)++Questions? Just reply to this email - we're happy to help.<br /><br />++Andrii Romasiun,+Swetrixdiff --git a/backend/apps/cloud/src/common/templates/en/trial-ends-tomorrow.html b/backend/apps/cloud/src/common/templates/en/trial-ends-tomorrow.htmlindex 771e806d5..3413a893f 100644--- a/backend/apps/cloud/src/common/templates/en/trial-ends-tomorrow.html+++ b/backend/apps/cloud/src/common/templates/en/trial-ends-tomorrow.html@@ -1,12 +1,14 @@-Your free Swetrix trial ends tomorrow, we hope that you enjoyed using Swetrix-and liked the experience of using a service that respects user privacy, does not-annoy your users with cookie banners and keeps your website as fast as possible-:)-<br />-If you wish to continue using Swetrix and receiving all the needed analytics-data easily, you'll need to <a href="{{url}}" target="_blank">upgrade</a> your-account to one of our subscription plans.-<br />-<br />-Please reply back to this email in case you have any questions or need-assistance.+Hey there,<br /><br />++Just a heads up - your free Swetrix trial ends in about 48 hours.<br /><br />++Most companies don't email you before your trial expires because they hope you'll forget and get charged anyway. We're doing the opposite β we don't want your money if you don't want to give it to us.<br /><br />++If you're loving Swetrix, you don't need to do anything. Your subscription will begin automatically and you'll keep getting privacy-first analytics without interruption.<br /><br />++If it's not the right fit, no hard feelings. You can <a href="{{url}}" target="_blank">cancel from your billing page</a> before the trial ends and you won't be charged.<br /><br />++Got questions about your plan, features, or anything else? Just reply to this email β we're here to help.<br /><br />++Andrii Romasiun,+Swetrixdiff --git a/backend/apps/cloud/src/mailer/mailer.service.ts b/backend/apps/cloud/src/mailer/mailer.service.tsindex 5220d5649..398f810e1 100644--- a/backend/apps/cloud/src/mailer/mailer.service.ts+++ b/backend/apps/cloud/src/mailer/mailer.service.ts@@ -11,7 +11,7 @@ const TEMPLATES_PATH = path.join(__dirname, '..', 'common', 'templates')const metaInfoJson = {[LetterTemplate.SignUp]: {subject: {- en: () => 'Please verify your account registration',+ en: () => 'Welcome to Swetrix β your 14-day trial has started',},},[LetterTemplate.ConfirmPasswordChange]: {@@ -78,7 +78,7 @@ const metaInfoJson = {},[LetterTemplate.TrialEndsTomorrow]: {subject: {- en: () => 'Your free Swetrix trial ends tomorrow',+ en: () => 'Your Swetrix trial ends in 48 hours',},},[LetterTemplate.ProjectSubscriberInvitation]: {diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.tsindex 27c6a83dc..728edd246 100644--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts@@ -1364,11 +1364,10 @@ export class TaskManagerService {async trialReminder() {const users = await this.userService.find({where: {- planCode: PlanCode.trial,+ planCode: Not(PlanCode.none),trialEndDate: Between(- // between today & tomorrownew Date(),- new Date(new Date().getTime() + 24 * 60 * 60 * 1000),+ new Date(new Date().getTime() + 48 * 60 * 60 * 1000),),trialReminderSent: false,},diff --git a/backend/apps/cloud/src/user/dto/cancel-subscription.dto.ts b/backend/apps/cloud/src/user/dto/cancel-subscription.dto.tsnew file mode 100644index 000000000..8ab87fb4f--- /dev/null+++ b/backend/apps/cloud/src/user/dto/cancel-subscription.dto.ts@@ -0,0 +1,10 @@+import { ApiPropertyOptional } from '@nestjs/swagger'+import { IsOptional, IsString, MaxLength } from 'class-validator'++export class CancelSubscriptionDTO {+ @ApiPropertyOptional()+ @IsOptional()+ @IsString()+ @MaxLength(2000)+ feedback?: string+}diff --git a/backend/apps/cloud/src/user/entities/cancellation-feedback.entity.ts b/backend/apps/cloud/src/user/entities/cancellation-feedback.entity.tsnew file mode 100644index 000000000..892b8f479--- /dev/null+++ b/backend/apps/cloud/src/user/entities/cancellation-feedback.entity.ts@@ -0,0 +1,24 @@+import {+ Column,+ CreateDateColumn,+ Entity,+ PrimaryGeneratedColumn,+} from 'typeorm'++@Entity()+export class CancellationFeedback {+ @PrimaryGeneratedColumn('uuid')+ id: string++ @Column('varchar', { length: 254, nullable: true })+ email: string++ @Column('varchar', { length: 50, nullable: true })+ planCode: string++ @Column('text', { nullable: true })+ feedback: string++ @CreateDateColumn()+ createdAt: Date+}diff --git a/backend/apps/cloud/src/user/entities/user.entity.ts b/backend/apps/cloud/src/user/entities/user.entity.tsindex cff1b2550..acd86b5b1 100644--- a/backend/apps/cloud/src/user/entities/user.entity.ts+++ b/backend/apps/cloud/src/user/entities/user.entity.ts@@ -209,6 +209,7 @@ export enum OnboardingStep {FEATURE_TRAFFIC = 'feature_traffic',FEATURE_ERRORS = 'feature_errors',FEATURE_SESSIONS = 'feature_sessions',+ SELECT_PLAN = 'select_plan',CREATE_PROJECT = 'create_project',SETUP_TRACKING = 'setup_tracking',WAITING_FOR_EVENTS = 'waiting_for_events',diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.tsindex 17072d929..a2b1e87e1 100644--- a/backend/apps/cloud/src/user/user.controller.ts+++ b/backend/apps/cloud/src/user/user.controller.ts@@ -55,6 +55,7 @@ import { AuthService } from '../auth/auth.service'import { LetterTemplate } from '../mailer/letter'import { AppLoggerService } from '../logger/logger.service'import { DeleteSelfDTO } from './dto/delete-self.dto'+import { CancelSubscriptionDTO } from './dto/cancel-subscription.dto'import {checkRateLimit,getGeoDetails,@@ -735,6 +736,53 @@ export class UserController {return this.userService.previewSubscription(id, planId)}+ @ApiBearerAuth()+ @Post('subscription/cancel')+ async cancelSubscription(+ @CurrentUserId() id: string,+ @Body() body: CancelSubscriptionDTO,+ @Headers() headers: Record<string, string>,+ @Ip() requestIp: string,+ ): Promise<void> {+ this.logger.log({ id }, 'POST /subscription/cancel')++ const ip = getIPFromHeaders(headers) || requestIp || ''+ const user = await this.userService.findOne({ where: { id } })++ if (!user) {+ throw new BadRequestException('User not found')+ }++ if (_includes(UNPAID_PLANS, user.planCode)) {+ throw new BadRequestException('No paid subscription to cancel')+ }++ await this.userService.cancelSubscription(id)++ if (body.feedback) {+ try {+ await this.userService.saveCancellationFeedback(+ user.email,+ user.planCode,+ body.feedback,+ )+ } catch (reason) {+ this.logger.error(+ '[ERROR] Failed to save cancellation feedback:',+ reason,+ )+ }+ }++ await trackCustom(ip, headers['user-agent'], {+ ev: 'SUBSCRIPTION_CANCELLED',+ meta: {+ plan: user.planCode,+ feedback_given: !!body.feedback,+ },+ })+ }+// Used to unsubscribe from email reports@Get('/unsubscribe/:token')@Public()diff --git a/backend/apps/cloud/src/user/user.module.ts b/backend/apps/cloud/src/user/user.module.tsindex 4515c1c41..06363ee0b 100644--- a/backend/apps/cloud/src/user/user.module.ts+++ b/backend/apps/cloud/src/user/user.module.ts@@ -13,12 +13,19 @@ import { AppLoggerModule } from '../logger/logger.module'import { ProjectModule } from '../project/project.module'import { RefreshToken } from './entities/refresh-token.entity'import { DeleteFeedback } from './entities/delete-feedback.entity'+import { CancellationFeedback } from './entities/cancellation-feedback.entity'import { Message } from '../integrations/telegram/entities/message.entity'import { OrganisationModule } from '../organisation/organisation.module'@Module({imports: [- TypeOrmModule.forFeature([User, RefreshToken, DeleteFeedback, Message]),+ TypeOrmModule.forFeature([+ User,+ RefreshToken,+ DeleteFeedback,+ CancellationFeedback,+ Message,+ ]),ActionTokensModule,MailerModule,forwardRef(() => AuthModule),diff --git a/backend/apps/cloud/src/user/user.service.ts b/backend/apps/cloud/src/user/user.service.tsindex 7deadd686..4d1d6abfb 100644--- a/backend/apps/cloud/src/user/user.service.ts+++ b/backend/apps/cloud/src/user/user.service.ts@@ -35,6 +35,7 @@ import {import { UserProfileDTO } from './dto/user.dto'import { RefreshToken } from './entities/refresh-token.entity'import { DeleteFeedback } from './entities/delete-feedback.entity'+import { CancellationFeedback } from './entities/cancellation-feedback.entity'import { UserGoogleDTO } from './dto/user-google.dto'import { UserGithubDTO } from './dto/user-github.dto'import { EMAIL_ACTION_ENCRYPTION_KEY } from '../common/constants'@@ -108,6 +109,8 @@ export class UserService {private readonly refreshTokenRepository: Repository<RefreshToken>,@InjectRepository(DeleteFeedback)private readonly deleteFeedbackRepository: Repository<DeleteFeedback>,+ @InjectRepository(CancellationFeedback)+ private readonly cancellationFeedbackRepository: Repository<CancellationFeedback>,private readonly organisationService: OrganisationService,) {}@@ -439,6 +442,57 @@ export class UserService {)}+ async saveCancellationFeedback(+ email: string,+ planCode: string,+ feedback: string,+ ) {+ return this.cancellationFeedbackRepository.save({+ email,+ planCode,+ feedback,+ })+ }++ async cancelSubscription(id: string) {+ const user = await this.findOne({ where: { id } })++ if (!user?.subID) {+ throw new BadRequestException('No active subscription found')+ }++ const url =+ 'https://vendors.paddle.com/api/2.0/subscription/users/cancel'++ try {+ const result = await axios.post(url, {+ vendor_id: Number(PADDLE_VENDOR_ID),+ vendor_auth_code: PADDLE_API_KEY,+ subscription_id: Number(user.subID),+ })++ if (!result.data?.success) {+ console.error(+ '[ERROR] (cancelSubscription) success -> false:',+ result.data,+ )+ throw new InternalServerErrorException(+ 'Failed to cancel subscription with payment provider',+ )+ }+ } catch (error) {+ if (error instanceof InternalServerErrorException) throw error++ console.error(+ '[ERROR] (cancelSubscription):',+ error?.response?.data?.error?.message || error,+ )+ throw new BadRequestException(+ 'Failed to cancel subscription. Please try again or contact support.',+ )+ }+ }+async updateSubscription(id: string, planID: number) {const user = await this.findOne({ where: { id } })const plan = this.getPlanById(planID)diff --git a/backend/apps/cloud/src/webhook/webhook.controller.ts b/backend/apps/cloud/src/webhook/webhook.controller.tsindex f2ad1806b..7ef5f1f27 100644--- a/backend/apps/cloud/src/webhook/webhook.controller.ts+++ b/backend/apps/cloud/src/webhook/webhook.controller.ts@@ -140,6 +140,7 @@ export class WebhookController {}}+ const isTrialing = status === 'trialing'const shouldUnlock =body.alert_name === 'subscription_created' ||isNextPlan(currentUser.planCode, plan.id)@@ -150,7 +151,7 @@ export class WebhookController {dashboardBlockReason: DashboardBlockReason.payment_failed,isAccountBillingSuspended: true,}- : shouldUnlock+ : shouldUnlock || isTrialing? {dashboardBlockReason: null,planExceedContactedAt: null,@@ -158,7 +159,7 @@ export class WebhookController {}: {}- const updateParams = {+ const updateParams: Record<string, any> = {planCode: plan.id,subID,subUpdateURL,@@ -172,6 +173,10 @@ export class WebhookController {...statusParams,}+ if (isTrialing && nextBillDate) {+ updateParams.trialEndDate = nextBillDate+ }+await this.userService.update(currentUser.id, updateParams)await this.projectService.clearProjectsRedisCache(currentUser.id)diff --git a/backend/migrations/mysql/2026_02_22_trial_with_cc.sql b/backend/migrations/mysql/2026_02_22_trial_with_cc.sqlnew file mode 100644index 000000000..eeaedfda7--- /dev/null+++ b/backend/migrations/mysql/2026_02_22_trial_with_cc.sql@@ -0,0 +1,10 @@+ALTER TABLE `user` MODIFY COLUMN `onboardingStep` enum('language','welcome','feature_traffic','feature_errors','feature_sessions','select_plan','create_project','setup_tracking','waiting_for_events','verify_email','completed') NOT NULL DEFAULT 'language';++CREATE TABLE `cancellation_feedback` (+ `id` varchar(36) NOT NULL,+ `email` varchar(254) DEFAULT NULL,+ `planCode` varchar(50) DEFAULT NULL,+ `feedback` text DEFAULT NULL,+ `createdAt` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),+ PRIMARY KEY (`id`)+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;diff --git a/web/app/pages/Auth/Signup/Signup.tsx b/web/app/pages/Auth/Signup/Signup.tsxindex 51df57b58..7973cfd65 100644--- a/web/app/pages/Auth/Signup/Signup.tsx+++ b/web/app/pages/Auth/Signup/Signup.tsx@@ -23,6 +23,8 @@ 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'@@ -31,6 +33,7 @@ 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'@@ -38,6 +41,7 @@ import routes from '~/utils/routes'import { MIN_PASSWORD_CHARS } from '~/utils/validator'const HASH_CHECK_FREQUENCY = 1000+const INITIAL_VISIBLE_PLANS = 3const featureIcons = [ChartBarIcon,@@ -46,6 +50,8 @@ const featureIcons = [SparkleIcon,]+const formatEventsLong = (value: number) => value.toLocaleString('en-US')+const featureKeys = ['realTimeAnalytics','eventTracking',@@ -63,6 +69,18 @@ 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())@@ -240,11 +258,106 @@ const Signup = () => {</Text>{isSelfhosted ? null : (<Text as='p' colour='muted' className='mt-2'>- {t('auth.signup.noCC')}+ {t('auth.signup.trialSubtitle')}</Text>)}</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>+ )}+<divclassName={cn('grid gap-3',@@ -309,15 +422,6 @@ const Signup = () => {disabled={isLoading}onChange={() => clearFieldError('password')}/>- <Input- name='repeat'- type='password'- label={t('auth.common.repeat')}- error={getFieldError('repeat')}- disabled={isLoading}- onChange={() => clearFieldError('repeat')}- />-{/* Hidden fields for checkbox values since Headless UI Checkbox doesn't submit natively */}<input type='hidden' name='tos' value={tos ? 'true' : 'false'} /><inputdiff --git a/web/app/pages/Onboarding/Onboarding.tsx b/web/app/pages/Onboarding/Onboarding.tsxindex 62636aaa1..30c4451d5 100644--- a/web/app/pages/Onboarding/Onboarding.tsx+++ b/web/app/pages/Onboarding/Onboarding.tsx@@ -9,6 +9,9 @@ import {FileTextIcon,ClockIcon,FolderPlusIcon,+ BellIcon,+ CreditCardIcon,+ RocketLaunchIcon,} from '@phosphor-icons/react'import { useState, useEffect, useRef, useCallback } from 'react'import { Trans, useTranslation } from 'react-i18next'@@ -17,11 +20,18 @@ 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,@@ -33,6 +43,7 @@ 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,@@ -47,7 +58,7 @@ import Alert from '~/ui/Alert'import { Text } from '~/ui/Text'import Textarea from '~/ui/Textarea'import { trackCustom } from '~/utils/analytics'-import { cn } from '~/utils/generic'+import { cn, loadScript } from '~/utils/generic'import routes from '~/utils/routes'const MAX_PROJECT_NAME_LENGTH = 50@@ -66,6 +77,7 @@ type OnboardingStep =| 'feature_traffic'| 'feature_errors'| 'feature_sessions'+ | 'select_plan'| 'create_project'| 'setup_tracking'| 'verify_email'@@ -77,10 +89,14 @@ 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')}@@ -88,6 +104,18 @@ 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 = {@@ -447,6 +475,24 @@ 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'@@ -488,6 +534,29 @@ 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@@ -857,6 +926,123 @@ 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@@ -1140,6 +1326,66 @@ 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' && (<ButtononClick={() => handleCreateProject()}diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsxindex c545ce62c..1b177fc78 100644--- a/web/app/pages/UserSettings/UserSettings.tsx+++ b/web/app/pages/UserSettings/UserSettings.tsx@@ -244,7 +244,7 @@ interface Form extends Partial<User> {}const UserSettings = () => {- const { user, logout, mergeUser, isLoading: authLoading } = useAuth()+ const { user, logout, mergeUser, loadUser, isLoading: authLoading } = useAuth()const loaderData = useLoaderData<UserSettingsLoaderData>()const { theme } = useTheme()@@ -259,6 +259,8 @@ const UserSettings = () => {const [searchParams, setSearchParams] = useSearchParams()const [isCancelSubModalOpened, setIsCancelSubModalOpened] = useState(false)+ const [cancellationFeedback, setCancellationFeedback] = useState('')+ const [isCancellingSubscription, setIsCancellingSubscription] = useState(false)const [lastEvent, setLastEvent] = useState<{ event: string } | null>(null)const metainfo = useMemo(() => {@@ -287,7 +289,12 @@ const UserSettings = () => {} = user || {}const isSubscriber = !['none', 'trial', 'free'].includes(planCode || '')- const isTrial = planCode === 'trial'+ const isLegacyTrial = planCode === 'trial'+ const isTrialingPaidPlan = (() => {+ if (!trialEndDate || !isSubscriber) return false+ return dayjs.utc(trialEndDate).isAfter(dayjs.utc())+ })()+ const isTrial = isLegacyTrial || isTrialingPaidPlanconst isNoSub = planCode === 'none'const totalUsage = (() => {@@ -360,30 +367,15 @@ const UserSettings = () => {})()const onSubscriptionCancel = () => {- if (!subCancelURL) {- toast.error(t('apiNotifications.somethingWentWrong'))- return- }+ setIsCancellingSubscription(true)- if (!(window as any).Paddle) {- window.location.replace(subCancelURL)- return+ const formData = new FormData()+ formData.set('intent', 'cancel-subscription')+ if (cancellationFeedback.trim()) {+ formData.set('feedback', cancellationFeedback.trim())}- ;(window as any).Paddle.Checkout.open({- override: subCancelURL,- method: 'inline',- frameTarget: 'checkout-container',- frameInitialHeight: 416,- frameStyle:- 'width:100%; min-width:312px; background-color: #f9fafb; border: none; border-radius: 10px; margin-top: 10px;',- locale: paddleLanguageMapping[language] || language,- displayModeTheme: theme,- country: metainfo.country,- })- setTimeout(() => {- document.querySelector('#checkout-container')?.scrollIntoView()- }, 500)+ fetcher.submit(formData, { method: 'POST', action: '/user-settings' })}const onUpdatePaymentDetails = () => {@@ -505,8 +497,15 @@ const UserSettings = () => {logout()toast.success(t('apiNotifications.accountDeleted'))navigate(routes.main)+ } else if (intent === 'cancel-subscription') {+ setIsCancellingSubscription(false)+ setCancellationFeedback('')+ setIsCancelSubModalOpened(false)+ toast.success(t('billing.subscriptionCancelledSuccess'))+ loadUser()}} else if (fetcher.data?.error) {+ setIsCancellingSubscription(false)if (pendingToggles.current.has('live-visitors')) {mergeUser({showLiveVisitorsInTitle: pendingToggles.current.get('live-visitors'),@@ -1271,7 +1270,8 @@ const UserSettings = () => {title={t('profileSettings.trialActive')}className='mb-6'>- {trialEndsOnMessage} {t('billing.trialDescription')}+ {trialEndsOnMessage}{' '}+ {t('billing.trialChargeWarning')}</Alert>) : null}@@ -1785,25 +1785,46 @@ const UserSettings = () => {/><ModalonClose={() => {- setIsCancelSubModalOpened(false)+ if (!isCancellingSubscription) {+ setIsCancelSubModalOpened(false)+ setCancellationFeedback('')+ }}}- onSubmit={() => {- setIsCancelSubModalOpened(false)- onSubscriptionCancel()- }}- submitText={t('common.yes')}- closeText={t('common.no')}+ onSubmit={onSubscriptionCancel}+ submitText={t('billing.confirmCancellation')}+ closeText={t('common.cancel')}title={t('pricing.cancelTitle')}submitType='danger'type='error'+ isLoading={isCancellingSubscription}+ submitDisabled={isCancellingSubscription}message={- <Trans- t={t}- i18nKey='pricing.cancelDesc'- values={{- email: CONTACT_EMAIL,- }}- />+ <div className='space-y-4'>+ <Trans+ t={t}+ i18nKey='pricing.cancelDesc'+ values={{+ email: CONTACT_EMAIL,+ }}+ />+ <div>+ <label+ htmlFor='cancellation-feedback'+ className='block text-sm font-medium text-gray-700 dark:text-gray-300'+ >+ {t('billing.cancellationFeedbackLabel')}+ </label>+ <textarea+ id='cancellation-feedback'+ className='mt-1 block w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm shadow-sm focus:border-indigo-500 focus:ring-indigo-500 focus:outline-none dark:border-slate-600 dark:bg-slate-800 dark:text-white'+ rows={3}+ placeholder={t('billing.cancellationFeedbackPlaceholder')}+ value={cancellationFeedback}+ onChange={(e) => setCancellationFeedback(e.target.value)}+ disabled={isCancellingSubscription}+ />+ </div>+ </div>}isOpened={isCancelSubModalOpened}/>diff --git a/web/app/routes/signup.tsx b/web/app/routes/signup.tsxindex 684d61e5c..53256a00f 100644--- a/web/app/routes/signup.tsx+++ b/web/app/routes/signup.tsx@@ -53,7 +53,6 @@ export interface SignupActionData {fieldErrors?: {email?: stringpassword?: string- repeat?: stringtos?: string}timestamp?: number@@ -64,7 +63,6 @@ export async function action({ request }: ActionFunctionArgs) {const email = formData.get('email')?.toString() || ''const password = formData.get('password')?.toString() || ''- const repeat = formData.get('repeat')?.toString() || ''const tos = formData.get('tos') === 'true'const checkIfLeaked = formData.get('checkIfLeaked') === 'true'@@ -82,20 +80,11 @@ export async function action({ request }: ActionFunctionArgs) {fieldErrors.password = 'Password must be at most 50 characters'}- if (password !== repeat) {- fieldErrors.repeat = 'Passwords do not match'- }-if (!tos && !isSelfhosted) {fieldErrors.tos = 'You must accept the Terms of Service'}- if (- fieldErrors.email ||- fieldErrors.password ||- fieldErrors.repeat ||- fieldErrors.tos- ) {+ if (fieldErrors.email || fieldErrors.password || fieldErrors.tos) {return data({ fieldErrors, timestamp: Date.now() }, { status: 400 })}diff --git a/web/app/routes/user-settings.tsx b/web/app/routes/user-settings.tsxindex b5161d9d4..22f471c3c 100644--- a/web/app/routes/user-settings.tsx+++ b/web/app/routes/user-settings.tsx@@ -613,6 +613,27 @@ export async function action({ request }: ActionFunctionArgs) {)}+ case 'cancel-subscription': {+ const feedback = formData.get('feedback')?.toString() || ''++ const result = await serverFetch(request, 'user/subscription/cancel', {+ method: 'POST',+ body: { feedback: feedback || undefined },+ })++ if (result.error) {+ return data<UserSettingsActionData>(+ { intent, error: result.error as string },+ { status: 400 },+ )+ }++ return data<UserSettingsActionData>(+ { intent, success: true },+ { headers: createHeadersWithCookies(result.cookies) },+ )+ }+default:return data<UserSettingsActionData>({ error: 'Unknown action' },diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex 1cbe2e47d..864bd59f4 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -145,7 +145,9 @@"communityEdition": "Community Edition","allPosts": "All posts","details": "Details",- "unknown": "Unknown"+ "unknown": "Unknown",+ "showMore": "Show {{count}} more",+ "showLess": "Show less"},"performance": {"slogan": "End user <span>performance monitoring</span> to deliver fast websites.",@@ -764,11 +766,12 @@"testimonial": "\"Swetrix has been a game changer for our analytics. They've always been on top of feature requests and have been friendly every step of the way.\""},"signup": {- "button": "Sign up",+ "button": "Continue to checkout","tos": "I do accept <tos>Terms and Conditions</tos> and the <pp>Privacy Policy</pp>.","create": "Create your account","trial": "Start your free {{amount}} day trial",- "noCC": "No credit card required.",+ "trialSubtitle": "Try all features free. Cancel anytime before your trial ends.",+ "changePlanLater": "You can change your plan later or at any time.","alreadyAMember": "Already a member? <url>Sign in</url>","createAnAccount": "Create an account","insightsInMinutes": "Get better website insights in minutes",@@ -2023,6 +2026,11 @@"changePlan": "You can change or cancel your subscription plan at any time here.","membersNotification": "Pageviews, custom events and error events are counted towards the limit of the subscription of the account owner. People you invite into your projects don't need a subscription.","trialDescription": "Your free trial includes access to all features and unlimited data collection limits. When your trial ends, you'll need to select a paid plan that matches your usage to continue using Swetrix.",+ "trialChargeWarning": "You will be automatically charged when the trial ends unless you cancel. You can cancel anytime from this page β no questions asked.",+ "subscriptionCancelledSuccess": "Your subscription has been cancelled. You'll retain access until the end of your current billing period.",+ "confirmCancellation": "Cancel subscription",+ "cancellationFeedbackLabel": "We'd love to know why you're leaving (optional)",+ "cancellationFeedbackPlaceholder": "What could we have done better? We're entirely subscriber-funded and value your feedback.","usageWarningHigh": "You've used {{percentage}}% of your monthly event limit. Consider upgrading your plan to avoid service interruption.","usageWarningCritical": "Warning: You've used {{percentage}}% of your monthly event limit! Upgrade now to ensure uninterrupted service.","xPercentUsed": "{{percentage}}% used",@@ -2073,9 +2081,12 @@"yearlyBilling": "Yearly","billedYearly": "Billed yearly","switchToMonthly": "Switch to monthly billing",+ "payYearly": "Pay yearly (2 months free)",+ "upToXEvents": "Up to {{amount}} monthly events.","frequency": "Payment frequency","eventsPerMonth": "events / month","switchToYearly": "Switch to yearly billing",+ "xMonthsFree": "{{amount}} months free","trialEnded": "Trial ended","overXEvents": "Over {{amount}} events","contactUs": "Contact us",@@ -2155,6 +2166,19 @@"tip": "View real-time sessions as they happen."}},+ "selectPlan": {+ "title": "Add your payment details",+ "subtitle": "Your card will not be charged until your 14-day trial has ended, and you can cancel anytime before that.",+ "startTrial": "Start free trial",+ "timeline": {+ "today": "Today",+ "todayDesc": "Start your free trial with full access to all features",+ "reminder": "Day {{days}}",+ "reminderDesc": "We'll send you a friendly reminder before your trial ends",+ "charge": "Day {{days}}",+ "chargeDesc": "Your subscription begins unless you cancel beforehand"+ }+ },"confirm": {"navTitle": "Confirm your email","navDesc": "Check your inbox and click the confirmation link.",