📈 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
Feature flags
Blue Mouse2a45060bbed4
diff --git a/backend/apps/cloud/src/user/entities/user.entity.ts b/backend/apps/cloud/src/user/entities/user.entity.tsindex 4146f4a88..6d08b6adf 100644--- a/backend/apps/cloud/src/user/entities/user.entity.ts+++ b/backend/apps/cloud/src/user/entities/user.entity.ts@@ -203,6 +203,11 @@ export const DEFAULT_TIMEZONE = 'Etc/GMT'export const TRIAL_DURATION = 14 // days+export enum FeatureFlag {+ 'dashboard-period-selector' = 'dashboard-period-selector',+ 'dashboard-analytics-tabs' = 'dashboard-analytics-tabs',+}+@Entity()export class User {@PrimaryGeneratedColumn('uuid')@@ -215,6 +220,13 @@ export class User {})roles: UserType[]+ @Column({+ type: 'set',+ enum: FeatureFlag,+ default: [],+ })+ featureFlags: FeatureFlag[]+@Column({type: 'enum',enum: PlanCode,diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.tsindex 136f43fe0..bede8e129 100644--- a/backend/apps/cloud/src/user/user.controller.ts+++ b/backend/apps/cloud/src/user/user.controller.ts@@ -47,6 +47,7 @@ import {MAX_EMAIL_REQUESTS,PlanCode,Theme,+ FeatureFlag,} from './entities/user.entity'import { Pagination } from '../common/pagination/pagination'import {@@ -149,6 +150,17 @@ export class UserController {return this.userService.update(userId, { theme })}+ @ApiBearerAuth()+ @Put('/feature-flags')+ @UseGuards(JwtAccessTokenGuard, RolesGuard)+ @Roles(UserType.CUSTOMER, UserType.ADMIN)+ async setFeatureFlags(+ @CurrentUserId() userId: string,+ @Body('featureFlags') featureFlags: FeatureFlag[],+ ) {+ await this.userService.update(userId, { featureFlags })+ }+@ApiBearerAuth()@Put('/live-visitors')@UseGuards(JwtAccessTokenGuard, RolesGuard)diff --git a/backend/migrations/mysql/2025_01_05.sql b/backend/migrations/mysql/2025_01_05.sqlnew file mode 100644index 000000000..268414ed8--- /dev/null+++ b/backend/migrations/mysql/2025_01_05.sql@@ -0,0 +1 @@+ALTER TABLE user ADD COLUMN `featureFlags` set('dashboard-period-selector','dashboard-analytics-tabs') NOT NULL DEFAULT '' AFTER `discordWebhookUrl`;diff --git a/web/app/api/index.ts b/web/app/api/index.tsindex 5309f7cf4..aed7f81ee 100644--- a/web/app/api/index.ts+++ b/web/app/api/index.ts@@ -10,7 +10,7 @@ import { authActions } from '~/lib/reducers/auth'import { getAccessToken, removeAccessToken, setAccessToken } from '~/utils/accessToken'import { getRefreshToken, removeRefreshToken } from '~/utils/refreshToken'import { DEFAULT_ALERTS_TAKE, API_URL, DEFAULT_MONITORS_TAKE } from '~/lib/constants'-import { User } from '~/lib/models/User'+import { User, FeatureFlag } from '~/lib/models/User'import { Auth } from '~/lib/models/Auth'import { Project, Overall, LiveStats, Funnel } from '~/lib/models/Project'import { Alerts } from '~/lib/models/Alerts'@@ -1602,3 +1602,11 @@ export const getDetailsPrediction = (pid: string, password: string | undefined =.catch((error) => {throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message})++export const setFeatureFlags = (featureFlags: FeatureFlag[]) =>+ api+ .put('/user/feature-flags', { featureFlags })+ .then((response): User => response.data)+ .catch((error) => {+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message+ })diff --git a/web/app/hooks/useFeatureFlag.ts b/web/app/hooks/useFeatureFlag.tsnew file mode 100644index 000000000..b7ef6d0dd--- /dev/null+++ b/web/app/hooks/useFeatureFlag.ts@@ -0,0 +1,15 @@+import { useSelector } from 'react-redux'+import { StateType } from '~/lib/store'+import { FeatureFlag } from '~/lib/models/User'++const useFeatureFlag = (flag: FeatureFlag): boolean => {+ const { user } = useSelector((state: StateType) => state.auth)++ if (!user?.featureFlags) {+ return false+ }++ return user.featureFlags.includes(flag)+}++export default useFeatureFlagdiff --git a/web/app/lib/models/User.ts b/web/app/lib/models/User.tsindex 46c3ec0d8..7cb652275 100644--- a/web/app/lib/models/User.ts+++ b/web/app/lib/models/User.ts@@ -22,10 +22,16 @@ enum PlanCode {'10m' = '10m',}+export enum FeatureFlag {+ 'dashboard-period-selector' = 'dashboard-period-selector',+ 'dashboard-analytics-tabs' = 'dashboard-analytics-tabs',+}+export interface User {id: stringroles: string[]planCode: PlanCode+ featureFlags: FeatureFlag[]nickname: stringemail: stringisActive: booleandiff --git a/web/app/pages/Dashboard/Dashboard.tsx b/web/app/pages/Dashboard/Dashboard.tsxindex 6febfd432..46ae79b1c 100644--- a/web/app/pages/Dashboard/Dashboard.tsx+++ b/web/app/pages/Dashboard/Dashboard.tsx@@ -7,6 +7,7 @@ import _map from 'lodash/map'import { useTranslation } from 'react-i18next'import { FolderPlusIcon, MagnifyingGlassIcon, XMarkIcon } from '@heroicons/react/24/outline'import { XCircleIcon } from '@heroicons/react/24/solid'+import cx from 'clsx'import Modal from '~/ui/Modal'import { withAuthentication, auth } from '~/hoc/protected'@@ -15,6 +16,8 @@ import { isSelfhosted, LIVE_VISITORS_UPDATE_INTERVAL } from '~/lib/constants'import EventsRunningOutBanner from '~/components/EventsRunningOutBanner'import DashboardLockedBanner from '~/components/DashboardLockedBanner'import useDebounce from '~/hooks/useDebounce'+import useFeatureFlag from '~/hooks/useFeatureFlag'+import { FeatureFlag } from '~/lib/models/User'import Pagination from '~/ui/Pagination'import { useSelector } from 'react-redux'@@ -31,6 +34,8 @@ const PAGE_SIZE_OPTIONS = [12, 24, 48, 96]const Dashboard = () => {const { user } = useSelector((state: StateType) => state.auth)+ const showPeriodSelector = useFeatureFlag(FeatureFlag['dashboard-period-selector'])+ const showTabs = useFeatureFlag(FeatureFlag['dashboard-analytics-tabs'])const { t } = useTranslation('common')const [isSearchActive, setIsSearchActive] = useState(false)@@ -190,7 +195,7 @@ const Dashboard = () => {<DashboardLockedBanner /><div className='flex flex-col px-4 py-6 sm:px-6 lg:px-8'><div className='mx-auto w-full max-w-7xl'>- <div className='flex justify-between'>+ <div className={cx('flex justify-between', showTabs ? 'mb-2' : 'mb-4')}><div className='flex items-end justify-between'><h2 className='mt-2 flex items-baseline text-3xl font-bold text-gray-900 dark:text-gray-50'>{t('titles.dashboard')}@@ -232,13 +237,13 @@ const Dashboard = () => {)}</div><div className='flex items-center gap-2'>- {activeTab === 'lost-traffic' ? null : (+ {activeTab === 'lost-traffic' ? null : showPeriodSelector ? (<PeriodSelectoractivePeriod={activePeriod}setActivePeriod={setActivePeriod}isLoading={isLoading === null || isLoading}/>- )}+ ) : null}<Linkto={routes.new_project}onClick={onNewProject}@@ -269,12 +274,14 @@ const Dashboard = () => {</div></div>)}- <Tabs- activeTab={activeTab}- setActiveTab={setActiveTab}- isLoading={isLoading === null || isLoading}- className='mb-4 mt-2'- />+ {showTabs && (+ <Tabs+ activeTab={activeTab}+ setActiveTab={setActiveTab}+ isLoading={isLoading === null || isLoading}+ className='mb-4'+ />+ )}{isLoading || isLoading === null ? (<div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'><ProjectCardSkeleton />diff --git a/web/app/routes/feature-flags.tsx b/web/app/routes/feature-flags.tsxnew file mode 100644index 000000000..3449a1d7f--- /dev/null+++ b/web/app/routes/feature-flags.tsx@@ -0,0 +1,103 @@+import { useEffect, useState } from 'react'+import { useSelector } from 'react-redux'+import { useTranslation } from 'react-i18next'+import { Switch } from '@headlessui/react'+import { toast } from 'sonner'+import cx from 'clsx'++import { StateType } from '~/lib/store'+import { FeatureFlag } from '~/lib/models/User'+import { withAuthentication, auth } from '~/hoc/protected'+import { setFeatureFlags } from '~/api'+import { useNavigate } from '@remix-run/react'+import routes from '~/utils/routes'+import Loader from '~/ui/Loader'++const FeatureFlagsPage = () => {+ const { t } = useTranslation('common')+ const { user, loading } = useSelector((state: StateType) => state.auth)+ const [flags, setFlags] = useState<FeatureFlag[]>([])+ const navigate = useNavigate()++ useEffect(() => {+ if (loading) {+ return+ }++ if (user) {+ setFlags(user.featureFlags)+ return+ }++ navigate(routes.main)+ }, [loading, user, navigate])++ const handleToggle = async (flag: FeatureFlag) => {+ try {+ const newFlags = flags.includes(flag) ? flags.filter((f) => f !== flag) : [...flags, flag]++ await setFeatureFlags(newFlags)+ setFlags(newFlags)+ toast.success(t('featureFlags.updated'))+ } catch (error) {+ console.error('Failed to update feature flags:', error)+ toast.error(t('featureFlags.error'))+ }+ }++ if (loading) {+ return (+ <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>+ <Loader />+ </div>+ )+ }++ return (+ <div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>+ <div className='mx-auto max-w-7xl px-4 py-12 sm:px-6 lg:px-8'>+ <div className='mx-auto max-w-4xl'>+ <h2 className='text-3xl font-bold tracking-tight text-gray-900 dark:text-gray-50'>+ {t('featureFlags.title')}+ </h2>+ <p className='mt-4 text-gray-500 dark:text-gray-400'>{t('featureFlags.description')}</p>++ <div className='mt-8 divide-y divide-gray-200 dark:divide-gray-700'>+ {Object.values(FeatureFlag).map((flag) => (+ <div key={flag} className='flex items-center justify-between py-4'>+ <div>+ <h3 className='text-lg font-medium leading-6 text-gray-900 dark:text-gray-50'>+ {t(`featureFlags.${flag}.title`)}+ </h3>+ <p className='mt-1 text-sm text-gray-500 dark:text-gray-400'>+ {t(`featureFlags.${flag}.description`, {+ defaultPeriod: 7,+ })}+ </p>+ </div>+ <Switch+ checked={flags.includes(flag)}+ onChange={() => handleToggle(flag)}+ className={cx(+ flags.includes(flag) ? 'bg-indigo-600' : 'bg-gray-200 dark:bg-gray-700',+ 'relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2',+ )}+ >+ <span+ aria-hidden='true'+ className={cx(+ flags.includes(flag) ? 'translate-x-5' : 'translate-x-0',+ 'pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out',+ )}+ />+ </Switch>+ </div>+ ))}+ </div>+ </div>+ </div>+ </div>+ )+}++export default withAuthentication(FeatureFlagsPage, auth.authenticated)diff --git a/web/app/utils/routes.ts b/web/app/utils/routes.tsindex da8784a7b..025270bf3 100644--- a/web/app/utils/routes.ts+++ b/web/app/utils/routes.ts@@ -44,6 +44,7 @@ const routes = Object.freeze({forSmallBusinesses: '/for-small-businesses',organisations: '/organisations',organisation: '/organisations/:id',+ feature_flags: '/feature-flags',})export default routesdiff --git a/web/app/utils/server.ts b/web/app/utils/server.tsindex c074d221f..93a273e65 100644--- a/web/app/utils/server.ts+++ b/web/app/utils/server.ts@@ -253,6 +253,12 @@ export const getPageMeta = (t: typeof i18next.t, url?: string, _pathname?: strin}break+ case routes.feature_flags:+ result = {+ title: t('titles.featureFlags'),+ }+ break+default:break}diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex 2f361225f..f5912813b 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -128,6 +128,20 @@"pagination": "Showing <0>{{start}}</0> to <0>{{end}}</0> of <0>{{total}}</0> results","resultsPerPage": "Results per page"},+ "featureFlags": {+ "title": "Feature Flags",+ "description": "Enable or disable experimental features to try out new functionality before it's fully released. Feature flags allow you to test new features and provide feedback.",+ "updated": "Feature flags updated successfully",+ "error": "Failed to update feature flags",+ "dashboard-period-selector": {+ "title": "Dashboard Period Selector",+ "description": "Enables the period selector in the dashboard, allowing you to see the number of pageviews for different periods (if this feature flag is disabled, the default period is {{defaultPeriod}} days)."+ },+ "dashboard-analytics-tabs": {+ "title": "Dashboard Analytics Tabs",+ "description": "Enables analytics tabs in the dashboard, providing different views of your data such as high / low traffic sites, abandoned projects, and more."+ }+ },"performance": {"slogan": "End user <span>performance monitoring</span> to deliver fast websites.","description": "Deliver a flawless experience to your users, and we will let you know if your site is fast enough.",@@ -824,7 +838,7 @@},"notFoundPage": {"title": "Page not found",- "description": "Sorry, we couldn’t find the page you’re looking for.\nPlease check the URL in the address bar and try again.",+ "description": "Sorry, we couldn't find the page you're looking for.\nPlease check the URL in the address bar and try again.","goHome": "Go back home","support": "Contact support"},@@ -1298,7 +1312,8 @@"errors": "End user error tracking tool to deliver bug-free experiences","forMarketers": "For marketers","forSmbs": "For small businesses",- "forStartups": "For startups"+ "forStartups": "For startups",+ "featureFlags": "Feature flags"},"header": {"switchTheme": "Switch theme",