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!

'Install with AI' option

Blue Mousea6c25267a213
diff --git a/web/app/pages/Onboarding/Onboarding.tsx b/web/app/pages/Onboarding/Onboarding.tsx
index f1875d64f..a55e1f371 100644
--- a/web/app/pages/Onboarding/Onboarding.tsx
+++ b/web/app/pages/Onboarding/Onboarding.tsx
@@ -425,7 +425,7 @@ const SetupTrackingStep = ({ project }: { project: Project }) => {
</Text>
</div>
- <TrackingSetup projectId={project.id} />
+ <TrackingSetup projectId={project.id} showAiInstallPrompt />
</div>
)
}
diff --git a/web/app/ui/CodeBlock.tsx b/web/app/ui/CodeBlock.tsx
index a56c292a8..caa568ba3 100644
--- a/web/app/ui/CodeBlock.tsx
+++ b/web/app/ui/CodeBlock.tsx
@@ -1,7 +1,6 @@
-import { CheckIcon, CopyIcon } from '@phosphor-icons/react'
-import { useMemo, useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { toast } from 'sonner'
+import { useMemo } from 'react'
+
+import CopyButton from '~/ui/CopyButton'
const highlightHTML = (code: string): React.ReactNode[] => {
const parts: React.ReactNode[] = []
@@ -82,20 +81,6 @@ interface CodeBlockProps {
}
const CodeBlock = ({ code, onCopy }: CodeBlockProps) => {
- const { t } = useTranslation('common')
- const [copied, setCopied] = useState(false)
-
- const handleCopy = async () => {
- try {
- await navigator.clipboard.writeText(code)
- setCopied(true)
- onCopy?.()
- setTimeout(() => setCopied(false), 2000)
- } catch {
- toast.error(t('common.failedToCopy'))
- }
- }
-
const highlighted = useMemo(() => highlightHTML(code), [code])
return (
@@ -103,28 +88,11 @@ const CodeBlock = ({ code, onCopy }: CodeBlockProps) => {
<pre className='overflow-x-auto rounded-lg bg-white p-4 pr-12 font-mono text-xs leading-relaxed text-gray-800 ring-1 ring-gray-200 dark:bg-slate-950 dark:text-gray-200 dark:ring-slate-800'>
<code>{highlighted}</code>
</pre>
- <button
- type='button'
- onClick={handleCopy}
- aria-label={copied ? t('common.copied') : t('common.copy')}
- className='absolute top-2.5 right-2.5 inline-flex items-center gap-1.5 rounded-md bg-white/90 px-2 py-1.5 text-xs font-medium text-gray-700 ring-1 ring-gray-200 backdrop-blur-sm transition-[background-color,color,box-shadow] duration-150 ease-out hover:bg-gray-100 hover:text-gray-900 focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-slate-900 focus-visible:outline-hidden dark:bg-slate-900/80 dark:text-gray-200 dark:ring-slate-700 dark:hover:bg-slate-800 dark:hover:text-white dark:focus-visible:ring-slate-300'
- >
- {copied ? (
- <>
- <CheckIcon
- className='size-3.5 text-emerald-600 dark:text-emerald-400'
- weight='bold'
- aria-hidden='true'
- />
- <span>{t('common.copied')}</span>
- </>
- ) : (
- <>
- <CopyIcon className='size-3.5' aria-hidden='true' />
- <span>{t('common.copy')}</span>
- </>
- )}
- </button>
+ <CopyButton
+ value={code}
+ onCopy={onCopy}
+ className='absolute top-2.5 right-2.5'
+ />
</div>
)
}
diff --git a/web/app/ui/CopyButton.tsx b/web/app/ui/CopyButton.tsx
new file mode 100644
index 000000000..52550de82
--- /dev/null
+++ b/web/app/ui/CopyButton.tsx
@@ -0,0 +1,58 @@
+import { CheckIcon, CopyIcon } from '@phosphor-icons/react'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+
+import { cn } from '~/utils/generic'
+
+interface CopyButtonProps {
+ value: string
+ onCopy?: () => void
+ className?: string
+}
+
+const CopyButton = ({ value, onCopy, className }: CopyButtonProps) => {
+ const { t } = useTranslation('common')
+ const [copied, setCopied] = useState(false)
+
+ const handleCopy = async () => {
+ try {
+ await navigator.clipboard.writeText(value)
+ setCopied(true)
+ onCopy?.()
+ setTimeout(() => setCopied(false), 2000)
+ } catch {
+ toast.error(t('common.failedToCopy'))
+ }
+ }
+
+ return (
+ <button
+ type='button'
+ onClick={handleCopy}
+ aria-label={copied ? t('common.copied') : t('common.copy')}
+ className={cn(
+ 'inline-flex items-center gap-1.5 rounded-md bg-white/90 px-2 py-1.5 text-xs font-medium text-gray-700 ring-1 ring-gray-200 backdrop-blur-sm transition-[background-color,color,box-shadow] duration-150 ease-out hover:bg-gray-100 hover:text-gray-900 focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-slate-900 focus-visible:outline-hidden dark:bg-slate-900/80 dark:text-gray-200 dark:ring-slate-700 dark:hover:bg-slate-800 dark:hover:text-white dark:focus-visible:ring-slate-300',
+ className,
+ )}
+ >
+ {copied ? (
+ <>
+ <CheckIcon
+ className='size-3.5 text-emerald-600 dark:text-emerald-400'
+ weight='bold'
+ aria-hidden='true'
+ />
+ <span>{t('common.copied')}</span>
+ </>
+ ) : (
+ <>
+ <CopyIcon className='size-3.5' aria-hidden='true' />
+ <span>{t('common.copy')}</span>
+ </>
+ )}
+ </button>
+ )
+}
+
+export default CopyButton
diff --git a/web/app/ui/TrackingSetup.tsx b/web/app/ui/TrackingSetup.tsx
index d4ac05bea..24c93dbd2 100644
--- a/web/app/ui/TrackingSetup.tsx
+++ b/web/app/ui/TrackingSetup.tsx
@@ -6,6 +6,7 @@ import {
ArrowSquareOutIcon,
CopyIcon,
CheckIcon,
+ SparkleIcon,
} from '@phosphor-icons/react'
import type { CSSProperties } from 'react'
import { useState } from 'react'
@@ -66,6 +67,7 @@ import {
} from '~/lib/constants'
import { Badge } from '~/ui/Badge'
import CodeBlock from '~/ui/CodeBlock'
+import CopyButton from '~/ui/CopyButton'
import { Text } from '~/ui/Text'
import { cn } from '~/utils/generic'
@@ -111,7 +113,7 @@ document.addEventListener('DOMContentLoaded', function() {
</noscript>`
}
-type TrackingTab = 'script' | 'npm' | 'gtm' | 'platforms'
+type TrackingTab = 'script' | 'npm' | 'gtm' | 'ai' | 'platforms'
const TRACKING_TABS: {
id: TrackingTab
@@ -133,6 +135,11 @@ const TRACKING_TABS: {
labelKey: 'onboarding.installTracking.tabs.tagManager',
icon: TagIcon,
},
+ {
+ id: 'ai',
+ labelKey: 'onboarding.installTracking.tabs.ai',
+ icon: SparkleIcon,
+ },
{
id: 'platforms',
labelKey: 'onboarding.installTracking.tabs.platforms',
@@ -412,6 +419,91 @@ const getGtmSnippet = (pid: string) =>
})();
</script>`
+const getCspInstruction = () => {
+ if (isSelfhosted) {
+ return `If a Content Security Policy exists, preserve the current policy and add https://swetrix.org to script-src when using the script tag. Add the Swetrix API origin used by apiURL (${API_URL_WITHOUT_TRAILING_SLASH}) to connect-src, and to img-src if you keep the noscript pixel.`
+ }
+
+ return 'If a Content Security Policy exists, preserve the current policy and add https://swetrix.org to script-src when using the script tag. Add https://api.swetrix.com to connect-src, and to img-src if you keep the noscript pixel.'
+}
+
+const getAiInstallPrompt = (
+ pid: string,
+) => `Install Swetrix analytics in this codebase.
+
+Use these exact Swetrix values:
+- Project ID: "${pid}"
+- Browser script URL: "https://swetrix.org/swetrix.js"
+
+Goal:
+- Track page views on every public page.
+- Install Swetrix in the shared/root location so tracking runs once across the whole site.
+- Keep the Project ID exactly as provided.
+- Do not add another analytics provider.
+- Do not send personal data to Swetrix in custom event names or metadata.
+
+First inspect the codebase and choose the least invasive setup for the framework.
+If Swetrix is already installed, update the existing setup instead of adding a duplicate.
+
+For plain HTML or server-rendered templates, place this inside the shared <body> template, footer, or base layout so it appears on every page:
+
+\`\`\`html
+${getSnippet(pid)}
+\`\`\`
+
+For JavaScript frameworks, prefer the official npm package:
+
+\`\`\`bash
+npm install swetrix
+\`\`\`
+
+Then initialize Swetrix once in the browser-only root entry, app shell, or layout:
+
+\`\`\`ts
+${getNpmSnippet(pid)}
+\`\`\`
+
+Framework placement guide:
+- Next.js App Router: create a client Analytics component, call Swetrix from useEffect, and render it from app/layout.tsx. Add the noscript pixel in the root layout body if possible.
+- Next.js Pages Router: initialize in pages/_app.tsx and put the noscript pixel in pages/_document.tsx.
+- React with Vite or CRA: initialize in src/main.tsx or src/index.tsx. Add the noscript pixel to index.html.
+- Remix: create app/components/Analytics.tsx and render it from app/root.tsx inside <body>.
+- Vue, Nuxt, SvelteKit, Astro, Gatsby, Qwik, and Solid: initialize once from the client-side root layout, plugin, or entry component.
+- WordPress, Shopify, Webflow, Wix, Squarespace, Ghost, and similar builders: use the global custom code, theme header, footer, or integration area so the snippet appears on every page.
+
+Implementation requirements:
+- Call init before trackViews.
+- Call trackViews once from the root/shared location. It automatically tracks supported client-side route changes.
+- Use the matching namespace: swetrix.* for script-tag installs, Swetrix.* for npm imports.
+- Keep the noscript image pixel where the framework or platform supports it.
+- If enabling automatic browser error monitoring, call trackErrors after trackViews.
+- For custom events, use track({ ev: "EVENT_NAME", meta: { key: "value" } }) with short event names and non-PII metadata only. Never include email, full name, phone number, payment data, auth tokens, or raw user IDs.
+- If an event location is ambiguous, do not invent tracking. Summarize the suggested event locations instead.
+- Do not enable devMode in production code. Swetrix ignores localhost by default.
+- ${getCspInstruction()}
+
+Useful references:
+- Install guide: https://swetrix.com/docs/install-script
+- Framework guides: https://swetrix.com/docs/integrations
+- Script API reference: https://swetrix.com/docs/swetrix-js-reference
+
+After installing:
+- Search the source for "swetrix" and this Project ID.
+- Visit a deployed page, or temporarily enable devMode only for local verification, and confirm pageviews appear in the Swetrix dashboard within about a minute.
+- Return a short summary of changed files and where Swetrix initializes.`
+
+const PROMPT_PREVIEW_LINES = 12
+
+const getPromptPreview = (prompt: string) => {
+ const lines = prompt.split('\n')
+
+ if (lines.length <= PROMPT_PREVIEW_LINES) {
+ return prompt
+ }
+
+ return lines.slice(0, PROMPT_PREVIEW_LINES).join('\n')
+}
+
const CopyableField = ({ value }: { value: string }) => {
const { t } = useTranslation('common')
const [copied, setCopied] = useState(false)
@@ -452,18 +544,60 @@ const CopyableField = ({ value }: { value: string }) => {
)
}
+const AiInstallTab = ({ projectId }: { projectId: string }) => {
+ const { t } = useTranslation('common')
+ const prompt = getAiInstallPrompt(projectId)
+ const preview = getPromptPreview(prompt)
+ const isTruncated = preview !== prompt
+
+ return (
+ <div>
+ <div className='mb-4 flex items-center gap-3'>
+ <div className='flex size-10 shrink-0 items-center justify-center rounded-lg border border-gray-200 dark:border-slate-700'>
+ <SparkleIcon className='size-5 text-gray-700 dark:text-gray-200' />
+ </div>
+ <div>
+ <Text as='h3' size='sm' weight='semibold'>
+ {t('onboarding.installTracking.ai.title')}
+ </Text>
+ <Text as='p' size='xs' colour='secondary'>
+ {t('onboarding.installTracking.ai.desc')}
+ </Text>
+ </div>
+ </div>
+
+ <div className='relative'>
+ <pre className='overflow-hidden rounded-lg bg-white p-4 pr-12 font-mono text-xs leading-relaxed whitespace-pre-wrap text-gray-800 ring-1 ring-gray-200 dark:bg-slate-950 dark:text-gray-200 dark:ring-slate-800'>
+ {preview}
+ </pre>
+ {isTruncated ? (
+ <div className='pointer-events-none absolute inset-x-px bottom-px h-24 rounded-b-lg bg-linear-to-t from-white via-white/90 to-transparent dark:from-slate-950 dark:via-slate-950/90' />
+ ) : null}
+ <CopyButton value={prompt} className='absolute top-2.5 right-2.5' />
+ </div>
+ </div>
+ )
+}
+
interface TrackingSetupProps {
projectId: string
+ showAiInstallPrompt?: boolean
}
-const TrackingSetup = ({ projectId }: TrackingSetupProps) => {
+const TrackingSetup = ({
+ projectId,
+ showAiInstallPrompt,
+}: TrackingSetupProps) => {
const { t } = useTranslation('common')
const [activeTab, setActiveTab] = useState<TrackingTab>('script')
+ const tabs = showAiInstallPrompt
+ ? TRACKING_TABS
+ : TRACKING_TABS.filter((tab) => tab.id !== 'ai')
return (
<div>
<div className='mb-4 flex gap-1 rounded-lg bg-gray-100 p-1 dark:bg-slate-900'>
- {TRACKING_TABS.map((tab) => {
+ {tabs.map((tab) => {
const Icon = tab.icon
const isActive = activeTab === tab.id
return (
@@ -626,6 +760,8 @@ const TrackingSetup = ({ projectId }: TrackingSetupProps) => {
</div>
)}
+ {activeTab === 'ai' && <AiInstallTab projectId={projectId} />}
+
{activeTab === 'platforms' && (
<div>
<div className='mb-4 flex items-center gap-3'>
diff --git a/web/public/locales/de.json b/web/public/locales/de.json
index 94f7e1a70..2c25c9ae5 100644
--- a/web/public/locales/de.json
+++ b/web/public/locales/de.json
@@ -3412,10 +3412,15 @@
"weAlsoSupport": "Du kannst Swetrix auch mit NPM für Frameworks wie React und Vue installieren, Events über die Events API senden oder Integrationen wie WordPress und Google Tag Manager nutzen. <url>Mehr erfahren</url>.",
"optional": "Dieser Schritt ist optional. Du kannst das Tracking später in den Projekteinstellungen einrichten.",
"skipForNow": "Vorerst überspringen",
+ "ai": {
+ "title": "Mit KI installieren",
+ "desc": "Kopiere diesen Prompt in deinen KI-Code-Editor (Claude Code, Cursor, etc.), um Swetrix automatisch zu installieren."
+ },
"tabs": {
"script": "Skript",
"npm": "NPM",
"tagManager": "Tag Manager",
+ "ai": "KI",
"platforms": "Plattformen"
},
"npm": {
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 9b4d9069e..c0f627a98 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -3412,10 +3412,15 @@
"weAlsoSupport": "You can also install Swetrix with NPM for frameworks like React and Vue, send events through the Events API, or use integrations such as WordPress and Google Tag Manager. <url>Learn more</url>.",
"optional": "This step is optional. You can set up tracking later from project settings.",
"skipForNow": "Skip for now",
+ "ai": {
+ "title": "Install with AI",
+ "desc": "Copy this prompt into your AI code editor (Claude Code, Cursor, etc.) to install Swetrix automatically."
+ },
"tabs": {
"script": "Script",
"npm": "NPM",
"tagManager": "Tag Manager",
+ "ai": "AI",
"platforms": "Platforms"
},
"npm": {
diff --git a/web/public/locales/fr.json b/web/public/locales/fr.json
index 9156de9d4..8d4fce41f 100644
--- a/web/public/locales/fr.json
+++ b/web/public/locales/fr.json
@@ -3412,10 +3412,15 @@
"weAlsoSupport": "Vous pouvez également installer Swetrix avec NPM pour des frameworks comme React et Vue, envoyer des événements via l'API Événements, ou utiliser des intégrations telles que WordPress et Google Tag Manager. <url>En savoir plus</url>.",
"optional": "Cette étape est facultative. Vous pourrez configurer le suivi plus tard depuis les paramètres du projet.",
"skipForNow": "Ignorer pour le moment",
+ "ai": {
+ "title": "Installer avec l'IA",
+ "desc": "Copiez ce prompt dans votre éditeur de code IA (Claude Code, Cursor, etc.) pour installer Swetrix automatiquement."
+ },
"tabs": {
"script": "Script",
"npm": "NPM",
"tagManager": "Tag Manager",
+ "ai": "IA",
"platforms": "Plateformes"
},
"npm": {
diff --git a/web/public/locales/pl.json b/web/public/locales/pl.json
index e5aaa55cb..f87d06e64 100644
--- a/web/public/locales/pl.json
+++ b/web/public/locales/pl.json
@@ -3412,10 +3412,15 @@
"weAlsoSupport": "Możesz również zainstalować Swetrix za pomocą NPM dla frameworków takich jak React i Vue, wysyłać zdarzenia przez Events API lub skorzystać z integracji, takich jak WordPress i Google Tag Manager. <url>Dowiedz się więcej</url>.",
"optional": "Ten krok jest opcjonalny. Możesz skonfigurować śledzenie później w ustawieniach projektu.",
"skipForNow": "Pomiń na razie",
+ "ai": {
+ "title": "Zainstaluj z AI",
+ "desc": "Skopiuj ten prompt do swojego edytora kodu z AI (Claude Code, Cursor itp.), aby automatycznie zainstalować Swetrix."
+ },
"tabs": {
"script": "Skrypt",
"npm": "NPM",
"tagManager": "Tag Manager",
+ "ai": "AI",
"platforms": "Platformy"
},
"npm": {
diff --git a/web/public/locales/uk.json b/web/public/locales/uk.json
index 2ee07b7d6..cc62e6743 100644
--- a/web/public/locales/uk.json
+++ b/web/public/locales/uk.json
@@ -3412,10 +3412,15 @@
"weAlsoSupport": "Ви також можете встановити Swetrix через NPM для фреймворків, таких як React і Vue, надсилати події через Events API або використовувати інтеграції, такі як WordPress і Google Tag Manager. <url>Дізнатися більше</url>.",
"optional": "Цей крок необов'язковий. Ви можете налаштувати відстеження пізніше в налаштуваннях проєкту.",
"skipForNow": "Пропустити поки",
+ "ai": {
+ "title": "Встановити за допомогою ШІ",
+ "desc": "Скопіюйте цей промпт у ваш ШІ-редактор коду (Claude Code, Cursor тощо), щоб автоматично встановити Swetrix."
+ },
"tabs": {
"script": "Скрипт",
"npm": "NPM",
"tagManager": "Менеджер тегів",
+ "ai": "ШІ",
"platforms": "Платформи"
},
"npm": {