📈 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
Set up formatter
Blue Mouseaf8b995ccf9b
diff --git a/docs/app/[[...slug]]/page.tsx b/docs/app/[[...slug]]/page.tsxindex 2deaf5146..cc2bbe334 100644--- a/docs/app/[[...slug]]/page.tsx+++ b/docs/app/[[...slug]]/page.tsx@@ -1,19 +1,12 @@-import { source } from '@/lib/source';-import {- DocsPage,- DocsBody,- DocsTitle,- DocsDescription,-} from 'fumadocs-ui/page';-import defaultMdxComponents from 'fumadocs-ui/mdx';-import { notFound } from 'next/navigation';-import { FeedbackWidget } from '@/components/FeedbackWidget';-import { IntegrationsGrid } from '@/components/IntegrationsGrid';-import { getMDXComponents } from '@/mdx-components';+import { source } from "@/lib/source";+import { DocsPage, DocsBody, DocsTitle, DocsDescription } from "fumadocs-ui/page";+import defaultMdxComponents from "fumadocs-ui/mdx";+import { notFound } from "next/navigation";+import { FeedbackWidget } from "@/components/FeedbackWidget";+import { IntegrationsGrid } from "@/components/IntegrationsGrid";+import { getMDXComponents } from "@/mdx-components";-export default async function Page(props: {- params: Promise<{ slug?: string[] }>;-}) {+export default async function Page(props: { params: Promise<{ slug?: string[] }> }) {const params = await props.params;const page = source.getPage(params.slug);if (!page) notFound();@@ -24,9 +17,9 @@ export default async function Page(props: {<DocsPagetoc={page.data.toc}editOnGithub={{- repo: 'swetrix',- owner: 'Swetrix',- sha: 'main',+ repo: "swetrix",+ owner: "Swetrix",+ sha: "main",path: `docs/content/docs/${page.url}`,}}>@@ -44,9 +37,7 @@ export function generateStaticParams() {return source.generateParams();}-export async function generateMetadata(props: {- params: Promise<{ slug?: string[] }>;-}) {+export async function generateMetadata(props: { params: Promise<{ slug?: string[] }> }) {const params = await props.params;const page = source.getPage(params.slug);if (!page) notFound();diff --git a/docs/app/components/Footer.tsx b/docs/app/components/Footer.tsxindex d1f344c82..a1356adcf 100644--- a/docs/app/components/Footer.tsx+++ b/docs/app/components/Footer.tsx@@ -1,4 +1,4 @@-'use client'+"use client";import {GithubLogoIcon,@@ -22,234 +22,233 @@ import {WarningIcon,ArrowsHorizontalIcon,type IconProps,-} from '@phosphor-icons/react'-import type { FC, ReactNode } from 'react'+} from "@phosphor-icons/react";+import type { FC, ReactNode } from "react";-const SITE = 'https://swetrix.com'-const GITHUB_URL = 'https://github.com/Swetrix/swetrix'-const LINKEDIN_URL = 'https://www.linkedin.com/company/swetrix/'-const TWITTER_URL =- 'https://twitter.com/intent/user?screen_name=swetrix'-const DISCORD_URL = 'https://discord.gg/ZVK8Tw2E8j'-const STATUSPAGE_URL = 'https://stats.uptimerobot.com/33rvmiXXEz'-const DOCS_URL = 'https://swetrix.com/docs'+const SITE = "https://swetrix.com";+const GITHUB_URL = "https://github.com/Swetrix/swetrix";+const LINKEDIN_URL = "https://www.linkedin.com/company/swetrix/";+const TWITTER_URL = "https://twitter.com/intent/user?screen_name=swetrix";+const DISCORD_URL = "https://discord.gg/ZVK8Tw2E8j";+const STATUSPAGE_URL = "https://stats.uptimerobot.com/33rvmiXXEz";+const DOCS_URL = "https://swetrix.com/docs";interface NavItem {- name: string- href: string- icon: FC<IconProps>- iconColor: string+ name: string;+ href: string;+ icon: FC<IconProps>;+ iconColor: string;}interface LegalItem {- name: string- href: string+ name: string;+ href: string;}const products: NavItem[] = [{- name: 'Web Analytics',+ name: "Web Analytics",href: SITE,icon: ChartBarIcon,- iconColor: 'text-indigo-400',+ iconColor: "text-indigo-400",},{- name: 'Performance monitoring',+ name: "Performance monitoring",href: `${SITE}/performance`,icon: GaugeIcon,- iconColor: 'text-amber-400',+ iconColor: "text-amber-400",},{- name: 'Error tracking',+ name: "Error tracking",href: `${SITE}/error-tracking`,icon: WarningIcon,- iconColor: 'text-rose-400',+ iconColor: "text-rose-400",},{- name: 'CAPTCHA',+ name: "CAPTCHA",href: `${SITE}/captcha`,icon: ShieldCheckIcon,- iconColor: 'text-emerald-400',+ iconColor: "text-emerald-400",},-]+];const freeTools: NavItem[] = [{- name: 'UTM Generator',+ name: "UTM Generator",href: `${SITE}/tools/utm-generator`,icon: LinkIcon,- iconColor: 'text-violet-400',+ iconColor: "text-violet-400",},{- name: 'CTR Calculator',+ name: "CTR Calculator",href: `${SITE}/tools/ctr-calculator`,icon: CursorClickIcon,- iconColor: 'text-pink-400',+ iconColor: "text-pink-400",},{- name: 'ROI Calculator',+ name: "ROI Calculator",href: `${SITE}/tools/roi-calculator`,icon: ChartPieIcon,- iconColor: 'text-teal-400',+ iconColor: "text-teal-400",},{- name: 'IP Lookup',+ name: "IP Lookup",href: `${SITE}/tools/ip-lookup`,icon: GlobeIcon,- iconColor: 'text-blue-400',+ iconColor: "text-blue-400",},{- name: 'Sitemap Validator',+ name: "Sitemap Validator",href: `${SITE}/tools/sitemap-validator`,icon: TreeStructureIcon,- iconColor: 'text-lime-400',+ iconColor: "text-lime-400",},-]+];const resources: NavItem[] = [{- name: 'Documentation',+ name: "Documentation",href: DOCS_URL,icon: BookOpenIcon,- iconColor: 'text-sky-400',+ iconColor: "text-sky-400",},{- name: 'Pricing',+ name: "Pricing",href: `${SITE}/#pricing`,icon: CurrencyDollarIcon,- iconColor: 'text-emerald-400',+ iconColor: "text-emerald-400",},-]+];const comparisons: NavItem[] = [{- name: 'Google Analytics',+ name: "Google Analytics",href: `${SITE}/comparison/google-analytics`,icon: ArrowsHorizontalIcon,- iconColor: 'text-amber-400',+ iconColor: "text-amber-400",},{- name: 'Plausible',+ name: "Plausible",href: `${SITE}/comparison/plausible`,icon: ArrowsHorizontalIcon,- iconColor: 'text-violet-400',+ iconColor: "text-violet-400",},{- name: 'Cloudflare Analytics',+ name: "Cloudflare Analytics",href: `${SITE}/comparison/cloudflare-analytics`,icon: ArrowsHorizontalIcon,- iconColor: 'text-orange-400',+ iconColor: "text-orange-400",},{- name: 'Fathom Analytics',+ name: "Fathom Analytics",href: `${SITE}/comparison/fathom-analytics`,icon: ArrowsHorizontalIcon,- iconColor: 'text-purple-400',+ iconColor: "text-purple-400",},{- name: 'Simple Analytics',+ name: "Simple Analytics",href: `${SITE}/comparison/simple-analytics`,icon: ArrowsHorizontalIcon,- iconColor: 'text-red-400',+ iconColor: "text-red-400",},{- name: 'Vercel Web Analytics',+ name: "Vercel Web Analytics",href: `${SITE}/comparison/vercel-web-analytics`,icon: ArrowsHorizontalIcon,- iconColor: 'text-slate-400',+ iconColor: "text-slate-400",},{- name: 'Rybbit',+ name: "Rybbit",href: `${SITE}/comparison/rybbit`,icon: ArrowsHorizontalIcon,- iconColor: 'text-emerald-400',+ iconColor: "text-emerald-400",},{- name: 'Umami',+ name: "Umami",href: `${SITE}/comparison/umami`,icon: ArrowsHorizontalIcon,- iconColor: 'text-blue-400',+ iconColor: "text-blue-400",},{- name: 'Pirsch',+ name: "Pirsch",href: `${SITE}/comparison/pirsch`,icon: ArrowsHorizontalIcon,- iconColor: 'text-emerald-400',+ iconColor: "text-emerald-400",},{- name: 'Matomo',+ name: "Matomo",href: `${SITE}/comparison/matomo`,icon: ArrowsHorizontalIcon,- iconColor: 'text-lime-400',+ iconColor: "text-lime-400",},{- name: 'PostHog',+ name: "PostHog",href: `${SITE}/comparison/posthog`,icon: ArrowsHorizontalIcon,- iconColor: 'text-blue-400',+ iconColor: "text-blue-400",},-]+];const company: NavItem[] = [{- name: 'Open startup',+ name: "Open startup",href: `${SITE}/open`,icon: LockKeyIcon,- iconColor: 'text-teal-400',+ iconColor: "text-teal-400",},{- name: 'Blog',+ name: "Blog",href: `${SITE}/blog`,icon: ArticleIcon,- iconColor: 'text-fuchsia-400',+ iconColor: "text-fuchsia-400",},{- name: 'Contact',+ name: "Contact",href: `${SITE}/contact`,icon: EnvelopeIcon,- iconColor: 'text-blue-400',+ iconColor: "text-blue-400",},{- name: 'Status',+ name: "Status",href: STATUSPAGE_URL,icon: PulseIcon,- iconColor: 'text-emerald-400',+ iconColor: "text-emerald-400",},-]+];const communityLinks: NavItem[] = [{- name: 'GitHub',+ name: "GitHub",href: GITHUB_URL,icon: GithubLogoIcon,- iconColor: 'text-gray-300',+ iconColor: "text-gray-300",},{- name: 'Discord',+ name: "Discord",href: DISCORD_URL,icon: DiscordLogoIcon,- iconColor: 'text-indigo-400',+ iconColor: "text-indigo-400",},{- name: 'Twitter / X',+ name: "Twitter / X",href: TWITTER_URL,icon: XLogoIcon,- iconColor: 'text-gray-300',+ iconColor: "text-gray-300",},{- name: 'LinkedIn',+ name: "LinkedIn",href: LINKEDIN_URL,icon: LinkedinLogoIcon,- iconColor: 'text-blue-400',+ iconColor: "text-blue-400",},-]+];const legal: LegalItem[] = [- { name: 'Privacy', href: `${SITE}/privacy` },- { name: 'Terms', href: `${SITE}/terms` },- { name: 'Cookie Policy', href: `${SITE}/cookie-policy` },- { name: 'Legal notice', href: `${SITE}/imprint` },-]+ { name: "Privacy", href: `${SITE}/privacy` },+ { name: "Terms", href: `${SITE}/terms` },+ { name: "Cookie Policy", href: `${SITE}/cookie-policy` },+ { name: "Legal notice", href: `${SITE}/imprint` },+];function FooterLink({href,@@ -257,10 +256,10 @@ function FooterLink({iconColor,children,}: {- href: string- icon?: FC<IconProps>- iconColor?: string- children: ReactNode+ href: string;+ icon?: FC<IconProps>;+ iconColor?: string;+ children: ReactNode;}) {return (<a@@ -271,49 +270,33 @@ function FooterLink({><span className="inline-flex items-center gap-2">{Icon && (- <Icon- weight="duotone"- className={`h-4 w-4 shrink-0 ${iconColor}`}- aria-hidden="true"- />+ <Icon weight="duotone" className={`h-4 w-4 shrink-0 ${iconColor}`} aria-hidden="true" />)}<span>{children}</span></span></a>- )+ );}-function NavColumn({- title,- items,-}: {- title: string- items: NavItem[]-}) {+function NavColumn({ title, items }: { title: string; items: NavItem[] }) {return (<div>- <h3 className="mb-4 text-sm font-semibold text-gray-200">- {title}- </h3>+ <h3 className="mb-4 text-sm font-semibold text-gray-200">{title}</h3><ul className="space-y-2.5">{items.map((item) => (<li key={item.name}>- <FooterLink- href={item.href}- icon={item.icon}- iconColor={item.iconColor}- >+ <FooterLink href={item.href} icon={item.icon} iconColor={item.iconColor}>{item.name}</FooterLink></li>))}</ul></div>- )+ );}export default function Footer() {- const year = new Date().getFullYear()+ const year = new Date().getFullYear();return (<footer@@ -364,9 +347,7 @@ export default function Footer() {alt=""loading="lazy"/>- <span className="text-2xl leading-5 font-bold text-white">- Swetrix- </span>+ <span className="text-2xl leading-5 font-bold text-white">Swetrix</span></a><p className="mt-4 max-w-72 text-sm text-gray-200">@@ -380,10 +361,7 @@ export default function Footer() {rel="noopener noreferrer"className="inline-flex items-center justify-center rounded-md border border-gray-300 bg-white px-3 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50">- <GithubLogoIcon- className="mr-1.5 h-4 w-4"- weight="duotone"- />+ <GithubLogoIcon className="mr-1.5 h-4 w-4" weight="duotone" /><span>Star us on GitHub</span></a></div>@@ -392,9 +370,7 @@ export default function Footer() {<div className="flex flex-col items-start border-t border-white/10 pt-6 lg:pt-8"><div className="flex w-full flex-col items-center gap-4 text-center text-sm md:flex-row md:justify-between md:text-left">- <div className="text-gray-200">- © {year} Swetrix Ltd. All rights reserved.- </div>+ <div className="text-gray-200">© {year} Swetrix Ltd. All rights reserved.</div><div className="flex flex-wrap items-center justify-center gap-x-6 gap-y-2">{legal.map(({ name, href }) => (@@ -414,5 +390,5 @@ export default function Footer() {</div></div></footer>- )+ );}diff --git a/docs/app/global.css b/docs/app/global.cssindex 763bb9067..9f05dc210 100644--- a/docs/app/global.css+++ b/docs/app/global.css@@ -1,6 +1,6 @@-@import 'tailwindcss';-@import 'fumadocs-ui/css/black.css';-@import 'fumadocs-ui/css/preset.css';+@import "tailwindcss";+@import "fumadocs-ui/css/black.css";+@import "fumadocs-ui/css/preset.css";@layer base {.shadow-sm,@@ -9,7 +9,12 @@.shadow-xl,.shadow-2xl {--tw-shadow: 0 0 #0000 !important;- box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), 0 0 #0000 !important;+ box-shadow:+ var(--tw-inset-shadow),+ var(--tw-inset-ring-shadow),+ var(--tw-ring-offset-shadow),+ var(--tw-ring-shadow),+ 0 0 #0000 !important;}}@@ -18,7 +23,7 @@position: relative;}.underline-animate::after {- content: '';+ content: "";position: absolute;left: 0;right: 0;diff --git a/docs/app/layout.tsx b/docs/app/layout.tsxindex 2dcbc34d7..604ed4f4e 100644--- a/docs/app/layout.tsx+++ b/docs/app/layout.tsx@@ -1,29 +1,26 @@-import { RootProvider } from 'fumadocs-ui/provider/next';-import { DocsLayout } from 'fumadocs-ui/layouts/docs';-import { GithubInfo } from 'fumadocs-ui/components/github-info';-import type { ReactNode } from 'react';-import { source } from '@/lib/source';-import Script from 'next/script';-import Footer from './components/Footer';-import './global.css';+import { RootProvider } from "fumadocs-ui/provider/next";+import { DocsLayout } from "fumadocs-ui/layouts/docs";+import { GithubInfo } from "fumadocs-ui/components/github-info";+import type { ReactNode } from "react";+import { source } from "@/lib/source";+import Script from "next/script";+import Footer from "./components/Footer";+import "./global.css";export const metadata = {title: {- template: '%s | Swetrix Docs',- default: 'Swetrix Docs',+ template: "%s | Swetrix Docs",+ default: "Swetrix Docs",},- description: 'Swetrix documentation — turn traffic into insights.',- icons: { icon: '/docs/img/favicon.ico' },+ description: "Swetrix documentation — turn traffic into insights.",+ icons: { icon: "/docs/img/favicon.ico" },};export default function RootLayout({ children }: { children: ReactNode }) {return (<html lang="en" suppressHydrationWarning><head>- <Script- src="https://swetrix.org/swetrix.js"- strategy="afterInteractive"- />+ <Script src="https://swetrix.org/swetrix.js" strategy="afterInteractive" /><Script id="swetrix-init" strategy="afterInteractive">{`document.addEventListener('DOMContentLoaded', function () {@@ -59,18 +56,12 @@ export default function RootLayout({ children }: { children: ReactNode }) {</span></div>),- url: 'https://swetrix.com',+ url: "https://swetrix.com",}}links={[{- type: 'custom',- children: (- <GithubInfo- owner="Swetrix"- repo="swetrix"- className="lg:-mx-2"- />- ),+ type: "custom",+ children: <GithubInfo owner="Swetrix" repo="swetrix" className="lg:-mx-2" />,},]}>diff --git a/docs/components/FeedbackWidget.tsx b/docs/components/FeedbackWidget.tsxindex 618a0f393..54b026c4e 100644--- a/docs/components/FeedbackWidget.tsx+++ b/docs/components/FeedbackWidget.tsx@@ -1,147 +1,158 @@-'use client';-import React, { useEffect, useMemo, useState } from 'react'-import { usePathname } from 'next/navigation'-import { ThumbsUpIcon, ThumbsDownIcon } from '@phosphor-icons/react'-import Link from 'next/link'+"use client";+import React, { useEffect, useMemo, useState } from "react";+import { usePathname } from "next/navigation";+import { ThumbsUpIcon, ThumbsDownIcon } from "@phosphor-icons/react";+import Link from "next/link";-const FEEDBACK_TTL_DAYS = 7-const FEEDBACK_TTL_MS = FEEDBACK_TTL_DAYS * 24 * 60 * 60 * 1000+const FEEDBACK_TTL_DAYS = 7;+const FEEDBACK_TTL_MS = FEEDBACK_TTL_DAYS * 24 * 60 * 60 * 1000;const NEGATIVE_REASONS = [- 'Content is out of date',- 'Missing information',- 'Code examples not working as expected',- 'Other',-]+ "Content is out of date",+ "Missing information",+ "Code examples not working as expected",+ "Other",+];const getNowMs = () => {- return Date.now()-}+ return Date.now();+};const storageKeyForPath = (pathname: string) => {- return `docs.feedback:${pathname}`-}+ return `docs.feedback:${pathname}`;+};const hasRecentFeedback = (pathname: string) => {- if (typeof window === 'undefined') return false+ if (typeof window === "undefined") return false;try {- const key = storageKeyForPath(pathname)- const raw = window.localStorage.getItem(key)+ const key = storageKeyForPath(pathname);+ const raw = window.localStorage.getItem(key);if (raw) {- const data = JSON.parse(raw)- if (- data &&- typeof data.ts === 'number' &&- getNowMs() - data.ts < FEEDBACK_TTL_MS- ) {- return true+ const data = JSON.parse(raw);+ if (data && typeof data.ts === "number" && getNowMs() - data.ts < FEEDBACK_TTL_MS) {+ return true;}}} catch (reason) {- console.error('Error checking recent feedback:', reason)+ console.error("Error checking recent feedback:", reason);}- return false-}+ return false;+};const persistFeedback = (pathname: string, answer: string, reason: string) => {- if (typeof window !== 'undefined') {+ if (typeof window !== "undefined") {try {- const key = storageKeyForPath(pathname)- const value = JSON.stringify({ answer, reason, ts: getNowMs() })- window.localStorage.setItem(key, value)+ const key = storageKeyForPath(pathname);+ const value = JSON.stringify({ answer, reason, ts: getNowMs() });+ window.localStorage.setItem(key, value);} catch (reason) {- console.error('Error persisting feedback:', reason)+ console.error("Error persisting feedback:", reason);}}-}+};const trackFeedback = async (answer: string, pathname: string, reason: string) => {try {await (window as any)?.swetrix?.track({- ev: 'DOCS_FEEDBACK',+ ev: "DOCS_FEEDBACK",meta: {answer,path: pathname,...(reason ? { reason } : {}),},- })+ });} catch (reason) {- console.error('Error tracking feedback:', reason)+ console.error("Error tracking feedback:", reason);}-}+};export function FeedbackWidget() {- const pathname = usePathname()- const [submitted, setSubmitted] = useState(false)- const [showReasonForm, setShowReasonForm] = useState(false)- const [reason, setReason] = useState('')- const suppressed = useMemo(() => hasRecentFeedback(pathname), [pathname])+ const pathname = usePathname();+ const [submitted, setSubmitted] = useState(false);+ const [showReasonForm, setShowReasonForm] = useState(false);+ const [reason, setReason] = useState("");+ const suppressed = useMemo(() => hasRecentFeedback(pathname), [pathname]);useEffect(() => {- setSubmitted(false)- setShowReasonForm(false)- setReason('')- }, [pathname])+ setSubmitted(false);+ setShowReasonForm(false);+ setReason("");+ }, [pathname]);const onClickYes = async () => {- await trackFeedback('Yes', pathname, '')- persistFeedback(pathname, 'Yes', '')- setSubmitted(true)- }+ await trackFeedback("Yes", pathname, "");+ persistFeedback(pathname, "Yes", "");+ setSubmitted(true);+ };const onClickNo = () => {- setShowReasonForm(true)- }+ setShowReasonForm(true);+ };const onSubmitReason = async (event: React.FormEvent<HTMLFormElement>) => {- event?.preventDefault?.()- if (!reason) return- await trackFeedback('No', pathname, reason)- persistFeedback(pathname, 'No', reason)- setSubmitted(true)- setShowReasonForm(false)- }+ event?.preventDefault?.();+ if (!reason) return;+ await trackFeedback("No", pathname, reason);+ persistFeedback(pathname, "No", reason);+ setSubmitted(true);+ setShowReasonForm(false);+ };return (- <section className='hidden sm:block mt-8 ring-1 ring-gray-300 dark:ring-slate-800/80 rounded-xl p-6 bg-transparent relative overflow-hidden' aria-label='Docs feedback widget'>- <div className='absolute right-0 -top-4 w-[140px] h-[140px] opacity-10 dark:opacity-5 pointer-events-none' aria-hidden='true'>- <img src='https://swetrix.com/logo512.png' alt='' className='w-full h-full object-contain -rotate-10' />+ <section+ className="hidden sm:block mt-8 ring-1 ring-gray-300 dark:ring-slate-800/80 rounded-xl p-6 bg-transparent relative overflow-hidden"+ aria-label="Docs feedback widget"+ >+ <div+ className="absolute right-0 -top-4 w-[140px] h-[140px] opacity-10 dark:opacity-5 pointer-events-none"+ aria-hidden="true"+ >+ <img+ src="https://swetrix.com/logo512.png"+ alt=""+ className="w-full h-full object-contain -rotate-10"+ /></div>- <h2 className='text-2xl font-bold mb-2 text-slate-900 dark:text-white mt-2'>Help us improve Swetrix</h2>+ <h2 className="text-2xl font-bold mb-2 text-slate-900 dark:text-white mt-2">+ Help us improve Swetrix+ </h2>{submitted || suppressed ? (- <p aria-live='polite' className='m-0 mb-12 text-lg text-slate-700 dark:text-slate-300'>+ <p aria-live="polite" className="m-0 mb-12 text-lg text-slate-700 dark:text-slate-300">Thank you for your feedback ❤️</p>) : (<>{showReasonForm ? (- <form className='mt-4' onSubmit={onSubmitReason}>- <p className='text-lg mb-4 text-slate-700 dark:text-slate-300'>+ <form className="mt-4" onSubmit={onSubmitReason}>+ <p className="text-lg mb-4 text-slate-700 dark:text-slate-300">Why was this page not helpful to you?</p><div- role='group'- aria-label='Choose a reason'- className='grid gap-3 mb-5 relative z-10'+ role="group"+ aria-label="Choose a reason"+ className="grid gap-3 mb-5 relative z-10">{NEGATIVE_REASONS.map((label) => (- <label key={label} className='flex items-center gap-3 cursor-pointer text-slate-700 dark:text-slate-300 hover:text-slate-900 dark:hover:text-white transition-colors'>+ <label+ key={label}+ className="flex items-center gap-3 cursor-pointer text-slate-700 dark:text-slate-300 hover:text-slate-900 dark:hover:text-white transition-colors"+ ><input- type='radio'- name='feedback-reason'+ type="radio"+ name="feedback-reason"value={label}checked={reason === label}onChange={() => setReason(label)}- className='w-4 h-4 text-slate-900 focus:ring-slate-900 dark:text-slate-100 dark:focus:ring-slate-300 bg-transparent border-gray-300 dark:border-slate-600'+ className="w-4 h-4 text-slate-900 focus:ring-slate-900 dark:text-slate-100 dark:focus:ring-slate-300 bg-transparent border-gray-300 dark:border-slate-600"/>- <span className='font-medium'>{label}</span>+ <span className="font-medium">{label}</span></label>))}</div><button- type='submit'- className='px-5 py-2.5 bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900 rounded-lg font-semibold disabled:opacity-50 disabled:cursor-not-allowed transition-colors hover:bg-slate-800 dark:hover:bg-slate-200 relative z-10'+ type="submit"+ className="px-5 py-2.5 bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900 rounded-lg font-semibold disabled:opacity-50 disabled:cursor-not-allowed transition-colors hover:bg-slate-800 dark:hover:bg-slate-200 relative z-10"disabled={!reason}aria-disabled={!reason}>@@ -150,26 +161,26 @@ export function FeedbackWidget() {</form>) : (<>- <p className='text-lg mb-4 text-slate-700 dark:text-slate-300'>+ <p className="text-lg mb-4 text-slate-700 dark:text-slate-300">Was this page helpful to you?</p>- <div role='group' className='flex gap-3 mb-6 relative z-10'>+ <div role="group" className="flex gap-3 mb-6 relative z-10"><button- type='button'- className='inline-flex items-center gap-2 border border-emerald-500 text-emerald-600 dark:text-emerald-500 bg-transparent hover:bg-emerald-500 hover:text-white dark:hover:bg-emerald-600 dark:hover:text-white px-5 py-2 rounded-lg transition-colors font-medium'+ type="button"+ className="inline-flex items-center gap-2 border border-emerald-500 text-emerald-600 dark:text-emerald-500 bg-transparent hover:bg-emerald-500 hover:text-white dark:hover:bg-emerald-600 dark:hover:text-white px-5 py-2 rounded-lg transition-colors font-medium"onClick={onClickYes}- aria-label='Yes, this page was helpful'+ aria-label="Yes, this page was helpful">- <ThumbsUpIcon width={20} height={20} weight='duotone' />+ <ThumbsUpIcon width={20} height={20} weight="duotone" />Yes</button><button- type='button'- className='inline-flex items-center gap-2 border border-red-500 text-red-600 dark:text-red-500 bg-transparent hover:bg-red-500 hover:text-white dark:hover:bg-red-600 dark:hover:text-white px-5 py-2 rounded-lg transition-colors font-medium'+ type="button"+ className="inline-flex items-center gap-2 border border-red-500 text-red-600 dark:text-red-500 bg-transparent hover:bg-red-500 hover:text-white dark:hover:bg-red-600 dark:hover:text-white px-5 py-2 rounded-lg transition-colors font-medium"onClick={onClickNo}- aria-label='No, this page was not helpful'+ aria-label="No, this page was not helpful">- <ThumbsDownIcon width={20} height={20} weight='duotone' />+ <ThumbsDownIcon width={20} height={20} weight="duotone" />No</button></div>@@ -177,20 +188,23 @@ export function FeedbackWidget() {)}</>)}- <div className='mt-6 pt-4 border-t border-gray-200 dark:border-slate-800 flex items-center gap-3 flex-wrap text-sm text-slate-500 dark:text-slate-400 relative z-10'>- <Link className='font-medium hover:text-slate-900 dark:hover:text-white transition-colors' href='/contribute'>+ <div className="mt-6 pt-4 border-t border-gray-200 dark:border-slate-800 flex items-center gap-3 flex-wrap text-sm text-slate-500 dark:text-slate-400 relative z-10">+ <Link+ className="font-medium hover:text-slate-900 dark:hover:text-white transition-colors"+ href="/contribute"+ >Learn how to contribute</Link>- <span className='opacity-40'>•</span>+ <span className="opacity-40">•</span><Link- className='font-medium hover:text-slate-900 dark:hover:text-white transition-colors'- href='https://github.com/Swetrix/swetrix/issues'- target='_blank'- rel='noopener noreferrer'+ className="font-medium hover:text-slate-900 dark:hover:text-white transition-colors"+ href="https://github.com/Swetrix/swetrix/issues"+ target="_blank"+ rel="noopener noreferrer">Report a problem with this content</Link></div></section>- )+ );}diff --git a/docs/components/GoogleGIcon.tsx b/docs/components/GoogleGIcon.tsxindex 41356846c..34bc3ade2 100644--- a/docs/components/GoogleGIcon.tsx+++ b/docs/components/GoogleGIcon.tsx@@ -1,34 +1,34 @@-import type { ComponentType } from 'react';+import type { ComponentType } from "react";const GoogleGSVG = ({ className }: { className?: string }) => (- <svg className={className} viewBox='0 0 186.69 190.5'>- <g transform='translate(1184.583 765.171)'>+ <svg className={className} viewBox="0 0 186.69 190.5">+ <g transform="translate(1184.583 765.171)"><path- clipPath='none'- mask='none'- d='M-1089.333-687.239v36.888h51.262c-2.251 11.863-9.006 21.908-19.137 28.662l30.913 23.986c18.011-16.625 28.402-41.044 28.402-70.052 0-6.754-.606-13.249-1.732-19.483z'- fill='#4285f4'+ clipPath="none"+ mask="none"+ d="M-1089.333-687.239v36.888h51.262c-2.251 11.863-9.006 21.908-19.137 28.662l30.913 23.986c18.011-16.625 28.402-41.044 28.402-70.052 0-6.754-.606-13.249-1.732-19.483z"+ fill="#4285f4"/><path- clipPath='none'- mask='none'- d='M-1142.714-651.791l-6.972 5.337-24.679 19.223h0c15.673 31.086 47.796 52.561 85.03 52.561 25.717 0 47.278-8.486 63.038-23.033l-30.913-23.986c-8.486 5.715-19.31 9.179-32.125 9.179-24.765 0-45.806-16.712-53.34-39.226z'- fill='#34a853'+ clipPath="none"+ mask="none"+ d="M-1142.714-651.791l-6.972 5.337-24.679 19.223h0c15.673 31.086 47.796 52.561 85.03 52.561 25.717 0 47.278-8.486 63.038-23.033l-30.913-23.986c-8.486 5.715-19.31 9.179-32.125 9.179-24.765 0-45.806-16.712-53.34-39.226z"+ fill="#34a853"/><path- clipPath='none'- mask='none'- d='M-1174.365-712.61c-6.494 12.815-10.217 27.276-10.217 42.689s3.723 29.874 10.217 42.689c0 .086 31.693-24.592 31.693-24.592-1.905-5.715-3.031-11.776-3.031-18.098s1.126-12.383 3.031-18.098z'- fill='#fbbc05'+ clipPath="none"+ mask="none"+ d="M-1174.365-712.61c-6.494 12.815-10.217 27.276-10.217 42.689s3.723 29.874 10.217 42.689c0 .086 31.693-24.592 31.693-24.592-1.905-5.715-3.031-11.776-3.031-18.098s1.126-12.383 3.031-18.098z"+ fill="#fbbc05"/><path- clipPath='none'- mask='none'- d='M-1089.333-727.244c14.028 0 26.497 4.849 36.455 14.201l27.276-27.276c-16.539-15.413-38.013-24.852-63.731-24.852-37.234 0-69.359 21.388-85.032 52.561l31.692 24.592c7.533-22.514 28.575-39.226 53.34-39.226z'- fill='#ea4335'+ clipPath="none"+ mask="none"+ d="M-1089.333-727.244c14.028 0 26.497 4.849 36.455 14.201l27.276-27.276c-16.539-15.413-38.013-24.852-63.731-24.852-37.234 0-69.359 21.388-85.032 52.561l31.692 24.592c7.533-22.514 28.575-39.226 53.34-39.226z"+ fill="#ea4335"/></g></svg>-)+);-export default GoogleGSVG+export default GoogleGSVG;diff --git a/docs/components/Icon.tsx b/docs/components/Icon.tsxindex 14c09e8b4..0c1963547 100644--- a/docs/components/Icon.tsx+++ b/docs/components/Icon.tsx@@ -1,7 +1,7 @@-'use client';+"use client";-import * as PhosphorIcons from '@phosphor-icons/react';-import { createElement } from 'react';+import * as PhosphorIcons from "@phosphor-icons/react";+import { createElement } from "react";export function Icon({ name }: { name: string }) {const IconComponent = PhosphorIcons[name as keyof typeof PhosphorIcons] as any;diff --git a/docs/components/IntegrationsGrid.tsx b/docs/components/IntegrationsGrid.tsxindex 644220542..01b779228 100644--- a/docs/components/IntegrationsGrid.tsx+++ b/docs/components/IntegrationsGrid.tsx@@ -1,8 +1,8 @@-'use client';+"use client";-import Link from 'next/link';-import { Cards, Card } from 'fumadocs-ui/components/card';-import type { ComponentType } from 'react';+import Link from "next/link";+import { Cards, Card } from "fumadocs-ui/components/card";+import type { ComponentType } from "react";import {siAngular,siAstro,@@ -33,168 +33,168 @@ import {siWoocommerce,siWordpress,type SimpleIcon,-} from 'simple-icons';-import GoogleGIcon from './GoogleGIcon';+} from "simple-icons";+import GoogleGIcon from "./GoogleGIcon";-const cn = (...classes: (string | undefined | null | false)[]) => classes.filter(Boolean).join(' ');+const cn = (...classes: (string | undefined | null | false)[]) => classes.filter(Boolean).join(" ");const INTEGRATIONS: {- name: string- href: string- icon?: SimpleIcon- customIcon?: ComponentType<{ className?: string }>- iconClassName?: string+ name: string;+ href: string;+ icon?: SimpleIcon;+ customIcon?: ComponentType<{ className?: string }>;+ iconClassName?: string;}[] = [{- name: 'Angular',- href: '/angular-integration',+ name: "Angular",+ href: "/angular-integration",icon: siAngular,- iconClassName: 'text-[#DD0031]',+ iconClassName: "text-[#DD0031]",},{- name: 'Astro',- href: '/astro-integration',+ name: "Astro",+ href: "/astro-integration",icon: siAstro,},{- name: 'BigCommerce',- href: '/bigcommerce-integration',+ name: "BigCommerce",+ href: "/bigcommerce-integration",icon: siBigcommerce,- iconClassName: 'dark:text-white',+ iconClassName: "dark:text-white",},{- name: 'Carrd',- href: '/carrd-integration',+ name: "Carrd",+ href: "/carrd-integration",icon: siCarrd,},{- name: 'Django',- href: '/django-integration',+ name: "Django",+ href: "/django-integration",icon: siDjango,- iconClassName: 'dark:text-[#44B78B]',+ iconClassName: "dark:text-[#44B78B]",},{- name: 'Docusaurus',- href: '/docusaurus-integration',+ name: "Docusaurus",+ href: "/docusaurus-integration",icon: siDocusaurus,},{- name: 'Drupal',- href: '/drupal-integration',+ name: "Drupal",+ href: "/drupal-integration",icon: siDrupal,},{- name: 'Flask',- href: '/flask-integration',+ name: "Flask",+ href: "/flask-integration",icon: siFlask,},{- name: 'Framer',- href: '/framer-integration',+ name: "Framer",+ href: "/framer-integration",icon: siFramer,},{- name: 'Gatsby',- href: '/gatsby-integration',+ name: "Gatsby",+ href: "/gatsby-integration",icon: siGatsby,},{- name: 'Ghost',- href: '/ghost-integration',+ name: "Ghost",+ href: "/ghost-integration",icon: siGhost,- iconClassName: 'dark:text-white',+ iconClassName: "dark:text-white",},{- name: 'Search Console',- href: '/integrations/google-search-console',+ name: "Search Console",+ href: "/integrations/google-search-console",customIcon: GoogleGIcon,},{- name: 'GTM',- href: '/gtm-integration',+ name: "GTM",+ href: "/gtm-integration",icon: siGoogletagmanager,},{- name: 'Hugo',- href: '/hugo-integration',+ name: "Hugo",+ href: "/hugo-integration",icon: siHugo,},{- name: 'Jekyll',- href: '/jekyll-integration',+ name: "Jekyll",+ href: "/jekyll-integration",icon: siJekyll,},{- name: 'Laravel',- href: '/laravel-integration',+ name: "Laravel",+ href: "/laravel-integration",icon: siLaravel,},{- name: 'Next.js',- href: '/nextjs-integration',+ name: "Next.js",+ href: "/nextjs-integration",icon: siNextdotjs,- iconClassName: 'dark:text-white',+ iconClassName: "dark:text-white",},{- name: 'Nuxt',- href: '/nuxt-integration',+ name: "Nuxt",+ href: "/nuxt-integration",icon: siNuxt,},{- name: 'React',- href: '/react-integration',+ name: "React",+ href: "/react-integration",icon: siReact,},{- name: 'Remix',- href: '/remix-integration',+ name: "Remix",+ href: "/remix-integration",icon: siRemix,- iconClassName: 'dark:text-white',+ iconClassName: "dark:text-white",},{- name: 'Ruby on Rails',- href: '/ruby-on-rails-integration',+ name: "Ruby on Rails",+ href: "/ruby-on-rails-integration",icon: siRubyonrails,},{- name: 'Shopify',- href: '/shopify-integration',+ name: "Shopify",+ href: "/shopify-integration",icon: siShopify,},{- name: 'Squarespace',- href: '/squarespace-integration',+ name: "Squarespace",+ href: "/squarespace-integration",icon: siSquarespace,- iconClassName: 'dark:text-white',+ iconClassName: "dark:text-white",},{- name: 'SvelteKit',- href: '/sveltekit-integration',+ name: "SvelteKit",+ href: "/sveltekit-integration",icon: siSvelte,},{- name: 'Vue',- href: '/vue-integration',+ name: "Vue",+ href: "/vue-integration",icon: siVuedotjs,},{- name: 'Webflow',- href: '/webflow-integration',+ name: "Webflow",+ href: "/webflow-integration",icon: siWebflow,},{- name: 'Wix',- href: '/wix-integration',+ name: "Wix",+ href: "/wix-integration",icon: siWix,},{- name: 'WooCommerce',- href: '/woocommerce-integration',+ name: "WooCommerce",+ href: "/woocommerce-integration",icon: siWoocommerce,},{- name: 'WordPress',- href: '/wordpress-integration',+ name: "WordPress",+ href: "/wordpress-integration",icon: siWordpress,},];@@ -204,38 +204,28 @@ const IntegrationLogo = ({className,style,}: {- icon: SimpleIcon- className?: string- style?: React.CSSProperties+ icon: SimpleIcon;+ className?: string;+ style?: React.CSSProperties;}) => (- <svg- viewBox='0 0 24 24'- className={className}- style={style}- aria-hidden='true'- >- <path fill='currentColor' d={icon.path} />+ <svg viewBox="0 0 24 24" className={className} style={style} aria-hidden="true">+ <path fill="currentColor" d={icon.path} /></svg>-)+);export function IntegrationsGrid() {return (<Cards className="sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">{INTEGRATIONS.map((integration) => {const icon = integration.customIcon ? (- <integration.customIcon- className={cn(integration.iconClassName)}- />+ <integration.customIcon className={cn(integration.iconClassName)} />) : integration.icon ? (<IntegrationLogoicon={integration.icon}- className={cn(- 'text-(--brand-color)',- integration.iconClassName,- )}+ className={cn("text-(--brand-color)", integration.iconClassName)}style={{- '--brand-color': `#${integration.icon.hex}`,+ "--brand-color": `#${integration.icon.hex}`,} as React.CSSProperties}/>diff --git a/docs/content/docs/accountsettings/api-keys.mdx b/docs/content/docs/accountsettings/api-keys.mdxindex 7c4bb0499..081d44ddc 100644--- a/docs/content/docs/accountsettings/api-keys.mdx+++ b/docs/content/docs/accountsettings/api-keys.mdx@@ -3,7 +3,6 @@ title: API Keysslug: /settings/api-keys----API keys allow you to authenticate with the Swetrix API programmatically. You can use them to retrieve statistics, manage your account, and more.## Creating an API Key@@ -17,7 +16,6 @@ To create a new API key:Your new API key will be displayed.-<Callout type="warn">Treat your API key like a password. Do not share it publicly or commit it to version control systems.diff --git a/docs/content/docs/accountsettings/change-email.mdx b/docs/content/docs/accountsettings/change-email.mdxindex f74b412c9..7a1cefb9f 100644--- a/docs/content/docs/accountsettings/change-email.mdx+++ b/docs/content/docs/accountsettings/change-email.mdx@@ -3,7 +3,6 @@ title: How to change your Swetrix account emailslug: /settings/change-email----To change your email, you need to log in to your account and go to the [account settings page](https://swetrix.com/user-settings).On the "Account" tab ("General settings" section), you will see the "Email" input field. There you will see your current email address.diff --git a/docs/content/docs/accountsettings/change-password.mdx b/docs/content/docs/accountsettings/change-password.mdxindex 980d60ed7..0013353e9 100644--- a/docs/content/docs/accountsettings/change-password.mdx+++ b/docs/content/docs/accountsettings/change-password.mdx@@ -3,7 +3,6 @@ title: How to change or reset your Swetrix account passwordslug: /settings/change-password----## How to change your passwordTo change your password, you need to log in to your account and go to the [account settings page](https://swetrix.com/user-settings).diff --git a/docs/content/docs/accountsettings/delete-account.mdx b/docs/content/docs/accountsettings/delete-account.mdxindex 35aec04a3..e0b710380 100644--- a/docs/content/docs/accountsettings/delete-account.mdx+++ b/docs/content/docs/accountsettings/delete-account.mdx@@ -3,14 +3,12 @@ title: Delete your accountslug: /settings/delete-account----To delete your Swetrix account, you need to log in to your account and go to the [account settings page](https://swetrix.com/user-settings).Make sure you unsubscribed from the paid subscription if you have one. You can do this on the [billing page](https://swetrix.com/billing).Click on the "Account" tab and then down to the end of the page. There you will see the "Delete account" button that will allow you to delete your account.-<Callout type="warn">Deleting your account will delete all your data permanently and you will not be able to recover it.diff --git a/docs/content/docs/accountsettings/email-reports.mdx b/docs/content/docs/accountsettings/email-reports.mdxindex c12e07eda..a6576d1e3 100644--- a/docs/content/docs/accountsettings/email-reports.mdx+++ b/docs/content/docs/accountsettings/email-reports.mdx@@ -3,10 +3,8 @@ title: Email reportsslug: /email-reports----Swetrix can send you regular email reports containing a summary of your projects' performance. This is a great way to keep track of your website's traffic without having to log in to the dashboard every time.-<Callout type="info">This feature is available only on Swetrix Cloud. If you are self-hosting Swetrix, you won't see this setting.@@ -47,7 +45,6 @@ You can choose to receive reports:Once you have selected your preferred frequency, click the **Save** button to apply the changes.-<Callout type="info">If you want to invite other people (like your team members or clients) to receive reports for a specific website, you should use the [site-specific email reports feature](/how-to-invite-users-to-your-website) instead. The account-level email reports described here are intended for your personal overview of all your projects.diff --git a/docs/content/docs/accountsettings/other-settings.mdx b/docs/content/docs/accountsettings/other-settings.mdxindex 0caf90495..7b9667698 100644--- a/docs/content/docs/accountsettings/other-settings.mdx+++ b/docs/content/docs/accountsettings/other-settings.mdx@@ -3,7 +3,6 @@ title: Other account settingsslug: /settings/other-settings----## How to link Google / Github accounts with your Swetrix accountSocialisation feature allows you to link 3rd party accounts (like Google or Github) to your Swetrix account and use them to sign in to Swetrix.@@ -14,7 +13,6 @@ A popup window will be opened prompting you to log into the account you want toAfter you connect it, you will be able to login to Swetrix using this account. You can also unlink it at any time.-<Callout>Please note that if you used Google or Github SSO feature to create an account, you will not be able to unlink it.diff --git a/docs/content/docs/accountsettings/teams-and-integrations.mdx b/docs/content/docs/accountsettings/teams-and-integrations.mdxindex 7be9b2ef4..f1794b7df 100644--- a/docs/content/docs/accountsettings/teams-and-integrations.mdx+++ b/docs/content/docs/accountsettings/teams-and-integrations.mdx@@ -3,7 +3,6 @@ title: Teams & Integrationsslug: /teams-api-integrations----Beyond basic profile settings, Swetrix offers powerful tools for collaboration, automation, and customisation.## Organisations (Teams)diff --git a/docs/content/docs/accountsettings/two-factor-authentication.mdx b/docs/content/docs/accountsettings/two-factor-authentication.mdxindex 847367d6a..b36370e5f 100644--- a/docs/content/docs/accountsettings/two-factor-authentication.mdx+++ b/docs/content/docs/accountsettings/two-factor-authentication.mdx@@ -3,7 +3,6 @@ title: Set up 2-factor authentication (2FA) for your accountslug: /settings/2-factor-authentication----Two-factor authentication (2FA) adds a second layer of defense to your account, so even if someone gets hold of your password they still can’t sign in.Once 2FA is enabled, when you try to log into your account you’ll need:@@ -37,7 +36,6 @@ To disable 2FA, on the [account settings page](https://swetrix.com/user-settingsIn the input field shown afterwards, enter a one-time code generated by your authenticator app or a recovery code and click on the "Disable" button.-<Callout type="warn">Once you disable the 2FA, verification codes from the authenticator application and saved recovery codes will become invalid.diff --git a/docs/content/docs/adblockers/guides/meta.json b/docs/content/docs/adblockers/guides/meta.jsonindex 47ec74113..af49c98d6 100644--- a/docs/content/docs/adblockers/guides/meta.json+++ b/docs/content/docs/adblockers/guides/meta.json@@ -1,8 +1,4 @@{"title": "Proxy guides",- "pages": [- "netlify",- "nextjs",- "nginx"- ]+ "pages": ["netlify", "nextjs", "nginx"]}diff --git a/docs/content/docs/adblockers/guides/netlify.mdx b/docs/content/docs/adblockers/guides/netlify.mdxindex ca0b0e1a3..e9930223d 100644--- a/docs/content/docs/adblockers/guides/netlify.mdx+++ b/docs/content/docs/adblockers/guides/netlify.mdx@@ -16,7 +16,6 @@ First, you need to add the following rules to the `_redirects` file. If you don'Instead of `/script.js` and `/sproxy` routes, you can use any other name. We recommend using a generic name or even just random letters to avoid being blocked by adblockers in the future.-<Callout>Make sure you don't use `/log`, `/analytics`, `/analytics.js` or any similar name, because they're blocked by many adblockers by default.@@ -27,12 +26,11 @@ Make sure you don't use `/log`, `/analytics`, `/analytics.js` or any similar namAfter you set up Netlify redirect rules, you need to update swetrix.js tracking script to send analytics data through it. You can do it by setting the `apiURL` property inside the [init() function](/swetrix-js-reference#init).```javascript-swetrix.init('YOUR_PROJECT_ID', {- apiURL: 'https://<yourproxydomain>/sproxy',-})+swetrix.init("YOUR_PROJECT_ID", {+ apiURL: "https://<yourproxydomain>/sproxy",+});```-<Callout>If you are not using the [Swetrix NPM package](/install-script#install-swetrix-via-npm), don't forget to also replace `https://swetrix.org/swetrix.js` with your proxy URL in the analytics `<script>` tag.diff --git a/docs/content/docs/adblockers/guides/nextjs.mdx b/docs/content/docs/adblockers/guides/nextjs.mdxindex 16583f676..23a23b004 100644--- a/docs/content/docs/adblockers/guides/nextjs.mdx+++ b/docs/content/docs/adblockers/guides/nextjs.mdx@@ -14,17 +14,16 @@ module.exports = {async rewrites() {return [{- source: '/sproxy/:path*',- destination: 'https://api.swetrix.com/log/:path*',+ source: "/sproxy/:path*",+ destination: "https://api.swetrix.com/log/:path*",},- ]+ ];},-}+};```Instead of `/sproxy` route, you can use any other name. We recommend using a generic name or even just random letters to avoid being blocked by adblockers in the future.-<Callout>Make sure you don't use `/log`, `/analytics`, `/analytics.js` or any similar name, because they're blocked by many adblockers by default.@@ -37,7 +36,7 @@ If you are not using the [Swetrix NPM package](/install-script#install-swetrix-vAfter you set up Next.js redirect rules, you need to update swetrix.js tracking script to send analytics data through it. You can do it by setting the `apiURL` property inside the [init() function](/swetrix-js-reference#init).```javascript-swetrix.init('YOUR_PROJECT_ID', {- apiURL: 'https://<yourproxydomain>/sproxy',-})+swetrix.init("YOUR_PROJECT_ID", {+ apiURL: "https://<yourproxydomain>/sproxy",+});```diff --git a/docs/content/docs/adblockers/guides/nginx.mdx b/docs/content/docs/adblockers/guides/nginx.mdxindex 5b7c3abf6..a13ac2bd0 100644--- a/docs/content/docs/adblockers/guides/nginx.mdx+++ b/docs/content/docs/adblockers/guides/nginx.mdx@@ -59,12 +59,11 @@ server {After you updated your Nginx configuration, you need to update swetrix.js tracking script to send analytics data through your server. You can do it by setting the `apiURL` property inside the [init() function](/swetrix-js-reference#init).```javascript-swetrix.init('YOUR_PROJECT_ID', {- apiURL: 'https://<yourproxydomain>/log',-})+swetrix.init("YOUR_PROJECT_ID", {+ apiURL: "https://<yourproxydomain>/log",+});```-<Callout>If you are not using the [Swetrix NPM package](/install-script#install-swetrix-via-npm), don't forget to also replace `https://swetrix.org/swetrix.js` with your proxy URL in the analytics `<script>` tag.diff --git a/docs/content/docs/adblockers/how-to-deal-with-adblockers.mdx b/docs/content/docs/adblockers/how-to-deal-with-adblockers.mdxindex d2491ac74..6880d05b6 100644--- a/docs/content/docs/adblockers/how-to-deal-with-adblockers.mdx+++ b/docs/content/docs/adblockers/how-to-deal-with-adblockers.mdx@@ -3,7 +3,6 @@ title: How to deal with adblockersslug: /adblockers/how-to----Swetrix is a privacy-first analytics tool, but some adblockers may still block it. In most cases, adblock maintainers don't want to take responsibility for deciding which services to block and which not to block, and we don't blame them. It's a big responsibility to maintain such ad block lists.Nevertheless, Swetrix is an open source, privacy-focused, cookie-less web analytics service. We never sell, share or do anything nasty with your data, and we want to give you the choice to bypass ad blockers.diff --git a/docs/content/docs/adblockers/meta.json b/docs/content/docs/adblockers/meta.jsonindex 8bdc9eb9a..ce07efd53 100644--- a/docs/content/docs/adblockers/meta.json+++ b/docs/content/docs/adblockers/meta.json@@ -1,7 +1,4 @@{"title": "Adblockers",- "pages": [- "how-to-deal-with-adblockers",- "guides"- ]+ "pages": ["how-to-deal-with-adblockers", "guides"]}diff --git a/docs/content/docs/add-script.mdx b/docs/content/docs/add-script.mdxindex c729d7481..31fd39311 100644--- a/docs/content/docs/add-script.mdx+++ b/docs/content/docs/add-script.mdx@@ -4,10 +4,8 @@ slug: /install-scripticon: Code----To use Swetrix on your website, you need to add a tracking script to your website and there are several ways to do this.-<Callout type="info" title="Using a CMS or site builder?">If your website runs on WordPress, Wix, Shopify, Webflow, or another CMS/site builder, use a dedicated integration guide instead of editing HTML manually.@@ -25,10 +23,10 @@ To do this, paste the following code snippet into the Body section (`<body>` tag```html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -40,7 +38,6 @@ To do this, paste the following code snippet into the Body section (`<body>` tag</noscript>```-<Callout type="warn">It's important to remember to replace `YOUR_PROJECT_ID` with your actual Project ID, which you can find in the Dashboard, otherwise tracking will not work!@@ -60,6 +57,7 @@ If you are using a website based on a JavaScript framework such as React or Vue,```bashnpm install swetrix```+</Step><Step>### Import Swetrix@@ -67,8 +65,9 @@ npm install swetrixImport the module into your project's root file (in React this is usually called `index.js` or `App.js`, and these files are located in the `src` folder):```js-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";```+</Step><Step>### Start tracking@@ -76,9 +75,10 @@ import * as Swetrix from 'swetrix'After that you can track anything you want. For example, the following code snippet will work just fine:```js-Swetrix.init('YOUR_PROJECT_ID')-Swetrix.trackViews()+Swetrix.init("YOUR_PROJECT_ID");+Swetrix.trackViews();```+</Step></Steps>diff --git a/docs/content/docs/analytics-dashboard/alerts.mdx b/docs/content/docs/analytics-dashboard/alerts.mdxindex 0fa311b74..f14c89d2c 100644--- a/docs/content/docs/analytics-dashboard/alerts.mdx+++ b/docs/content/docs/analytics-dashboard/alerts.mdx@@ -4,8 +4,6 @@ title: Alertssidebar_label: Alerts-----<Callout type="info" title="Cloud Exclusive">The Alerts feature is exclusively available on **Swetrix Cloud**. It is not currently available for self-hosted instances at the moment.@@ -26,7 +24,10 @@ Before setting up alerts, you must connect a notification channel to your accounTo configure these, go to your **Account Settings** and follow the instructions for each integration. If no channel is connected, you will see a warning on the Alerts page.-<img alt="Alert communication channels" src="/docs/img/accountsettings/communication-channels.png" />+<img+ alt="Alert communication channels"+ src="/docs/img/accountsettings/communication-channels.png"+/>## Creating an Alertdiff --git a/docs/content/docs/analytics-dashboard/ask-ai.mdx b/docs/content/docs/analytics-dashboard/ask-ai.mdxindex 6a0d82d88..c6379e485 100644--- a/docs/content/docs/analytics-dashboard/ask-ai.mdx+++ b/docs/content/docs/analytics-dashboard/ask-ai.mdx@@ -3,7 +3,6 @@ title: Ask AIslug: /analytics-dashboard/ask-ai----Ask AI is a powerful feature that allows you to query your analytics data using natural language. Instead of manually filtering and analyzing complex datasets, you can simply ask a question and get immediate insights.## How it worksdiff --git a/docs/content/docs/analytics-dashboard/captcha.mdx b/docs/content/docs/analytics-dashboard/captcha.mdxindex fa5356a7a..d183e1fba 100644--- a/docs/content/docs/analytics-dashboard/captcha.mdx+++ b/docs/content/docs/analytics-dashboard/captcha.mdx@@ -4,7 +4,6 @@ title: Captcha Analyticssidebar_label: Captcha Analytics----The Captcha Analytics dashboard provides detailed insights into how users are interacting with the Swetrix CAPTCHA on your website. It helps you monitor completion rates and understand the demographics of users solving your CAPTCHAs.<img alt="Captcha Dashboard" src="/docs/img/analytics-dashboard/captcha-view.png" />@@ -13,7 +12,6 @@ The Captcha Analytics dashboard provides detailed insights into how users are inSwetrix offers a privacy-friendly, cookieless CAPTCHA solution that uses a Proof of Work mechanism. This dashboard allows you to track the performance of this feature and ensure legitimate users are successfully accessing your protected content while bots are kept at bay.-<Callout type="info">For more details on how Swetrix CAPTCHA works and how to integrate it, please refer to the [Captcha documentation](../captcha/introduction.md).diff --git a/docs/content/docs/analytics-dashboard/error-tracking.mdx b/docs/content/docs/analytics-dashboard/error-tracking.mdxindex e98a57c6a..4ed8d1443 100644--- a/docs/content/docs/analytics-dashboard/error-tracking.mdx+++ b/docs/content/docs/analytics-dashboard/error-tracking.mdx@@ -4,10 +4,12 @@ title: Error Trackingsidebar_label: Error Tracking----Error Tracking allows you to monitor and analyse exceptions that occur in your web application. It helps you identify stability issues, understand their impact on users, and debug them effectively with detailed stack traces and session context.-<img alt="Error tracking overview" src="/docs/img/analytics-dashboard/screenshot_errors_light.png" />+<img+ alt="Error tracking overview"+ src="/docs/img/analytics-dashboard/screenshot_errors_light.png"+/>## Setting updiff --git a/docs/content/docs/analytics-dashboard/experiments.mdx b/docs/content/docs/analytics-dashboard/experiments.mdxindex 91f9d9dc6..a02c32a55 100644--- a/docs/content/docs/analytics-dashboard/experiments.mdx+++ b/docs/content/docs/analytics-dashboard/experiments.mdx@@ -3,7 +3,6 @@ title: Experiments (A/B Testing)slug: /analytics-dashboard/experiments----Experiments (A/B Testing) allow you to test different variations of your application to see which one performs better. You can use experiments to optimize conversion rates, user engagement, and other key metrics.## Overview@@ -21,20 +20,20 @@ To use experiments in your application, you can use the Swetrix tracking script.### Fetching all experiments```javascript-import { getExperiments } from 'swetrix'+import { getExperiments } from "swetrix";-const experiments = await getExperiments()+const experiments = await getExperiments();// Returns: { 'experiment-id-1': 'variant-a', 'experiment-id-2': 'control' }```### Getting a specific experiment variant```javascript-import { getExperiment } from 'swetrix'+import { getExperiment } from "swetrix";-const variant = await getExperiment('checkout-redesign')+const variant = await getExperiment("checkout-redesign");-if (variant === 'new-checkout') {+if (variant === "new-checkout") {// Show new checkout flow} else {// Show control (original) checkoutdiff --git a/docs/content/docs/analytics-dashboard/feature-flags.mdx b/docs/content/docs/analytics-dashboard/feature-flags.mdxindex e33251a98..e9acb0055 100644--- a/docs/content/docs/analytics-dashboard/feature-flags.mdx+++ b/docs/content/docs/analytics-dashboard/feature-flags.mdx@@ -3,7 +3,6 @@ title: Feature Flagsslug: /analytics-dashboard/feature-flags----Feature flags allow you to toggle features on and off for your users without deploying new code. This is useful for rolling out new features gradually, testing in production, or quickly disabling a feature if something goes wrong.## Overview@@ -21,11 +20,11 @@ To use feature flags in your application, you can use the Swetrix tracking scrip### Fetching all flags```javascript-import { getFeatureFlags } from 'swetrix'+import { getFeatureFlags } from "swetrix";-const flags = await getFeatureFlags()+const flags = await getFeatureFlags();-if (flags['new-checkout']) {+if (flags["new-checkout"]) {// Show new checkout flow}```@@ -33,13 +32,13 @@ if (flags['new-checkout']) {### Getting a single flag```javascript-import { getFeatureFlag } from 'swetrix'+import { getFeatureFlag } from "swetrix";-const isEnabled = await getFeatureFlag('dark-mode', {+const isEnabled = await getFeatureFlag("dark-mode", {// Optional: provide a specific profileId if known,// otherwise it uses the one from init() or generates an anonymous one.- profileId: 'user-123',-})+ profileId: "user-123",+});if (isEnabled) {// Enable dark mode@@ -51,10 +50,10 @@ if (isEnabled) {Feature flags are cached for 5 minutes by default to minimize network requests. You can force a refresh or clear the cache if needed:```javascript-import { clearFeatureFlagsCache } from 'swetrix'+import { clearFeatureFlagsCache } from "swetrix";// Clear cache to force a fresh fetch on next call-clearFeatureFlagsCache()+clearFeatureFlagsCache();```## Managing Flagsdiff --git a/docs/content/docs/analytics-dashboard/funnels.mdx b/docs/content/docs/analytics-dashboard/funnels.mdxindex 6e21168ec..ddfc15500 100644--- a/docs/content/docs/analytics-dashboard/funnels.mdx+++ b/docs/content/docs/analytics-dashboard/funnels.mdx@@ -4,7 +4,6 @@ title: Funnelssidebar_label: Funnels----Funnels allow you to visualise and measure how many users complete a specific series of steps on your website. This is essential for understanding conversion rates and identifying where users drop off in key processes like sign-ups, checkouts, or onboarding flows.<img alt="Funnel view" src="/docs/img/analytics-dashboard/funnel-view.png" />@@ -58,7 +57,6 @@ You can manage your funnels directly from the main list:- **Edit**: Click the **Settings** (gear) icon on a funnel card to change its name or modify the steps.- **Delete**: Click the **Delete** (trash bin) icon to remove the funnel permanently.-<Callout type="info" title="Permissions">Only project owners and administrators (managers) can create, edit, or delete funnels. View-only members can view the funnel data but cannot make changes.diff --git a/docs/content/docs/analytics-dashboard/goals.mdx b/docs/content/docs/analytics-dashboard/goals.mdxindex bf14cc12f..e8e07e279 100644--- a/docs/content/docs/analytics-dashboard/goals.mdx+++ b/docs/content/docs/analytics-dashboard/goals.mdx@@ -4,7 +4,6 @@ title: Goalssidebar_label: Goals----Goals allow you to track specific actions that visitors perform on your website. They help you measure how well your site fulfils your target objectives.<img alt="Goals list" src="/docs/img/analytics-dashboard/goals-list.png" />diff --git a/docs/content/docs/analytics-dashboard/live-visitors.mdx b/docs/content/docs/analytics-dashboard/live-visitors.mdxindex 8d4897965..19e404b31 100644--- a/docs/content/docs/analytics-dashboard/live-visitors.mdx+++ b/docs/content/docs/analytics-dashboard/live-visitors.mdx@@ -3,7 +3,6 @@ title: Live Visitorsslug: /analytics-dashboard/live-visitors----Swetrix provides real-time traffic monitoring, allowing you to see how many people are on your website right now.## The Live Counterdiff --git a/docs/content/docs/analytics-dashboard/performance.mdx b/docs/content/docs/analytics-dashboard/performance.mdxindex a99b26f7d..544e5d714 100644--- a/docs/content/docs/analytics-dashboard/performance.mdx+++ b/docs/content/docs/analytics-dashboard/performance.mdx@@ -3,7 +3,6 @@ sidebar_label: Performance Monitoringtitle: Performance Monitoring----The Performance tab gives you deep insights into your website's speed and user experience metrics. By monitoring these metrics, you can identify bottlenecks and optimize your site for faster load times.## Overviewdiff --git a/docs/content/docs/analytics-dashboard/segments.mdx b/docs/content/docs/analytics-dashboard/segments.mdxindex 5a0593257..62439aa25 100644--- a/docs/content/docs/analytics-dashboard/segments.mdx+++ b/docs/content/docs/analytics-dashboard/segments.mdx@@ -4,7 +4,6 @@ title: Segmentssidebar_label: Segments----Segments (also known as Saved Views) allow you to save a specific configuration of filters and custom metrics for quick access. Instead of manually reapplying the same filters every time you visit your dashboard, you can simply switch to a saved Segment.<img alt="Segments Modal" src="/docs/img/analytics-dashboard/segments.png" />diff --git a/docs/content/docs/analytics-dashboard/traffic.mdx b/docs/content/docs/analytics-dashboard/traffic.mdxindex 3e7a8954f..da3dd31dd 100644--- a/docs/content/docs/analytics-dashboard/traffic.mdx+++ b/docs/content/docs/analytics-dashboard/traffic.mdx@@ -4,7 +4,6 @@ title: Traffic Analyticssidebar_label: Traffic Analytics----The Traffic Analytics dashboard is the core of Swetrix, providing comprehensive insights into your website's visitors, their behavior, and traffic sources. It allows you to visualize data through interactive charts and detailed breakdowns.<img alt="Traffic Dashboard" src="/docs/img/analytics-dashboard/screenshot_light.png" />diff --git a/docs/content/docs/api/events.mdx b/docs/content/docs/api/events.mdxindex c4c2b380f..7e6452093 100644--- a/docs/content/docs/api/events.mdx+++ b/docs/content/docs/api/events.mdx@@ -11,7 +11,6 @@ We already provide several [integrations](/integrations) and a [script](/swetrix### Unique visitors tracking-<Callout type="warn">For the unique (and live) visitor functionality to work properly, each request must have the `User-Agent` and `X-Client-IP-Address` HTTP headers set. If you don't set these headers, the API will still work, but the unique visitor count will be incorrect.@@ -73,7 +72,7 @@ All of the values are numbers in milliseconds.| Name | Type | Required | Description || -------- | --------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `pid` | `string` | `true` | A project ID to record the pageview event for |-| `ev` | `string` | `true` | An event identifier you want to track. Can contain any characters (including spaces, unicode, etc.) with a maximum length of 256 characters. |+| `ev` | `string` | `true` | An event identifier you want to track. Can contain any characters (including spaces, unicode, etc.) with a maximum length of 256 characters. || `unique` | `boolean` | `false` | If set to true, only 1 custom event will be saved per session || `pg` | `string` | `false` | A page that user sent data from (e.g. `/home`) || `lc` | `string` | `false` | A locale of the user (e.g. `en-US` or `uk-UA`) |@@ -171,22 +170,22 @@ For more efficient heartbeat tracking (like long-running sessions, desktop appli**Example (using socket.io-client):**```javascript-import { io } from 'socket.io-client'+import { io } from "socket.io-client";-const socket = io('https://api.swetrix.com/hb', {+const socket = io("https://api.swetrix.com/hb", {query: {- pid: 'YOUR_PROJECT_ID',+ pid: "YOUR_PROJECT_ID",},- transports: ['websocket'], // Optional: force WebSocket transport-})+ transports: ["websocket"], // Optional: force WebSocket transport+});-socket.on('connected', () => {- console.log('Heartbeat session established')-})+socket.on("connected", () => {+ console.log("Heartbeat session established");+});-socket.on('error', (err) => {- console.error('Heartbeat error:', err.message)-})+socket.on("error", (err) => {+ console.error("Heartbeat error:", err.message);+});// The server automatically handles the heartbeat interval (every 60s)// Keep the connection open as long as the user is active on the page@@ -253,21 +252,21 @@ Also as an example, feel free to check out the [source code](https://github.com/### Recording a pageview event using JavaScript fetch API```javascript-fetch('https://api.swetrix.com/log', {- method: 'POST',+fetch("https://api.swetrix.com/log", {+ method: "POST",headers: {- 'User-Agent': 'FORWARD_CLIENT_USER_AGENT_HERE',- 'X-Client-IP-Address': 'FORWARD_CLIENT_IP_ADDRESS_HERE',- 'Content-Type': 'application/json',+ "User-Agent": "FORWARD_CLIENT_USER_AGENT_HERE",+ "X-Client-IP-Address": "FORWARD_CLIENT_IP_ADDRESS_HERE",+ "Content-Type": "application/json",},body: JSON.stringify({- pid: 'YOUR_PROJECT_ID',- lc: 'en-US',- pg: '/',- tz: 'UTC',+ pid: "YOUR_PROJECT_ID",+ lc: "en-US",+ pg: "/",+ tz: "UTC",unique: false,}),-})+});```### Recording a custom event using Go net/httpdiff --git a/docs/content/docs/api/meta.json b/docs/content/docs/api/meta.jsonindex bbc0f8505..958983eb7 100644--- a/docs/content/docs/api/meta.json+++ b/docs/content/docs/api/meta.json@@ -1,8 +1,4 @@{"title": "API",- "pages": [- "stats",- "events",- "admin"- ]+ "pages": ["stats", "events", "admin"]}diff --git a/docs/content/docs/api/stats.mdx b/docs/content/docs/api/stats.mdxindex ded708fd3..99e3b8a97 100644--- a/docs/content/docs/api/stats.mdx+++ b/docs/content/docs/api/stats.mdx@@ -41,7 +41,6 @@ If you have special needs for more requests, please contact us to request more c- **24M** - last 24 months.- **all** - all time (i.e. the time starting from the project creation date).-<Callout type="info">`Time buckets` and `periods` are predefined values that you can use in your API requests. The API won't accept any other values. If you want to specify a custom time range, use `from` and `to` parameters in your aggregation requests.diff --git a/docs/content/docs/billing/exceeding-plan-limits.mdx b/docs/content/docs/billing/exceeding-plan-limits.mdxindex ec50582e1..043c1b72f 100644--- a/docs/content/docs/billing/exceeding-plan-limits.mdx+++ b/docs/content/docs/billing/exceeding-plan-limits.mdx@@ -4,7 +4,9 @@ slug: /exceeding-plan-limits---<Callout type="info">-We don't stop collecting traffic or charge extra if you have an occasional traffic spike. We also don't stop collecting data if you miss your invoice for a short period of time. There are no hidden charges and we won't charge your card unexpectedly.+ We don't stop collecting traffic or charge extra if you have an occasional traffic spike. We also+ don't stop collecting data if you miss your invoice for a short period of time. There are no+ hidden charges and we won't charge your card unexpectedly.</Callout>If you exceed your subscription plan, we won't automatically upgrade you to the next one because it's unethical.@@ -19,7 +21,9 @@ If this happens, we will not lock your dashboard immediately. Instead, we will gWe may also lock your dashboard if you miss a bill. We will lock the dashboard after 5 failed attempts.<Callout>-We will not stop collecting your analytics data even if your dashboard is temporarily locked. If you upgrade to an appropriate tier that reflects your traffic usage (or the payment issues are resolved) - the dashboard will automatically be unlocked.+ We will not stop collecting your analytics data even if your dashboard is temporarily locked. If+ you upgrade to an appropriate tier that reflects your traffic usage (or the payment issues are+ resolved) - the dashboard will automatically be unlocked.</Callout>We will only stop collecting data if our invoices go unpaid for many months, the dashboard is locked for a long time, or if you have exceptionally high traffic to your site and the billing issue is not resolved.diff --git a/docs/content/docs/billing/faq.mdx b/docs/content/docs/billing/faq.mdxindex 206d1e242..ae5df5ed5 100644--- a/docs/content/docs/billing/faq.mdx+++ b/docs/content/docs/billing/faq.mdx@@ -3,7 +3,6 @@ title: Billing FAQslug: /billing-faq----## How does billing work?If you subscribe to a monthly plan, you will be billed the same amount on the same day (unless you upgrade or downgrade your plan). For example, if you subscribe on the 15th of July, you will be billed on the 15th of each subsequent month.@@ -35,7 +34,8 @@ We accept credit/debit cards, PayPal, Google Pay and Apple Pay. All payments areYou can add your company details and VAT ID when subscribing to one of our plans. If you're eligible, no VAT or other sales taxes will be added to your subscription price.<img alt="Add VAT on checkout" src="/docs/img/billing/checkout_add_vat.png" />-<br /><br />+<br />+<br />You can also add your VAT number after you created a subscription, to do that open the invoice Paddle sent you to your email address, and click on the "Add address & VAT Number" button.@@ -47,8 +47,12 @@ If your VAT number has a country code prefix in it (e.g. "DE" in "DE123456789"),The reason for this is that you are selecting the country code from the list of countries below, so the VAT number is validated separately. Our payment processor Paddle handles the VAT processing. Here is [a list of VAT numbers formats](https://www.paddle.com/help/sell/tax/what-format-should-i-use-for-my-vat-id) accepted by Paddle.-<img alt="Unable to validate VAT number" src="/docs/img/billing/checkout_unable_to_validate_vat.png" />-<br /><br />+<img+ alt="Unable to validate VAT number"+ src="/docs/img/billing/checkout_unable_to_validate_vat.png"+/>+<br />+<br />If you are still having this issue, please [contact us](https://swetrix.com/contact).diff --git a/docs/content/docs/billing/upgrade-from-trial.mdx b/docs/content/docs/billing/upgrade-from-trial.mdxindex 2e2199356..3ad390644 100644--- a/docs/content/docs/billing/upgrade-from-trial.mdx+++ b/docs/content/docs/billing/upgrade-from-trial.mdx@@ -3,11 +3,11 @@ title: Upgrade from trial to a paid subscriptionslug: /upgrade-from-trial-to-a-paid-subscription----At any time during your trial, or once it's over, you can upgrade to a paid subscription.<Callout type="info">-We do not stop collection or reset your collected data. The analytics data is preserved when you update from a trial to a paid plan, or change your paid subscription to another plan.+ We do not stop collection or reset your collected data. The analytics data is preserved when you+ update from a trial to a paid plan, or change your paid subscription to another plan.</Callout>## Updating to a paid subscription@@ -23,6 +23,7 @@ You will see the Plan usage section with an indicator of how many events you useWe count pageviews, error events, and custom events as "events".Using the subscription plan selector, choose a plan based on your estimated usage, and the billing frequency (monthly or yearly). You can get 2 free months with a yearly subscription.+</Step><Step>### Start the upgrade@@ -43,6 +44,7 @@ Choose your location and click on the "Continue" button.Next you need to select your payment method and enter your payment details. You can pay by PayPal, payment card, or Apple and Google Pay if supported by your device.After you're done, click on the "Subscribe now" button to complete the subscription. You'll receive an email confirmation and your subscription will be active immediately.+</Step></Steps>diff --git a/docs/content/docs/captcha/client-side-usage.mdx b/docs/content/docs/captcha/client-side-usage.mdxindex d1ef38a96..b6eb92064 100644--- a/docs/content/docs/captcha/client-side-usage.mdx+++ b/docs/content/docs/captcha/client-side-usage.mdx@@ -42,13 +42,13 @@ After the CAPTCHA loader script is loaded, it will add a `window.swetrixCaptchaFYou can customise the appearance of the CAPTCHA widget by adding the following attributes to the `.swecaptcha` element:-| Attribute | Type | Description |-| -------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `data-project-id` | string | The ID of your CAPTCHA project (REQUIRED). |-| `data-theme` | string | The theme of the CAPTCHA widget. Possible values: `auto` (default), `light`, `dark`. |-| `data-response-input-name` | string | Name of the token input element. Default: `swetrix-captcha-response`. |+| Attribute | Type | Description |+| -------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `data-project-id` | string | The ID of your CAPTCHA project (REQUIRED). |+| `data-theme` | string | The theme of the CAPTCHA widget. Possible values: `auto` (default), `light`, `dark`. |+| `data-response-input-name` | string | Name of the token input element. Default: `swetrix-captcha-response`. || `data-api-url` | string | The URL of the CAPTCHA API. Default: `https://api.swetrixcaptcha.com/v1/captcha`. If you're self-hosting Swetrix CE, you should put the URL of your API instance here, like `[BASE_URL]/backend/v1/captcha`. Swetrix Cloud users should leave it as is. |-| `data-lang` | string | Force a specific language for the widget (see [Language support](#language-support)). |+| `data-lang` | string | Force a specific language for the widget (see [Language support](#language-support)). |### Language supportdiff --git a/docs/content/docs/captcha/introduction.mdx b/docs/content/docs/captcha/introduction.mdxindex b7d0b325f..8d97be40a 100644--- a/docs/content/docs/captcha/introduction.mdx+++ b/docs/content/docs/captcha/introduction.mdx@@ -10,22 +10,23 @@ Swetrix CAPTCHA is a fully open source, cookieless, and privacy-friendly CAPTCHAUnlike traditional CAPTCHAs that require users to identify objects in images or solve puzzles, Swetrix CAPTCHA uses a **Proof of Work (PoW)** mechanism.<Steps>-<Step>-### Challenge Request-When a user interacts with a protected form, the client requests a challenge from the Swetrix server.-</Step>-<Step>-### PoW Calculation-The client-side script performs a cryptographic calculation (Proof of Work) in the background. This requires a small amount of computational power from the user's device, which is trivial for a legitimate user but computationally expensive for bots trying to spam at scale.-</Step>-<Step>-### Verification-The solution to the PoW challenge is sent back to the server for verification.-</Step>+ <Step>+ ### Challenge Request When a user interacts with a protected form, the client requests a+ challenge from the Swetrix server.+ </Step>+ <Step>+ ### PoW Calculation The client-side script performs a cryptographic calculation (Proof of Work)+ in the background. This requires a small amount of computational power from the user's device,+ which is trivial for a legitimate user but computationally expensive for bots trying to spam at+ scale.+ </Step>+ <Step>+ ### Verification The solution to the PoW challenge is sent back to the server for verification.+ </Step></Steps>This approach provides a seamless user experience (no more "select all traffic lights") while effectively deterring automated bots.<Callout type="info">-You can find the demonstration of the CAPTCHA widget [here](https://captcha.swetrix.com/demo).+ You can find the demonstration of the CAPTCHA widget [here](https://captcha.swetrix.com/demo).</Callout>diff --git a/docs/content/docs/captcha/meta.json b/docs/content/docs/captcha/meta.jsonindex 1856fcfca..cd425634b 100644--- a/docs/content/docs/captcha/meta.json+++ b/docs/content/docs/captcha/meta.json@@ -1,10 +1,5 @@{"title": "CAPTCHA","root": true,- "pages": [- "introduction",- "client-side-usage",- "server-side-validation",- "testing"- ]+ "pages": ["introduction", "client-side-usage", "server-side-validation", "testing"]}diff --git a/docs/content/docs/captcha/server-side-validation.mdx b/docs/content/docs/captcha/server-side-validation.mdxindex d8d740bda..28d51577b 100644--- a/docs/content/docs/captcha/server-side-validation.mdx+++ b/docs/content/docs/captcha/server-side-validation.mdx@@ -9,7 +9,6 @@ You have to validate the user's response to the CAPTCHA on your server. The tokeThe validation endpoint accepts the CAPTHCA token and your project-specific secret key and returns a JSON response with the validation result.-<Callout type="info">Token validation can only be performed once, if you try to validate the same token twice, the second validation will fail. This is done to prevent token reuse attacks.@@ -80,17 +79,17 @@ The package exports a single function `validateToken` which takes arguments listHere's an example of how to use the package in your project:```js-const { validateToken } = require('@swetrix/captcha-validator')+const { validateToken } = require("@swetrix/captcha-validator");// or-import { validateToken } from '@swetrix/captcha-validator'+import { validateToken } from "@swetrix/captcha-validator";// somewhere inside the controller of your form where the CAPTCHA is used-validateToken('CAPTCHA_TOKEN', 'YOUR_SECRET_KEY').then((result) => {- const [status, data] = result+validateToken("CAPTCHA_TOKEN", "YOUR_SECRET_KEY").then((result) => {+ const [status, data] = result;// status is a boolean, true if the token is valid, false otherwise// data is an error message if status is false- console.log(status, data)-})+ console.log(status, data);+});```</Tab>diff --git a/docs/content/docs/contribute/how-to.mdx b/docs/content/docs/contribute/how-to.mdxindex 067fa5754..85f8219f5 100644--- a/docs/content/docs/contribute/how-to.mdx+++ b/docs/content/docs/contribute/how-to.mdx@@ -14,5 +14,6 @@ Here are some ways you can contribute to the project:- Report a bug to [Report](https://github.com/Swetrix/roadmap/issues) or make a feature request on our Github issues page. We are always open to your ideas and suggestions.<Callout type="info">-All Swetrix repositories are open source and available on [GitHub](https://github.com/Swetrix). We welcome contributions of all kinds — from code to translations to documentation.+ All Swetrix repositories are open source and available on [GitHub](https://github.com/Swetrix). We+ welcome contributions of all kinds — from code to translations to documentation.</Callout>diff --git a/docs/content/docs/contribute/meta.json b/docs/content/docs/contribute/meta.jsonindex 6f9ac5202..8bf81e63c 100644--- a/docs/content/docs/contribute/meta.json+++ b/docs/content/docs/contribute/meta.json@@ -1,6 +1,4 @@{"title": "Contribute",- "pages": [- "how-to"- ]+ "pages": ["how-to"]}diff --git a/docs/content/docs/error-tracking.mdx b/docs/content/docs/error-tracking.mdxindex 2e0566e67..6af2f1801 100644--- a/docs/content/docs/error-tracking.mdx+++ b/docs/content/docs/error-tracking.mdx@@ -8,5 +8,6 @@ As well as providing you with regular data insights such as traffic or site speeThis allows you to track when, on which pages and what kind of errors your users are experiencing. The error tracking script is included in swetrix.js by default and can be easily enabled with a [one line of code](/swetrix-js-reference#trackerrors).<Callout type="info">-Error tracking is included in all plans and is charged as 1 error event = 1 regular event (like a pageview or custom event).+ Error tracking is included in all plans and is charged as 1 error event = 1 regular event (like a+ pageview or custom event).</Callout>diff --git a/docs/content/docs/integrations/angular.mdx b/docs/content/docs/integrations/angular.mdxindex fb1dafe94..31135bdc3 100644--- a/docs/content/docs/integrations/angular.mdx+++ b/docs/content/docs/integrations/angular.mdx@@ -20,22 +20,21 @@ If your app doesn't use the Angular Router, you can initialise Swetrix once in yOpen `src/app/app.component.ts`:```typescript-import { Component, OnInit } from '@angular/core'-import * as Swetrix from 'swetrix'+import { Component, OnInit } from "@angular/core";+import * as Swetrix from "swetrix";@Component({- selector: 'app-root',- templateUrl: './app.component.html',+ selector: "app-root",+ templateUrl: "./app.component.html",})export class AppComponent implements OnInit {ngOnInit() {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();}}```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -77,7 +76,7 @@ By default, Swetrix ignores `localhost` traffic. You can also explicitly disableexport const environment = {production: true,swetrixDisabled: false,-}+};````src/environments/environment.development.ts`:@@ -86,28 +85,27 @@ export const environment = {export const environment = {production: false,swetrixDisabled: true,-}+};```**2. Use it during initialisation**```typescript-import { environment } from '../environments/environment'-import * as Swetrix from 'swetrix'+import { environment } from "../environments/environment";+import * as Swetrix from "swetrix";-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {disabled: environment.swetrixDisabled,-})+});```-<Callout type="info">If you want to verify tracking locally during development, set `devMode: true` instead:```typescript-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {devMode: true,-})+});```Remember to remove this before deploying to production.@@ -141,21 +139,21 @@ Custom events let you track specific user interactions — button clicks, form s### Example: tracking button clicks```typescript-import { Component } from '@angular/core'-import * as Swetrix from 'swetrix'+import { Component } from "@angular/core";+import * as Swetrix from "swetrix";@Component({- selector: 'app-signup-button',+ selector: "app-signup-button",template: '<button (click)="onClick()">Sign up</button>',})export class SignUpButtonComponent {onClick() {Swetrix.track({- ev: 'SIGNUP_CTA_CLICK',+ ev: "SIGNUP_CTA_CLICK",meta: {- location: 'navbar',+ location: "navbar",},- })+ });}}```@@ -163,11 +161,11 @@ export class SignUpButtonComponent {### Example: tracking form submissions```typescript-import { Component } from '@angular/core'-import * as Swetrix from 'swetrix'+import { Component } from "@angular/core";+import * as Swetrix from "swetrix";@Component({- selector: 'app-contact-form',+ selector: "app-contact-form",template: `<form (ngSubmit)="onSubmit()"><input type="email" placeholder="[email protected]" required />@@ -179,11 +177,11 @@ import * as Swetrix from 'swetrix'export class ContactFormComponent {onSubmit() {Swetrix.track({- ev: 'CONTACT_FORM_SUBMITTED',+ ev: "CONTACT_FORM_SUBMITTED",meta: {- source: 'support_page',+ source: "support_page",},- })+ });// ...submit logic}@@ -195,19 +193,19 @@ export class ContactFormComponent {Create a reusable directive for external links:```typescript-import { Directive, HostListener, Input } from '@angular/core'-import * as Swetrix from 'swetrix'+import { Directive, HostListener, Input } from "@angular/core";+import * as Swetrix from "swetrix";-@Directive({ selector: 'a[appTrackOutbound]' })+@Directive({ selector: "a[appTrackOutbound]" })export class TrackOutboundDirective {- @Input() appTrackOutbound = 'OUTBOUND_CLICK'+ @Input() appTrackOutbound = "OUTBOUND_CLICK";- @HostListener('click', ['$event.target'])+ @HostListener("click", ["$event.target"])onClick(target: HTMLAnchorElement) {Swetrix.track({ev: this.appTrackOutbound,meta: { url: target.href },- })+ });}}```@@ -243,17 +241,17 @@ Rather than hardcoding your Project ID, you can store it in Angular's environmen```typescriptexport const environment = {production: true,- swetrixPid: 'YOUR_PROJECT_ID',-}+ swetrixPid: "YOUR_PROJECT_ID",+};```**2. Use it in your analytics service:**```typescript-import { environment } from '../../environments/environment'-import * as Swetrix from 'swetrix'+import { environment } from "../../environments/environment";+import * as Swetrix from "swetrix";-Swetrix.init(environment.swetrixPid)+Swetrix.init(environment.swetrixPid);```## Further readingdiff --git a/docs/content/docs/integrations/aspnet.mdx b/docs/content/docs/integrations/aspnet.mdxindex 4c131aa7c..4de0f353b 100644--- a/docs/content/docs/integrations/aspnet.mdx+++ b/docs/content/docs/integrations/aspnet.mdx@@ -20,23 +20,23 @@ Open your shared layout file — typically `Views/Shared/_Layout.cshtml` (MVC) o```html<!DOCTYPE html><html lang="en">-<head>+ <head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>@ViewData["Title"] - My App</title><!-- Swetrix Analytics --><script src="https://swetrix.org/swetrix.js" defer></script>-</head>-<body>+ </head>+ <body>@RenderBody()<!-- Swetrix Analytics --><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -48,11 +48,10 @@ Open your shared layout file — typically `Views/Shared/_Layout.cshtml` (MVC) o</noscript>@await RenderSectionAsync("Scripts", required: false)-</body>+ </body></html>```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -64,7 +63,7 @@ Wrap the snippets in an environment check so they only load in production:```html<environment include="Production">- <script src="https://swetrix.org/swetrix.js" defer></script>+ <script src="https://swetrix.org/swetrix.js" defer></script></environment>```@@ -72,31 +71,30 @@ And for the body initialisation:```html<environment include="Production">- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })- </script>-- <noscript>- <img- src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"- alt=""- referrerpolicy="no-referrer-when-downgrade"- />- </noscript>+ <script>+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });+ </script>++ <noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+ </noscript></environment>```The `<environment>` tag helper is built into ASP.NET Core and reads from the `ASPNETCORE_ENVIRONMENT` variable.-<Callout type="info">During development, Swetrix ignores `localhost` traffic by default. If you want to verify tracking locally without changing your environment, you can temporarily set `devMode: true`:```js-swetrix.init('YOUR_PROJECT_ID', { devMode: true })+swetrix.init("YOUR_PROJECT_ID", { devMode: true });```Remember to remove this before deploying.@@ -112,7 +110,7 @@ Open `Views/Shared/_Layout.cshtml` and add the Swetrix script:```html<!DOCTYPE html><html>-<head>+ <head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>@ViewBag.Title - My App</title>@@ -120,16 +118,16 @@ Open `Views/Shared/_Layout.cshtml` and add the Swetrix script:<!-- Swetrix Analytics --><script src="https://swetrix.org/swetrix.js" defer></script>-</head>-<body>+ </head>+ <body>@RenderBody()<!-- Swetrix Analytics --><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -140,9 +138,8 @@ Open `Views/Shared/_Layout.cshtml` and add the Swetrix script:/></noscript>- @Scripts.Render("~/bundles/jquery")- @RenderSection("scripts", required: false)-</body>+ @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false)+ </body></html>```@@ -151,31 +148,29 @@ Open `Views/Shared/_Layout.cshtml` and add the Swetrix script:ASP.NET Framework doesn't have a built-in `<environment>` tag helper. Use a conditional check in Razor instead:```html-@if (!HttpContext.Current.IsDebuggingEnabled)-{- <script src="https://swetrix.org/swetrix.js" defer></script>+@if (!HttpContext.Current.IsDebuggingEnabled) {+<script src="https://swetrix.org/swetrix.js" defer></script>}```And for the body initialisation:```html-@if (!HttpContext.Current.IsDebuggingEnabled)-{- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })- </script>+@if (!HttpContext.Current.IsDebuggingEnabled) {+<script>+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });+</script>- <noscript>- <img- src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"- alt=""- referrerpolicy="no-referrer-when-downgrade"- />- </noscript>+<noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+</noscript>}```@@ -241,10 +236,10 @@ export Swetrix__ProjectId=YOUR_PROJECT_ID```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('@System.Configuration.ConfigurationManager.AppSettings["Swetrix:ProjectId"]')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init('@System.Configuration.ConfigurationManager.AppSettings["Swetrix:ProjectId"]');+ swetrix.trackViews();+ });</script>```@@ -258,11 +253,11 @@ Enable automatic client-side error monitoring by adding `trackErrors()` to the i```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- swetrix.trackErrors()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ swetrix.trackErrors();+ });</script>```@@ -278,21 +273,21 @@ Track when users submit a contact form:```html<form id="contact-form" method="post" asp-action="Contact">- <!-- form fields -->- <button type="submit">Send message</button>+ <!-- form fields -->+ <button type="submit">Send message</button></form><script>- document.getElementById('contact-form')?.addEventListener('submit', function () {- if (typeof swetrix !== 'undefined') {+ document.getElementById("contact-form")?.addEventListener("submit", function () {+ if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'CONTACT_FORM_SUBMITTED',+ ev: "CONTACT_FORM_SUBMITTED",meta: {page: window.location.pathname,},- })+ });}- })+ });</script>```@@ -302,20 +297,20 @@ Track clicks on external links across your site. Add this to your layout file:```html<script>- document.addEventListener('DOMContentLoaded', function () {+ document.addEventListener("DOMContentLoaded", function () {document.querySelectorAll('a[href^="http"]').forEach(function (link) {if (link.hostname !== window.location.hostname) {- link.addEventListener('click', function () {- if (typeof swetrix !== 'undefined') {+ link.addEventListener("click", function () {+ if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'OUTBOUND_CLICK',+ ev: "OUTBOUND_CLICK",meta: { url: link.href },- })+ });}- })+ });}- })- })+ });+ });</script>```@@ -336,18 +331,18 @@ For Blazor apps that render on the server, add the Swetrix script to your host p```html<head>- <!-- other head content -->- <script src="https://swetrix.org/swetrix.js" defer></script>+ <!-- other head content -->+ <script src="https://swetrix.org/swetrix.js" defer></script></head><body>- <!-- Blazor root component -->+ <!-- Blazor root component -->- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })- </script>+ <script>+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });+ </script></body>```@@ -359,18 +354,18 @@ For standalone Blazor WASM apps, add the script to `wwwroot/index.html`:```html<head>- <script src="https://swetrix.org/swetrix.js" defer></script>+ <script src="https://swetrix.org/swetrix.js" defer></script></head><body>- <div id="app">Loading...</div>+ <div id="app">Loading...</div>- <script src="_framework/blazor.webassembly.js"></script>- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })- </script>+ <script src="_framework/blazor.webassembly.js"></script>+ <script>+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });+ </script></body>```@@ -512,7 +507,6 @@ Register the middleware in `Program.cs`:app.UseMiddleware<SwetrixMiddleware>();```-<Callout type="info">By using fire-and-forget (`_ = ...`), the analytics call runs in the background without adding latency to your responses. This is the recommended pattern for production.@@ -585,9 +579,9 @@ If you're self-hosting the [Swetrix API](https://github.com/Swetrix/swetrix-api)**Client-side:**```js-swetrix.init('YOUR_PROJECT_ID', {- apiURL: 'https://your-swetrix-instance.com/log',-})+swetrix.init("YOUR_PROJECT_ID", {+ apiURL: "https://your-swetrix-instance.com/log",+});```**Server-side:**diff --git a/docs/content/docs/integrations/astro.mdx b/docs/content/docs/integrations/astro.mdxindex 209dc37aa..8f4c296a1 100644--- a/docs/content/docs/integrations/astro.mdx+++ b/docs/content/docs/integrations/astro.mdx@@ -11,9 +11,9 @@ Astro is a web framework designed for content-rich websites that ships minimal JThere are two ways to add Swetrix to your Astro site:-| Approach | Best for |-| --- | --- |-| **CDN script** | Simple sites, blogs, and documentation — no build-time dependency required |+| Approach | Best for |+| --------------- | ----------------------------------------------------------------------------------------------- |+| **CDN script** | Simple sites, blogs, and documentation — no build-time dependency required || **npm package** | Full TypeScript support, tighter integration with island components, more configuration options |<Tabs items={["CDN script (recommended)", "npm package"]}>@@ -32,6 +32,7 @@ export interface Props {const { title } = Astro.props;---+<!doctype html><html lang="en"><head>@@ -42,10 +43,10 @@ const { title } = Astro.props;<!-- Swetrix Analytics --><script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script></head><body>@@ -54,7 +55,6 @@ const { title } = Astro.props;</html>```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -91,11 +91,12 @@ npm install swetrixCreate `src/scripts/analytics.ts`:```typescript-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";-Swetrix.init('YOUR_PROJECT_ID')-Swetrix.trackViews()+Swetrix.init("YOUR_PROJECT_ID");+Swetrix.trackViews();```+</Step><Step>### Include it in your layout@@ -111,6 +112,7 @@ export interface Props {const { title } = Astro.props;---+<!doctype html><html lang="en"><head>@@ -121,24 +123,23 @@ const { title } = Astro.props;<body><slot /><script>- import * as Swetrix from 'swetrix'+ import * as Swetrix from "swetrix";- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();</script></body></html>```+</Step></Steps>-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.</Callout>-<Callout type="info">Astro processes `<script>` tags — they're bundled and deduplicated automatically. The script above will only be included once in the final build, even if the layout is used on every page.@@ -192,12 +193,12 @@ Wrap the initialisation in a host check:```html<script>- document.addEventListener('DOMContentLoaded', function () {- var isDev = window.location.hostname === 'localhost'+ document.addEventListener("DOMContentLoaded", function () {+ var isDev = window.location.hostname === "localhost";- swetrix.init('YOUR_PROJECT_ID', { disabled: isDev })- swetrix.trackViews()- })+ swetrix.init("YOUR_PROJECT_ID", { disabled: isDev });+ swetrix.trackViews();+ });</script>```@@ -207,25 +208,24 @@ Wrap the initialisation in a host check:Use `import.meta.env`:```typescript-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {disabled: import.meta.env.DEV,-})-Swetrix.trackViews()+});+Swetrix.trackViews();```</Tab></Tabs>-<Callout type="info">If you want to verify tracking locally during development, set `devMode: true` instead:```typescript-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {devMode: true,-})+});```Remember to remove this before deploying to production.@@ -245,11 +245,11 @@ Enable automatic client-side error monitoring to capture unhandled JavaScript er```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- swetrix.trackErrors()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ swetrix.trackErrors();+ });</script>```@@ -257,11 +257,11 @@ Enable automatic client-side error monitoring to capture unhandled JavaScript er<Tab value="npm package">```typescript-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";-Swetrix.init('YOUR_PROJECT_ID')-Swetrix.trackViews()-Swetrix.trackErrors()+Swetrix.init("YOUR_PROJECT_ID");+Swetrix.trackViews();+Swetrix.trackErrors();```</Tab>@@ -281,14 +281,15 @@ Use a `<script>` tag with client-side JavaScript to track events from `.astro` c---// src/components/DownloadButton.astro---+<button id="download-btn">Download PDF</button><script>- document.getElementById('download-btn')?.addEventListener('click', () => {+ document.getElementById("download-btn")?.addEventListener("click", () => {if (window.swetrix) {- swetrix.track({ ev: 'PDF_DOWNLOAD' })+ swetrix.track({ ev: "PDF_DOWNLOAD" });}- })+ });</script>```@@ -298,17 +299,18 @@ If you're using the npm package, you can import it directly:---// src/components/DownloadButton.astro---+<button id="download-btn">Download PDF</button><script>- import * as Swetrix from 'swetrix'+ import * as Swetrix from "swetrix";- document.getElementById('download-btn')?.addEventListener('click', () => {+ document.getElementById("download-btn")?.addEventListener("click", () => {Swetrix.track({- ev: 'PDF_DOWNLOAD',- meta: { format: 'pdf' },- })- })+ ev: "PDF_DOWNLOAD",+ meta: { format: "pdf" },+ });+ });</script>```@@ -320,26 +322,26 @@ If you're using [Astro islands](https://docs.astro.build/en/concepts/islands/) w```tsx// src/components/SignUpForm.tsx-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export default function SignUpForm() {const handleSubmit = (e: React.FormEvent) => {- e.preventDefault()+ e.preventDefault();Swetrix.track({- ev: 'SIGNUP_FORM_SUBMITTED',- meta: { source: 'landing_page' },- })+ ev: "SIGNUP_FORM_SUBMITTED",+ meta: { source: "landing_page" },+ });// ...submit logic- }+ };return (<form onSubmit={handleSubmit}><input type="email" placeholder="[email protected]" required /><button type="submit">Sign up</button></form>- )+ );}```@@ -379,10 +381,10 @@ PUBLIC_SWETRIX_PID=YOUR_PROJECT_ID**2. Reference it in your analytics script** (npm package approach):```typescript-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";-Swetrix.init(import.meta.env.PUBLIC_SWETRIX_PID)-Swetrix.trackViews()+Swetrix.init(import.meta.env.PUBLIC_SWETRIX_PID);+Swetrix.trackViews();```Astro requires client-side environment variables to be prefixed with `PUBLIC_`.diff --git a/docs/content/docs/integrations/bigcommerce.mdx b/docs/content/docs/integrations/bigcommerce.mdxindex 13d291457..ca839fbd6 100644--- a/docs/content/docs/integrations/bigcommerce.mdx+++ b/docs/content/docs/integrations/bigcommerce.mdx@@ -19,24 +19,24 @@ BigCommerce's built-in **Script Manager** is the simplest way to add external scFill in the script settings as follows:-| Setting | Value |-| ----------------- | ----------------------- |-| Name | Swetrix Analytics |-| Description | Swetrix tracking script |-| Placement | **Head** |-| Location | **All pages** |-| Script category | **Analytics** |-| Script type | **Script** |+| Setting | Value |+| --------------- | ----------------------- |+| Name | Swetrix Analytics |+| Description | Swetrix tracking script |+| Placement | **Head** |+| Location | **All pages** |+| Script category | **Analytics** |+| Script type | **Script** |In the **Script contents** box, paste:```html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -52,7 +52,6 @@ In the **Script contents** box, paste:Click **Save** to activate the script across your store.-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the Swetrix dashboard, otherwise tracking won't work.@@ -70,7 +69,6 @@ Beyond basic page views, you can track key e-commerce interactions as custom eveYou can view these events and their metadata in the **Custom events** section of your Swetrix dashboard. Refer to the [tracking script reference](/swetrix-js-reference) for full API details.-<Callout>BigCommerce uses [Handlebars templating](https://developer.bigcommerce.com/docs/storefront/stencil/themes/context/handlebars-reference). The `{{double curly brace}}` syntax in the snippets below is processed server-side by BigCommerce to inject dynamic store data — it is not JavaScript template literal syntax.@@ -83,14 +81,14 @@ Track confirmed purchases on the order confirmation page by creating a second sc1. In **Storefront > Script Manager**, click **Create a Script**.2. Configure it with these settings:-| Setting | Value |-| ----------------- | -------------------------- |-| Name | Swetrix Purchase Tracking |-| Description | Tracks completed purchases |-| Placement | **Footer** |-| Location | **Order Confirmation** |-| Script category | **Analytics** |-| Script type | **Script** |+| Setting | Value |+| --------------- | -------------------------- |+| Name | Swetrix Purchase Tracking |+| Description | Tracks completed purchases |+| Placement | **Footer** |+| Location | **Order Confirmation** |+| Script category | **Analytics** |+| Script type | **Script** |3. In the **Script contents** box, paste:@@ -117,7 +115,6 @@ Track confirmed purchases on the order confirmation page by creating a second scThe `{{#if checkout.order}}` Handlebars block ensures the event only fires when valid order data is present.-<Callout type="info">Test by placing a small test order and checking the **Custom events** section in your Swetrix dashboard. You should see a `purchase` event with the order metadata.diff --git a/docs/content/docs/integrations/bubble.mdx b/docs/content/docs/integrations/bubble.mdxindex 157be77f5..34d553d40 100644--- a/docs/content/docs/integrations/bubble.mdx+++ b/docs/content/docs/integrations/bubble.mdx@@ -22,10 +22,10 @@ Scroll down to **Script/meta tags in header** and paste the following snippet. T```html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -37,7 +37,6 @@ Scroll down to **Script/meta tags in header** and paste the following snippet. T</noscript>```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -65,10 +64,10 @@ There are a few scenarios to be aware of:```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews({ hash: true })- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews({ hash: true });+ });</script>```@@ -77,12 +76,12 @@ There are a few scenarios to be aware of:If your Bubble app navigates between views without changing the URL, you can fire a pageview manually when a group becomes visible. Use a **Run JavaScript** workflow action:```javascript-if (typeof swetrix !== 'undefined') {+if (typeof swetrix !== "undefined") {swetrix.pageview({payload: {- pg: '/your-virtual-page',+ pg: "/your-virtual-page",},- })+ });}```@@ -95,11 +94,11 @@ Enable automatic client-side error monitoring by adding `trackErrors()` to the i```html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- swetrix.trackErrors()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ swetrix.trackErrors();+ });</script>```@@ -124,10 +123,10 @@ Bubble doesn't include a built-in JavaScript action by default. You need the fre3. Add a **Run JavaScript** action and paste your tracking code:```javascript-if (typeof swetrix !== 'undefined') {+if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'SIGNUP_CLICKED',- })+ ev: "SIGNUP_CLICKED",+ });}```@@ -136,20 +135,19 @@ if (typeof swetrix !== 'undefined') {Bubble lets you insert dynamic expressions into the JavaScript action. You can use this to attach contextual metadata:```javascript-if (typeof swetrix !== 'undefined') {+if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'ITEM_ADDED_TO_CART',+ ev: "ITEM_ADDED_TO_CART",meta: {- item_name: 'DYNAMIC_ITEM_NAME',- category: 'DYNAMIC_CATEGORY',+ item_name: "DYNAMIC_ITEM_NAME",+ category: "DYNAMIC_CATEGORY",},- })+ });}```Replace the placeholder strings with Bubble's **Insert dynamic data** feature inside the Run JavaScript editor — Bubble will substitute them with actual values at runtime.-<Callout type="info">You can pass up to 20 metadata keys per event. Values are converted to strings and the combined length of all values must be under 1,000 characters. See the [tracking script reference](/swetrix-js-reference#track) for full details.@@ -167,27 +165,27 @@ We recommend `UPPER_SNAKE_CASE` for consistency (e.g. `SIGNUP_CLICKED`, `ITEM_AD### Example: tracking a form submission```javascript-if (typeof swetrix !== 'undefined') {+if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'CONTACT_FORM_SUBMITTED',+ ev: "CONTACT_FORM_SUBMITTED",meta: {page: window.location.pathname,},- })+ });}```### Example: tracking a purchase```javascript-if (typeof swetrix !== 'undefined') {+if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'PURCHASE_COMPLETED',+ ev: "PURCHASE_COMPLETED",meta: {- plan: 'DYNAMIC_PLAN_NAME',- price: 'DYNAMIC_PRICE',+ plan: "DYNAMIC_PLAN_NAME",+ price: "DYNAMIC_PRICE",},- })+ });}```diff --git a/docs/content/docs/integrations/carrd.mdx b/docs/content/docs/integrations/carrd.mdxindex 6812b294d..8a3d13b31 100644--- a/docs/content/docs/integrations/carrd.mdx+++ b/docs/content/docs/integrations/carrd.mdx@@ -24,15 +24,15 @@ Adding custom code to a Carrd site requires a **Pro** subscription (Pro Standard```html<script>(function () {- var s = document.createElement('script')- s.src = 'https://swetrix.org/swetrix.js'- s.defer = true+ var s = document.createElement("script");+ s.src = "https://swetrix.org/swetrix.js";+ s.defer = true;s.onload = function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- }- document.head.appendChild(s)- })()+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ };+ document.head.appendChild(s);+ })();</script><noscript>@@ -50,7 +50,6 @@ We use the JavaScript approach (dynamically creating the script element) insteadClick **Save**, then **Publish** to apply the changes to your live site.-<Callout type="warn">Don't forget to replace `YOUR_PROJECT_ID` with your actual Project ID from the Swetrix dashboard, otherwise tracking won't work.@@ -60,7 +59,6 @@ Don't forget to replace `YOUR_PROJECT_ID` with your actual Project ID from the SOpen your published Carrd site in a new tab (or an incognito window). Within a minute you should see a pageview appear in your Swetrix dashboard.-<Callout type="info">The tracking script only runs on your published site. You won't see analytics data while previewing inside the Carrd editor.@@ -76,14 +74,14 @@ You can use `swetrix.track()` to capture custom interactions such as button clic```html<script>- document.addEventListener('DOMContentLoaded', function () {- var form = document.querySelector('form')- if (!form || typeof swetrix === 'undefined') return-- form.addEventListener('submit', function () {- swetrix.track({ ev: 'form_submission' })- })- })+ document.addEventListener("DOMContentLoaded", function () {+ var form = document.querySelector("form");+ if (!form || typeof swetrix === "undefined") return;++ form.addEventListener("submit", function () {+ swetrix.track({ ev: "form_submission" });+ });+ });</script>```diff --git a/docs/content/docs/integrations/django.mdx b/docs/content/docs/integrations/django.mdxindex 96604709e..01af0bbb1 100644--- a/docs/content/docs/integrations/django.mdx+++ b/docs/content/docs/integrations/django.mdx@@ -18,25 +18,25 @@ Django projects typically have a base template that all other templates extend v```html<!DOCTYPE html><html lang="en">-<head>- <meta charset="utf-8">- <meta name="viewport" content="width=device-width, initial-scale=1">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" /><title>{% block title %}My Site{% endblock %}</title>{% block styles %}{% endblock %}<!-- Swetrix Analytics --><script src="https://swetrix.org/swetrix.js" defer></script>-</head>-<body>+ </head>+ <body>{% block content %}{% endblock %}<!-- Swetrix Analytics --><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -48,11 +48,10 @@ Django projects typically have a base template that all other templates extend v</noscript>{% block scripts %}{% endblock %}-</body>+ </body></html>```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -66,7 +65,7 @@ Then wrap the snippets:```html{% if not debug %}- <script src="https://swetrix.org/swetrix.js" defer></script>+<script src="https://swetrix.org/swetrix.js" defer></script>{% endif %}```@@ -74,29 +73,28 @@ And for the body initialisation:```html{% if not debug %}- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })- </script>+<script>+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });+</script>- <noscript>- <img- src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"- alt=""- referrerpolicy="no-referrer-when-downgrade"- />- </noscript>+<noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+</noscript>{% endif %}```-<Callout type="info">During development, Swetrix ignores `localhost` traffic by default. If you want to verify tracking locally without changing your environment, you can temporarily set `devMode: true`:```js-swetrix.init('YOUR_PROJECT_ID', { devMode: true })+swetrix.init("YOUR_PROJECT_ID", { devMode: true });```Remember to remove this before deploying.@@ -146,21 +144,21 @@ TEMPLATES = [```html{% if SWETRIX_PROJECT_ID %}- <script src="https://swetrix.org/swetrix.js" defer></script>- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('{{ SWETRIX_PROJECT_ID }}')- swetrix.trackViews()- })- </script>+<script src="https://swetrix.org/swetrix.js" defer></script>+<script>+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("{{ SWETRIX_PROJECT_ID }}");+ swetrix.trackViews();+ });+</script>- <noscript>- <img- src="https://api.swetrix.com/log/noscript?pid={{ SWETRIX_PROJECT_ID }}"- alt=""- referrerpolicy="no-referrer-when-downgrade"- />- </noscript>+<noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid={{ SWETRIX_PROJECT_ID }}"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+</noscript>{% endif %}```@@ -180,11 +178,11 @@ Enable automatic client-side error monitoring by adding `trackErrors()` to the i```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- swetrix.trackErrors()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ swetrix.trackErrors();+ });</script>```@@ -200,22 +198,21 @@ Track when users submit a contact form:```html<form id="contact-form" method="POST" action="{% url 'contact' %}">- {% csrf_token %}- {{ form.as_p }}- <button type="submit">Send message</button>+ {% csrf_token %} {{ form.as_p }}+ <button type="submit">Send message</button></form><script>- document.getElementById('contact-form')?.addEventListener('submit', function () {- if (typeof swetrix !== 'undefined') {+ document.getElementById("contact-form")?.addEventListener("submit", function () {+ if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'CONTACT_FORM_SUBMITTED',+ ev: "CONTACT_FORM_SUBMITTED",meta: {page: window.location.pathname,},- })+ });}- })+ });</script>```@@ -225,20 +222,20 @@ Track clicks on external links across your site. Add this to your base template:```html<script>- document.addEventListener('DOMContentLoaded', function () {+ document.addEventListener("DOMContentLoaded", function () {document.querySelectorAll('a[href^="http"]').forEach(function (link) {if (link.hostname !== window.location.hostname) {- link.addEventListener('click', function () {- if (typeof swetrix !== 'undefined') {+ link.addEventListener("click", function () {+ if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'OUTBOUND_CLICK',+ ev: "OUTBOUND_CLICK",meta: { url: link.href },- })+ });}- })+ });}- })- })+ });+ });</script>```@@ -258,9 +255,12 @@ If your Django application uses [HTMX](https://htmx.org/) for dynamic page updatIf you use HTMX to swap content without changing the URL and want to track those interactions, use custom events:```html-<button hx-post="/api/subscribe" hx-swap="outerHTML"- onclick="if(typeof swetrix!=='undefined') swetrix.track({ ev: 'SUBSCRIBE_CLICKED' })">- Subscribe+<button+ hx-post="/api/subscribe"+ hx-swap="outerHTML"+ onclick="if(typeof swetrix!=='undefined') swetrix.track({ ev: 'SUBSCRIBE_CLICKED' })"+>+ Subscribe</button>```@@ -273,10 +273,10 @@ npm install swetrix``````javascript-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";-Swetrix.init('YOUR_PROJECT_ID')-Swetrix.trackViews()+Swetrix.init("YOUR_PROJECT_ID");+Swetrix.trackViews();```See the relevant frontend framework integration guide ([React](/react-integration), [Vue](/vue-integration), etc.) for framework-specific details.diff --git a/docs/content/docs/integrations/docusaurus.mdx b/docs/content/docs/integrations/docusaurus.mdxindex 60ad4ee42..5869d02c1 100644--- a/docs/content/docs/integrations/docusaurus.mdx+++ b/docs/content/docs/integrations/docusaurus.mdx@@ -18,15 +18,15 @@ const config = {// ...your existing configscripts: [{- src: 'https://swetrix.org/swetrix.js',+ src: "https://swetrix.org/swetrix.js",defer: true,},{- src: '/js/setupswetrix.js',+ src: "/js/setupswetrix.js",defer: true,},],-}+};```### 2. Create the setup file@@ -34,15 +34,14 @@ const config = {Create a new file at `static/js/setupswetrix.js`:```js-document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()-})+document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+});```That's it — Swetrix will now automatically track page views across your entire site, including client-side navigations.-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -53,7 +52,7 @@ Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboarTo track visitors who have JavaScript disabled, you can add a noscript image pixel. Create or edit `src/theme/Root.js` to wrap your site with the fallback:```jsx-import React from 'react'+import React from "react";export default function Root({ children }) {return (@@ -67,7 +66,7 @@ export default function Root({ children }) {/></noscript></>- )+ );}```@@ -75,14 +74,13 @@ export default function Root({ children }) {After adding the tracking script, start your Docusaurus site and visit a few pages. Within a minute you should see new pageviews appearing in your Swetrix dashboard.-<Callout type="info">During development, pageviews from `localhost` are not sent by default. Set `devMode: true` in the setup file if you want to verify tracking locally:```js-swetrix.init('YOUR_PROJECT_ID', {+swetrix.init("YOUR_PROJECT_ID", {devMode: true,-})+});```Remember to remove this before deploying to production.@@ -96,11 +94,11 @@ You can enable automatic client-side error monitoring by adding `trackErrors()`Update `static/js/setupswetrix.js`:```js-document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- swetrix.trackErrors()-})+document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ swetrix.trackErrors();+});```Errors will appear in the **Errors** tab of your project dashboard. See the [tracking script reference](/swetrix-js-reference#trackerrors) for configuration options like `sampleRate` and `callback`.@@ -117,11 +115,11 @@ const trackEvent = (eventName, metadata = {}) => {window?.swetrix?.track({ev: eventName,meta: metadata,- })+ });} catch (error) {- console.error('Swetrix tracking error:', error)+ console.error("Swetrix tracking error:", error);}-}+};```### Example: tracking button clicks@@ -129,24 +127,24 @@ const trackEvent = (eventName, metadata = {}) => {A simple example — track when users click a CTA button:```jsx-import React from 'react'+import React from "react";export default function SignUpButton() {const handleClick = () => {window?.swetrix?.track({- ev: 'CTA_CLICK',+ ev: "CTA_CLICK",meta: {- label: 'Sign up',- location: 'hero',+ label: "Sign up",+ location: "hero",},- })- }+ });+ };return (<a href="https://swetrix.com/signup" onClick={handleClick}>Get started free</a>- )+ );}```@@ -155,40 +153,40 @@ export default function SignUpButton() {A more practical example — track whether users found a docs page helpful. This is similar to what we use on the Swetrix docs site itself:```jsx-import React, { useState } from 'react'-import { useLocation } from '@docusaurus/router'+import React, { useState } from "react";+import { useLocation } from "@docusaurus/router";export default function DocsFeedback() {- const { pathname } = useLocation()- const [submitted, setSubmitted] = useState(false)+ const { pathname } = useLocation();+ const [submitted, setSubmitted] = useState(false);const sendFeedback = async (answer) => {try {await window?.swetrix?.track({- ev: 'DOCS_FEEDBACK',+ ev: "DOCS_FEEDBACK",meta: {answer,path: pathname,},- })+ });} catch (error) {- console.error('Error tracking feedback:', error)+ console.error("Error tracking feedback:", error);}- setSubmitted(true)- }+ setSubmitted(true);+ };if (submitted) {- return <p>Thank you for your feedback!</p>+ return <p>Thank you for your feedback!</p>;}return (<div><p>Was this page helpful?</p>- <button onClick={() => sendFeedback('Yes')}>Yes</button>- <button onClick={() => sendFeedback('No')}>No</button>+ <button onClick={() => sendFeedback("Yes")}>Yes</button>+ <button onClick={() => sendFeedback("No")}>No</button></div>- )+ );}```@@ -199,37 +197,37 @@ This sends a `DOCS_FEEDBACK` event to Swetrix with the user's answer and the curIf you use Docusaurus's built-in search (e.g. Algolia DocSearch), you can track when users open the search modal:```jsx-import React, { useEffect } from 'react'+import React, { useEffect } from "react";export default function Root({ children }) {useEffect(() => {const handleKeyDown = (event) => {- if ((event.metaKey || event.ctrlKey) && event.key === 'k') {+ if ((event.metaKey || event.ctrlKey) && event.key === "k") {window?.swetrix?.track({- ev: 'SEARCH_OPENED',- meta: { trigger: 'keyboard' },- })+ ev: "SEARCH_OPENED",+ meta: { trigger: "keyboard" },+ });}- }+ };- const searchButton = document.querySelector('.DocSearch-Button')+ const searchButton = document.querySelector(".DocSearch-Button");const handleClick = () => {window?.swetrix?.track({- ev: 'SEARCH_OPENED',- meta: { trigger: 'click' },- })- }+ ev: "SEARCH_OPENED",+ meta: { trigger: "click" },+ });+ };- document.addEventListener('keydown', handleKeyDown)- searchButton?.addEventListener('click', handleClick)+ document.addEventListener("keydown", handleKeyDown);+ searchButton?.addEventListener("click", handleClick);return () => {- document.removeEventListener('keydown', handleKeyDown)- searchButton?.removeEventListener('click', handleClick)- }- }, [])+ document.removeEventListener("keydown", handleKeyDown);+ searchButton?.removeEventListener("click", handleClick);+ };+ }, []);- return <>{children}</>+ return <>{children}</>;}```@@ -238,30 +236,30 @@ export default function Root({ children }) {Track when users click external links in your docs, useful for measuring referral traffic to third-party resources:```jsx-import React from 'react'+import React from "react";-export default function TrackedLink({ href, children, eventName = 'OUTBOUND_CLICK' }) {+export default function TrackedLink({ href, children, eventName = "OUTBOUND_CLICK" }) {const handleClick = () => {window?.swetrix?.track({ev: eventName,meta: {url: href,},- })- }+ });+ };return (<a href={href} target="_blank" rel="noopener noreferrer" onClick={handleClick}>{children}</a>- )+ );}```Usage in MDX:```mdx-import TrackedLink from '@site/src/components/TrackedLink'+import TrackedLink from "@site/src/components/TrackedLink";Check out the <TrackedLink href="https://github.com/Swetrix/swetrix">source code</TrackedLink>.```diff --git a/docs/content/docs/integrations/drupal.mdx b/docs/content/docs/integrations/drupal.mdxindex f027dbb7a..da4dd87a5 100644--- a/docs/content/docs/integrations/drupal.mdx+++ b/docs/content/docs/integrations/drupal.mdx@@ -27,7 +27,6 @@ If your theme doesn't override this template yet, copy it from Drupal core as acore/themes/stable9/templates/layout/html.html.twig```-<Callout type="info">Always use a **custom or sub-theme** for template overrides. Editing a contributed theme directly means your changes will be lost on the next theme update.@@ -40,10 +39,10 @@ Open `html.html.twig` and paste the following just before the closing `</body>````html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -65,7 +64,6 @@ The template usually ends with something like this:Place the Swetrix snippet between the `<js-bottom-placeholder>` line and the `</body>` tag.-<Callout type="warn">Don't forget to replace `YOUR_PROJECT_ID` with your actual Project ID from the Swetrix dashboard, otherwise tracking won't work.@@ -108,21 +106,20 @@ Or download it from [drupal.org/project/asset_injector](https://www.drupal.org/p```javascript(function () {- var s = document.createElement('script')- s.src = 'https://swetrix.org/swetrix.js'- s.defer = true+ var s = document.createElement("script");+ s.src = "https://swetrix.org/swetrix.js";+ s.defer = true;s.onload = function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- }- document.head.appendChild(s)-})()+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ };+ document.head.appendChild(s);+})();```4. Under **Conditions**, leave the pages field empty so the script runs on every page (or restrict it to specific paths if needed).5. Click **Save**.-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the Swetrix dashboard.@@ -156,14 +153,14 @@ Example — tracking a Webform submission:```html<script>- document.addEventListener('DOMContentLoaded', function () {- var form = document.querySelector('.webform-submission-form')- if (!form || typeof swetrix === 'undefined') return-- form.addEventListener('submit', function () {- swetrix.track({ ev: 'webform_submitted' })- })- })+ document.addEventListener("DOMContentLoaded", function () {+ var form = document.querySelector(".webform-submission-form");+ if (!form || typeof swetrix === "undefined") return;++ form.addEventListener("submit", function () {+ swetrix.track({ ev: "webform_submitted" });+ });+ });</script>```diff --git a/docs/content/docs/integrations/eleventy.mdx b/docs/content/docs/integrations/eleventy.mdxindex 66aba6a5d..2914730fe 100644--- a/docs/content/docs/integrations/eleventy.mdx+++ b/docs/content/docs/integrations/eleventy.mdx@@ -32,10 +32,10 @@ Add the Swetrix script just before the closing `</body>` tag:<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -49,7 +49,6 @@ Add the Swetrix script just before the closing `</body>` tag:</html>```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -74,12 +73,12 @@ Or set a default layout for all pages in your Eleventy config (`eleventy.config.module.exports = function (eleventyConfig) {return {dir: {- input: 'src',- includes: '_includes',- output: '_site',+ input: "src",+ includes: "_includes",+ output: "_site",},- }-}+ };+};```Then use [directory-level data files](https://www.11ty.dev/docs/data-template-dir/) to set the layout for an entire folder. For example, create `src/src.json`:@@ -104,8 +103,8 @@ ELEVENTY_ENV=production npx @11ty/eleventy```jsmodule.exports = {- isProd: process.env.ELEVENTY_ENV === 'production',-}+ isProd: process.env.ELEVENTY_ENV === "production",+};```**3. Wrap the tracking script in a conditional** in your layout:@@ -114,10 +113,10 @@ module.exports = {{% if env.isProd %}<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -130,7 +129,6 @@ module.exports = {{% endif %}```-<Callout type="info">By default Swetrix ignores `localhost` traffic, so the environment variable approach is optional. It's useful if you want to avoid loading the script entirely during development.@@ -144,8 +142,8 @@ To keep your Project ID out of template code, store it in a global data file.```jsmodule.exports = {- projectId: process.env.SWETRIX_PID || 'YOUR_PROJECT_ID',-}+ projectId: process.env.SWETRIX_PID || "YOUR_PROJECT_ID",+};```**2. Reference it in your layout:**@@ -153,10 +151,10 @@ module.exports = {```html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('{{ swetrix.projectId }}')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("{{ swetrix.projectId }}");+ swetrix.trackViews();+ });</script><noscript>@@ -180,11 +178,11 @@ Enable automatic client-side error monitoring by adding `trackErrors()` alongsid```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- swetrix.trackErrors()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ swetrix.trackErrors();+ });</script>```@@ -200,14 +198,14 @@ Add event tracking to any page or component using inline scripts:<button id="download-btn">Download PDF</button><script>- document.addEventListener('DOMContentLoaded', function () {- var btn = document.getElementById('download-btn')- if (!btn || typeof swetrix === 'undefined') return-- btn.addEventListener('click', function () {- swetrix.track({ ev: 'PDF_DOWNLOAD' })- })- })+ document.addEventListener("DOMContentLoaded", function () {+ var btn = document.getElementById("download-btn");+ if (!btn || typeof swetrix === "undefined") return;++ btn.addEventListener("click", function () {+ swetrix.track({ ev: "PDF_DOWNLOAD" });+ });+ });</script>```@@ -220,17 +218,17 @@ Add event tracking to any page or component using inline scripts:</form><script>- document.addEventListener('DOMContentLoaded', function () {- var form = document.getElementById('contact-form')- if (!form || typeof swetrix === 'undefined') return+ document.addEventListener("DOMContentLoaded", function () {+ var form = document.getElementById("contact-form");+ if (!form || typeof swetrix === "undefined") return;- form.addEventListener('submit', function () {+ form.addEventListener("submit", function () {swetrix.track({- ev: 'NEWSLETTER_SIGNUP',- meta: { source: 'footer' },- })- })- })+ ev: "NEWSLETTER_SIGNUP",+ meta: { source: "footer" },+ });+ });+ });</script>```@@ -254,10 +252,10 @@ npm install swetrixThen import and use it in your client-side JavaScript:```js-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";-Swetrix.init('YOUR_PROJECT_ID')-Swetrix.trackViews()+Swetrix.init("YOUR_PROJECT_ID");+Swetrix.trackViews();```## Further readingdiff --git a/docs/content/docs/integrations/express.mdx b/docs/content/docs/integrations/express.mdxindex b61b0bf10..32db86049 100644--- a/docs/content/docs/integrations/express.mdx+++ b/docs/content/docs/integrations/express.mdx@@ -18,24 +18,23 @@ npm install @swetrix/nodeInitialise the Swetrix client with your Project ID:```javascript-const express = require('express')-const { Swetrix } = require('@swetrix/node')+const express = require("express");+const { Swetrix } = require("@swetrix/node");-const app = express()-const swetrix = new Swetrix('YOUR_PROJECT_ID')+const app = express();+const swetrix = new Swetrix("YOUR_PROJECT_ID");```Or using ES module syntax:```javascript-import express from 'express'-import { Swetrix } from '@swetrix/node'+import express from "express";+import { Swetrix } from "@swetrix/node";-const app = express()-const swetrix = new Swetrix('YOUR_PROJECT_ID')+const app = express();+const swetrix = new Swetrix("YOUR_PROJECT_ID");```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -44,20 +43,20 @@ Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboarThe `Swetrix` constructor accepts an optional second argument — an options object:```javascript-const swetrix = new Swetrix('YOUR_PROJECT_ID', {+const swetrix = new Swetrix("YOUR_PROJECT_ID", {devMode: false,- disabled: process.env.NODE_ENV !== 'production',+ disabled: process.env.NODE_ENV !== "production",apiURL: undefined, // only needed for self-hosted Swetrix-})+});```-| Option | Type | Description |-| --- | --- | --- |-| `devMode` | `boolean` | When `true`, all tracking logs are printed to the console |-| `disabled` | `boolean` | When `true`, no data is sent to the server — useful for development |-| `apiURL` | `string` | Custom API server URL (for self-hosted Swetrix) |-| `unique` | `boolean` | When `true`, only unique events are saved |-| `profileId` | `string` | Optional profile ID for long-term user tracking |+| Option | Type | Description |+| ----------- | --------- | ------------------------------------------------------------------- |+| `devMode` | `boolean` | When `true`, all tracking logs are printed to the console |+| `disabled` | `boolean` | When `true`, no data is sent to the server — useful for development |+| `apiURL` | `string` | Custom API server URL (for self-hosted Swetrix) |+| `unique` | `boolean` | When `true`, only unique events are saved |+| `profileId` | `string` | Optional profile ID for long-term user tracking |## Tracking pageviews@@ -66,18 +65,18 @@ To track pageviews you need to pass the visitor's **IP address** and **User-Agen### Basic example```javascript-app.get('/', async (req, res) => {- const ip = req.ip- const userAgent = req.headers['user-agent']+app.get("/", async (req, res) => {+ const ip = req.ip;+ const userAgent = req.headers["user-agent"];await swetrix.trackPageView(ip, userAgent, {- pg: '/',- lc: req.headers['accept-language']?.split(',')[0],- ref: req.headers['referer'],- })+ pg: "/",+ lc: req.headers["accept-language"]?.split(",")[0],+ ref: req.headers["referer"],+ });- res.send('Hello World')-})+ res.send("Hello World");+});```### Middleware approach (recommended)@@ -86,21 +85,20 @@ For most applications, you'll want to track pageviews on every request. A middle```javascriptapp.use(async (req, res, next) => {- const ip = req.ip- const userAgent = req.headers['user-agent']+ const ip = req.ip;+ const userAgent = req.headers["user-agent"];// Fire-and-forget — don't block the responseswetrix.trackPageView(ip, userAgent, {pg: req.path,- lc: req.headers['accept-language']?.split(',')[0],- ref: req.headers['referer'],- })+ lc: req.headers["accept-language"]?.split(",")[0],+ ref: req.headers["referer"],+ });- next()-})+ next();+});```-<Callout type="info">By not awaiting `trackPageView`, analytics calls happen in the background without adding latency to your responses. This is the recommended pattern for production.@@ -109,43 +107,43 @@ By not awaiting `trackPageView`, analytics calls happen in the background withouIf your Express app runs behind a reverse proxy (e.g. Nginx, Cloudflare, or a load balancer), make sure to configure the [`trust proxy`](https://expressjs.com/en/guide/behind-proxies.html) setting so `req.ip` returns the real client IP:```javascript-app.set('trust proxy', true)+app.set("trust proxy", true);```### Pageview optionsThe third argument to `trackPageView` is an options object:-| Option | Type | Description |-| --- | --- | --- |-| `pg` | `string` | Page path (e.g. `/home`) |-| `lc` | `string` | Visitor locale (e.g. `en-US`) |-| `ref` | `string` | Referrer URL |-| `so` | `string` | Traffic source (e.g. `utm_source`) |-| `me` | `string` | Traffic medium (e.g. `utm_medium`) |-| `ca` | `string` | Campaign (e.g. `utm_campaign`) |-| `unique` | `boolean` | Only save unique visits |-| `meta` | `object` | Custom metadata key-value pairs |+| Option | Type | Description |+| -------- | --------- | ---------------------------------- |+| `pg` | `string` | Page path (e.g. `/home`) |+| `lc` | `string` | Visitor locale (e.g. `en-US`) |+| `ref` | `string` | Referrer URL |+| `so` | `string` | Traffic source (e.g. `utm_source`) |+| `me` | `string` | Traffic medium (e.g. `utm_medium`) |+| `ca` | `string` | Campaign (e.g. `utm_campaign`) |+| `unique` | `boolean` | Only save unique visits |+| `meta` | `object` | Custom metadata key-value pairs |## Tracking custom eventsTrack specific actions — API calls, form submissions, purchases, etc.:```javascript-app.post('/api/subscribe', async (req, res) => {- const ip = req.ip- const userAgent = req.headers['user-agent']+app.post("/api/subscribe", async (req, res) => {+ const ip = req.ip;+ const userAgent = req.headers["user-agent"];swetrix.track(ip, userAgent, {- ev: 'NEWSLETTER_SUBSCRIBE',- page: '/subscribe',+ ev: "NEWSLETTER_SUBSCRIBE",+ page: "/subscribe",meta: {plan: req.body.plan,},- })+ });- res.json({ success: true })-})+ res.json({ success: true });+});```### Event naming rules@@ -163,38 +161,38 @@ Report server-side errors to Swetrix for centralised monitoring:```javascriptapp.use((err, req, res, next) => {- const ip = req.ip- const userAgent = req.headers['user-agent']+ const ip = req.ip;+ const userAgent = req.headers["user-agent"];swetrix.trackError(ip, userAgent, {- name: err.name || 'Error',+ name: err.name || "Error",message: err.message,stackTrace: err.stack,pg: req.path,- })+ });- res.status(500).json({ error: 'Internal Server Error' })-})+ res.status(500).json({ error: "Internal Server Error" });+});```You can also track errors from specific routes:```javascript-app.get('/api/data', async (req, res) => {+app.get("/api/data", async (req, res) => {try {- const data = await fetchExternalData()- res.json(data)+ const data = await fetchExternalData();+ res.json(data);} catch (err) {- swetrix.trackError(req.ip, req.headers['user-agent'], {+ swetrix.trackError(req.ip, req.headers["user-agent"], {name: err.name,message: err.message,stackTrace: err.stack,pg: req.path,- })+ });- res.status(500).json({ error: 'Failed to fetch data' })+ res.status(500).json({ error: "Failed to fetch data" });}-})+});```## Heartbeat events@@ -203,18 +201,18 @@ Heartbeat events let Swetrix know a visitor's session is still active, powering```javascript// Example: send heartbeats for active WebSocket connections-const HEARTBEAT_INTERVAL = 30_000+const HEARTBEAT_INTERVAL = 30_000;-wss.on('connection', (ws, req) => {- const ip = req.socket.remoteAddress- const userAgent = req.headers['user-agent']+wss.on("connection", (ws, req) => {+ const ip = req.socket.remoteAddress;+ const userAgent = req.headers["user-agent"];const interval = setInterval(() => {- swetrix.heartbeat(ip, userAgent)- }, HEARTBEAT_INTERVAL)+ swetrix.heartbeat(ip, userAgent);+ }, HEARTBEAT_INTERVAL);- ws.on('close', () => clearInterval(interval))-})+ ws.on("close", () => clearInterval(interval));+});```## Feature flags@@ -222,32 +220,32 @@ wss.on('connection', (ws, req) => {Evaluate feature flags server-side based on visitor context:```javascript-app.get('/dashboard', async (req, res) => {- const ip = req.ip- const userAgent = req.headers['user-agent']+app.get("/dashboard", async (req, res) => {+ const ip = req.ip;+ const userAgent = req.headers["user-agent"];const showNewDashboard = await swetrix.getFeatureFlag(- 'new-dashboard',+ "new-dashboard",ip,userAgent,{ profileId: req.user?.id },false, // default value- )+ );if (showNewDashboard) {- res.render('dashboard-v2')+ res.render("dashboard-v2");} else {- res.render('dashboard')+ res.render("dashboard");}-})+});```You can also fetch all flags at once:```javascript-const flags = await swetrix.getFeatureFlags(ip, userAgent)+const flags = await swetrix.getFeatureFlags(ip, userAgent);-if (flags['beta-feature']) {+if (flags["beta-feature"]) {// Enable beta feature}```@@ -255,7 +253,7 @@ if (flags['beta-feature']) {Feature flags are cached for 5 minutes. To force a refresh:```javascript-swetrix.clearFeatureFlagsCache()+swetrix.clearFeatureFlagsCache();```## A/B testing (experiments)@@ -263,24 +261,24 @@ swetrix.clearFeatureFlagsCache()Run server-side A/B tests and get the assigned variant for each visitor:```javascript-app.get('/pricing', async (req, res) => {- const ip = req.ip- const userAgent = req.headers['user-agent']+app.get("/pricing", async (req, res) => {+ const ip = req.ip;+ const userAgent = req.headers["user-agent"];const variant = await swetrix.getExperiment(- 'pricing-experiment-id',+ "pricing-experiment-id",ip,userAgent,{ profileId: req.user?.id },null, // default variant- )+ );- if (variant === 'annual-first') {- res.render('pricing', { showAnnualFirst: true })+ if (variant === "annual-first") {+ res.render("pricing", { showAnnualFirst: true });} else {- res.render('pricing', { showAnnualFirst: false })+ res.render("pricing", { showAnnualFirst: false });}-})+});```## Revenue attribution@@ -288,14 +286,14 @@ app.get('/pricing', async (req, res) => {Use profile and session IDs to connect analytics with your payment provider (e.g. Paddle, Stripe):```javascript-app.get('/checkout', async (req, res) => {- const ip = req.ip- const userAgent = req.headers['user-agent']+app.get("/checkout", async (req, res) => {+ const ip = req.ip;+ const userAgent = req.headers["user-agent"];const [profileId, sessionId] = await Promise.all([swetrix.getProfileId(ip, userAgent),swetrix.getSessionId(ip, userAgent),- ])+ ]);res.json({checkoutConfig: {@@ -304,8 +302,8 @@ app.get('/checkout', async (req, res) => {swetrix_session_id: sessionId,},},- })-})+ });+});```## Disable tracking in development@@ -313,17 +311,17 @@ app.get('/checkout', async (req, res) => {Use the `disabled` option to prevent tracking during development:```javascript-const swetrix = new Swetrix('YOUR_PROJECT_ID', {- disabled: process.env.NODE_ENV !== 'production',-})+const swetrix = new Swetrix("YOUR_PROJECT_ID", {+ disabled: process.env.NODE_ENV !== "production",+});```Or use `devMode` to log tracking calls to the console without disabling them:```javascript-const swetrix = new Swetrix('YOUR_PROJECT_ID', {- devMode: process.env.NODE_ENV === 'development',-})+const swetrix = new Swetrix("YOUR_PROJECT_ID", {+ devMode: process.env.NODE_ENV === "development",+});```## Using environment variables for your Project ID@@ -335,7 +333,7 @@ SWETRIX_PROJECT_ID=YOUR_PROJECT_ID``````javascript-const swetrix = new Swetrix(process.env.SWETRIX_PROJECT_ID)+const swetrix = new Swetrix(process.env.SWETRIX_PROJECT_ID);```If you use [dotenv](https://www.npmjs.com/package/dotenv):@@ -345,9 +343,9 @@ npm install dotenv``````javascript-require('dotenv').config()+require("dotenv").config();-const swetrix = new Swetrix(process.env.SWETRIX_PROJECT_ID)+const swetrix = new Swetrix(process.env.SWETRIX_PROJECT_ID);```## Complete example@@ -355,56 +353,56 @@ const swetrix = new Swetrix(process.env.SWETRIX_PROJECT_ID)Here's a full Express application with Swetrix analytics:```javascript-const express = require('express')-const { Swetrix } = require('@swetrix/node')+const express = require("express");+const { Swetrix } = require("@swetrix/node");-const app = express()+const app = express();const swetrix = new Swetrix(process.env.SWETRIX_PROJECT_ID, {- disabled: process.env.NODE_ENV !== 'production',-})+ disabled: process.env.NODE_ENV !== "production",+});-app.set('trust proxy', true)-app.use(express.json())+app.set("trust proxy", true);+app.use(express.json());// Track pageviews on all requestsapp.use((req, res, next) => {- swetrix.trackPageView(req.ip, req.headers['user-agent'], {+ swetrix.trackPageView(req.ip, req.headers["user-agent"], {pg: req.path,- lc: req.headers['accept-language']?.split(',')[0],- ref: req.headers['referer'],- })+ lc: req.headers["accept-language"]?.split(",")[0],+ ref: req.headers["referer"],+ });- next()-})+ next();+});-app.get('/', (req, res) => {- res.send('Hello World')-})+app.get("/", (req, res) => {+ res.send("Hello World");+});-app.post('/api/contact', async (req, res) => {- swetrix.track(req.ip, req.headers['user-agent'], {- ev: 'CONTACT_FORM_SUBMITTED',- page: '/contact',- })+app.post("/api/contact", async (req, res) => {+ swetrix.track(req.ip, req.headers["user-agent"], {+ ev: "CONTACT_FORM_SUBMITTED",+ page: "/contact",+ });- res.json({ success: true })-})+ res.json({ success: true });+});// Error trackingapp.use((err, req, res, next) => {- swetrix.trackError(req.ip, req.headers['user-agent'], {- name: err.name || 'Error',+ swetrix.trackError(req.ip, req.headers["user-agent"], {+ name: err.name || "Error",message: err.message,stackTrace: err.stack,pg: req.path,- })+ });- res.status(500).json({ error: 'Internal Server Error' })-})+ res.status(500).json({ error: "Internal Server Error" });+});app.listen(3000, () => {- console.log('Server running on port 3000')-})+ console.log("Server running on port 3000");+});```## Check your installation@@ -416,9 +414,9 @@ Deploy your application (or temporarily enable `devMode`) and make a few requestIf you're self-hosting the [Swetrix API](https://github.com/Swetrix/swetrix-api), point the `apiURL` option to your instance:```javascript-const swetrix = new Swetrix('YOUR_PROJECT_ID', {- apiURL: 'https://your-swetrix-instance.com/log',-})+const swetrix = new Swetrix("YOUR_PROJECT_ID", {+ apiURL: "https://your-swetrix-instance.com/log",+});```## Further readingdiff --git a/docs/content/docs/integrations/fastapi.mdx b/docs/content/docs/integrations/fastapi.mdxindex f461b51e8..369039216 100644--- a/docs/content/docs/integrations/fastapi.mdx+++ b/docs/content/docs/integrations/fastapi.mdx@@ -164,7 +164,6 @@ class SwetrixClient:await self._client.aclose()```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -250,7 +249,6 @@ async def track_pageviews(request: Request, call_next):return response```-<Callout type="info">By using `asyncio.create_task()`, the analytics call runs in the background without adding latency to your responses. This is the recommended pattern for production.@@ -307,15 +305,15 @@ async def dashboard(request: Request, visitor: VisitorInfo = Depends(get_visitorThe `track_pageview` method accepts the following keyword arguments:-| Option | Type | Description |-| --- | --- | --- |-| `pg` | `str` | Page path (e.g. `/home`) |-| `lc` | `str` | Visitor locale (e.g. `en-US`) |-| `ref` | `str` | Referrer URL |-| `so` | `str` | Traffic source (e.g. `utm_source`) |-| `me` | `str` | Traffic medium (e.g. `utm_medium`) |-| `ca` | `str` | Campaign (e.g. `utm_campaign`) |-| `unique` | `bool` | Only save unique visits |+| Option | Type | Description |+| -------- | ------ | ---------------------------------- |+| `pg` | `str` | Page path (e.g. `/home`) |+| `lc` | `str` | Visitor locale (e.g. `en-US`) |+| `ref` | `str` | Referrer URL |+| `so` | `str` | Traffic source (e.g. `utm_source`) |+| `me` | `str` | Traffic medium (e.g. `utm_medium`) |+| `ca` | `str` | Campaign (e.g. `utm_campaign`) |+| `unique` | `bool` | Only save unique visits |## Tracking custom eventsdiff --git a/docs/content/docs/integrations/fastify.mdx b/docs/content/docs/integrations/fastify.mdxindex 9c8b34d18..8c6e1fbf2 100644--- a/docs/content/docs/integrations/fastify.mdx+++ b/docs/content/docs/integrations/fastify.mdx@@ -18,14 +18,13 @@ npm install @swetrix/nodeInitialise the Swetrix client with your Project ID:```javascript-import Fastify from 'fastify'-import { Swetrix } from '@swetrix/node'+import Fastify from "fastify";+import { Swetrix } from "@swetrix/node";-const fastify = Fastify({ logger: true })-const swetrix = new Swetrix('YOUR_PROJECT_ID')+const fastify = Fastify({ logger: true });+const swetrix = new Swetrix("YOUR_PROJECT_ID");```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -34,20 +33,20 @@ Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboarThe `Swetrix` constructor accepts an optional second argument — an options object:```javascript-const swetrix = new Swetrix('YOUR_PROJECT_ID', {+const swetrix = new Swetrix("YOUR_PROJECT_ID", {devMode: false,- disabled: process.env.NODE_ENV !== 'production',+ disabled: process.env.NODE_ENV !== "production",apiURL: undefined, // only needed for self-hosted Swetrix-})+});```-| Option | Type | Description |-| --- | --- | --- |-| `devMode` | `boolean` | When `true`, all tracking logs are printed to the console |-| `disabled` | `boolean` | When `true`, no data is sent to the server — useful for development |-| `apiURL` | `string` | Custom API server URL (for self-hosted Swetrix) |-| `unique` | `boolean` | When `true`, only unique events are saved |-| `profileId` | `string` | Optional profile ID for long-term user tracking |+| Option | Type | Description |+| ----------- | --------- | ------------------------------------------------------------------- |+| `devMode` | `boolean` | When `true`, all tracking logs are printed to the console |+| `disabled` | `boolean` | When `true`, no data is sent to the server — useful for development |+| `apiURL` | `string` | Custom API server URL (for self-hosted Swetrix) |+| `unique` | `boolean` | When `true`, only unique events are saved |+| `profileId` | `string` | Optional profile ID for long-term user tracking |## Tracking pageviews@@ -56,18 +55,18 @@ To track pageviews you need to pass the visitor's **IP address** and **User-Agen### Basic example```javascript-fastify.get('/', async (request, reply) => {- const ip = request.ip- const userAgent = request.headers['user-agent']+fastify.get("/", async (request, reply) => {+ const ip = request.ip;+ const userAgent = request.headers["user-agent"];await swetrix.trackPageView(ip, userAgent, {- pg: '/',- lc: request.headers['accept-language']?.split(',')[0],- ref: request.headers['referer'],- })+ pg: "/",+ lc: request.headers["accept-language"]?.split(",")[0],+ ref: request.headers["referer"],+ });- return { message: 'Hello World' }-})+ return { message: "Hello World" };+});```### Hook approach (recommended)@@ -75,20 +74,19 @@ fastify.get('/', async (request, reply) => {Fastify's lifecycle hooks let you track pageviews automatically on every request without repeating code in each route handler. The `onRequest` hook runs before the route handler:```javascript-fastify.addHook('onRequest', async (request, reply) => {- const ip = request.ip- const userAgent = request.headers['user-agent']+fastify.addHook("onRequest", async (request, reply) => {+ const ip = request.ip;+ const userAgent = request.headers["user-agent"];// Fire-and-forget — don't block the responseswetrix.trackPageView(ip, userAgent, {pg: request.url,- lc: request.headers['accept-language']?.split(',')[0],- ref: request.headers['referer'],- })-})+ lc: request.headers["accept-language"]?.split(",")[0],+ ref: request.headers["referer"],+ });+});```-<Callout type="info">By not awaiting `trackPageView`, analytics calls happen in the background without adding latency to your responses. This is the recommended pattern for production.@@ -99,7 +97,7 @@ If your Fastify app runs behind a reverse proxy (e.g. Nginx, Cloudflare, or a lo```javascriptconst fastify = Fastify({trustProxy: true,-})+});```### Plugin approach@@ -107,36 +105,36 @@ const fastify = Fastify({For a more Fastify-idiomatic solution, you can wrap the tracking logic in a plugin:```javascript-import fp from 'fastify-plugin'-import { Swetrix } from '@swetrix/node'+import fp from "fastify-plugin";+import { Swetrix } from "@swetrix/node";export default fp(async function swetrixPlugin(fastify, opts) {const swetrix = new Swetrix(opts.projectId, {disabled: opts.disabled,devMode: opts.devMode,- })+ });- fastify.decorate('swetrix', swetrix)+ fastify.decorate("swetrix", swetrix);- fastify.addHook('onRequest', async (request) => {- swetrix.trackPageView(request.ip, request.headers['user-agent'], {+ fastify.addHook("onRequest", async (request) => {+ swetrix.trackPageView(request.ip, request.headers["user-agent"], {pg: request.url,- lc: request.headers['accept-language']?.split(',')[0],- ref: request.headers['referer'],- })- })-})+ lc: request.headers["accept-language"]?.split(",")[0],+ ref: request.headers["referer"],+ });+ });+});```Register the plugin in your app:```javascript-import swetrixPlugin from './plugins/swetrix.js'+import swetrixPlugin from "./plugins/swetrix.js";fastify.register(swetrixPlugin, {projectId: process.env.SWETRIX_PROJECT_ID,- disabled: process.env.NODE_ENV !== 'production',-})+ disabled: process.env.NODE_ENV !== "production",+});```After registering, you can access the Swetrix instance from any route via `fastify.swetrix` or `request.server.swetrix`.@@ -145,33 +143,33 @@ After registering, you can access the Swetrix instance from any route via `fastiThe third argument to `trackPageView` is an options object:-| Option | Type | Description |-| --- | --- | --- |-| `pg` | `string` | Page path (e.g. `/home`) |-| `lc` | `string` | Visitor locale (e.g. `en-US`) |-| `ref` | `string` | Referrer URL |-| `so` | `string` | Traffic source (e.g. `utm_source`) |-| `me` | `string` | Traffic medium (e.g. `utm_medium`) |-| `ca` | `string` | Campaign (e.g. `utm_campaign`) |-| `unique` | `boolean` | Only save unique visits |-| `meta` | `object` | Custom metadata key-value pairs |+| Option | Type | Description |+| -------- | --------- | ---------------------------------- |+| `pg` | `string` | Page path (e.g. `/home`) |+| `lc` | `string` | Visitor locale (e.g. `en-US`) |+| `ref` | `string` | Referrer URL |+| `so` | `string` | Traffic source (e.g. `utm_source`) |+| `me` | `string` | Traffic medium (e.g. `utm_medium`) |+| `ca` | `string` | Campaign (e.g. `utm_campaign`) |+| `unique` | `boolean` | Only save unique visits |+| `meta` | `object` | Custom metadata key-value pairs |## Tracking custom eventsTrack specific actions — API calls, form submissions, purchases, etc.:```javascript-fastify.post('/api/subscribe', async (request, reply) => {- swetrix.track(request.ip, request.headers['user-agent'], {- ev: 'NEWSLETTER_SUBSCRIBE',- page: '/subscribe',+fastify.post("/api/subscribe", async (request, reply) => {+ swetrix.track(request.ip, request.headers["user-agent"], {+ ev: "NEWSLETTER_SUBSCRIBE",+ page: "/subscribe",meta: {plan: request.body.plan,},- })+ });- return { success: true }-})+ return { success: true };+});```### Event naming rules@@ -189,37 +187,37 @@ Use Fastify's `setErrorHandler` to report errors to Swetrix automatically:```javascriptfastify.setErrorHandler((error, request, reply) => {- swetrix.trackError(request.ip, request.headers['user-agent'], {- name: error.name || 'Error',+ swetrix.trackError(request.ip, request.headers["user-agent"], {+ name: error.name || "Error",message: error.message,stackTrace: error.stack,pg: request.url,- })+ });reply.status(error.statusCode || 500).send({- error: 'Internal Server Error',- })-})+ error: "Internal Server Error",+ });+});```You can also track errors from specific routes:```javascript-fastify.get('/api/data', async (request, reply) => {+fastify.get("/api/data", async (request, reply) => {try {- const data = await fetchExternalData()- return data+ const data = await fetchExternalData();+ return data;} catch (err) {- swetrix.trackError(request.ip, request.headers['user-agent'], {+ swetrix.trackError(request.ip, request.headers["user-agent"], {name: err.name,message: err.message,stackTrace: err.stack,pg: request.url,- })+ });- reply.status(500).send({ error: 'Failed to fetch data' })+ reply.status(500).send({ error: "Failed to fetch data" });}-})+});```## Heartbeat events@@ -227,22 +225,22 @@ fastify.get('/api/data', async (request, reply) => {Heartbeat events let Swetrix know a visitor's session is still active, powering the **Live Visitors** counter in your dashboard. They're most useful in long-lived connections like WebSocket sessions:```javascript-import websocket from '@fastify/websocket'+import websocket from "@fastify/websocket";-fastify.register(websocket)+fastify.register(websocket);-const HEARTBEAT_INTERVAL = 30_000+const HEARTBEAT_INTERVAL = 30_000;-fastify.get('/ws', { websocket: true }, (socket, request) => {- const ip = request.ip- const userAgent = request.headers['user-agent']+fastify.get("/ws", { websocket: true }, (socket, request) => {+ const ip = request.ip;+ const userAgent = request.headers["user-agent"];const interval = setInterval(() => {- swetrix.heartbeat(ip, userAgent)- }, HEARTBEAT_INTERVAL)+ swetrix.heartbeat(ip, userAgent);+ }, HEARTBEAT_INTERVAL);- socket.on('close', () => clearInterval(interval))-})+ socket.on("close", () => clearInterval(interval));+});```## Feature flags@@ -250,29 +248,29 @@ fastify.get('/ws', { websocket: true }, (socket, request) => {Evaluate feature flags server-side based on visitor context:```javascript-fastify.get('/dashboard', async (request, reply) => {+fastify.get("/dashboard", async (request, reply) => {const showNewDashboard = await swetrix.getFeatureFlag(- 'new-dashboard',+ "new-dashboard",request.ip,- request.headers['user-agent'],+ request.headers["user-agent"],{ profileId: request.user?.id },false, // default value- )+ );if (showNewDashboard) {- return reply.view('dashboard-v2')+ return reply.view("dashboard-v2");}- return reply.view('dashboard')-})+ return reply.view("dashboard");+});```You can also fetch all flags at once:```javascript-const flags = await swetrix.getFeatureFlags(request.ip, request.headers['user-agent'])+const flags = await swetrix.getFeatureFlags(request.ip, request.headers["user-agent"]);-if (flags['beta-feature']) {+if (flags["beta-feature"]) {// Enable beta feature}```@@ -280,7 +278,7 @@ if (flags['beta-feature']) {Feature flags are cached for 5 minutes. To force a refresh:```javascript-swetrix.clearFeatureFlagsCache()+swetrix.clearFeatureFlagsCache();```## A/B testing (experiments)@@ -288,19 +286,19 @@ swetrix.clearFeatureFlagsCache()Run server-side A/B tests and get the assigned variant for each visitor:```javascript-fastify.get('/pricing', async (request, reply) => {+fastify.get("/pricing", async (request, reply) => {const variant = await swetrix.getExperiment(- 'pricing-experiment-id',+ "pricing-experiment-id",request.ip,- request.headers['user-agent'],+ request.headers["user-agent"],{ profileId: request.user?.id },null, // default variant- )+ );return {- showAnnualFirst: variant === 'annual-first',- }-})+ showAnnualFirst: variant === "annual-first",+ };+});```## Revenue attribution@@ -308,11 +306,11 @@ fastify.get('/pricing', async (request, reply) => {Use profile and session IDs to connect analytics with your payment provider (e.g. Paddle, Stripe):```javascript-fastify.get('/checkout', async (request, reply) => {+fastify.get("/checkout", async (request, reply) => {const [profileId, sessionId] = await Promise.all([- swetrix.getProfileId(request.ip, request.headers['user-agent']),- swetrix.getSessionId(request.ip, request.headers['user-agent']),- ])+ swetrix.getProfileId(request.ip, request.headers["user-agent"]),+ swetrix.getSessionId(request.ip, request.headers["user-agent"]),+ ]);return {checkoutConfig: {@@ -321,8 +319,8 @@ fastify.get('/checkout', async (request, reply) => {swetrix_session_id: sessionId,},},- }-})+ };+});```## Disable tracking in development@@ -330,17 +328,17 @@ fastify.get('/checkout', async (request, reply) => {Use the `disabled` option to prevent tracking during development:```javascript-const swetrix = new Swetrix('YOUR_PROJECT_ID', {- disabled: process.env.NODE_ENV !== 'production',-})+const swetrix = new Swetrix("YOUR_PROJECT_ID", {+ disabled: process.env.NODE_ENV !== "production",+});```Or use `devMode` to log tracking calls to the console without disabling them:```javascript-const swetrix = new Swetrix('YOUR_PROJECT_ID', {- devMode: process.env.NODE_ENV === 'development',-})+const swetrix = new Swetrix("YOUR_PROJECT_ID", {+ devMode: process.env.NODE_ENV === "development",+});```## Using environment variables for your Project ID@@ -352,23 +350,23 @@ SWETRIX_PROJECT_ID=YOUR_PROJECT_ID``````javascript-const swetrix = new Swetrix(process.env.SWETRIX_PROJECT_ID)+const swetrix = new Swetrix(process.env.SWETRIX_PROJECT_ID);```With Fastify's [`@fastify/env`](https://github.com/fastify/fastify-env) plugin:```javascript-import fastifyEnv from '@fastify/env'+import fastifyEnv from "@fastify/env";const schema = {- type: 'object',- required: ['SWETRIX_PROJECT_ID'],+ type: "object",+ required: ["SWETRIX_PROJECT_ID"],properties: {- SWETRIX_PROJECT_ID: { type: 'string' },+ SWETRIX_PROJECT_ID: { type: "string" },},-}+};-fastify.register(fastifyEnv, { schema, dotenv: true })+fastify.register(fastifyEnv, { schema, dotenv: true });```## Complete example@@ -376,58 +374,58 @@ fastify.register(fastifyEnv, { schema, dotenv: true })Here's a full Fastify application with Swetrix analytics:```javascript-import Fastify from 'fastify'-import { Swetrix } from '@swetrix/node'+import Fastify from "fastify";+import { Swetrix } from "@swetrix/node";const fastify = Fastify({logger: true,trustProxy: true,-})+});const swetrix = new Swetrix(process.env.SWETRIX_PROJECT_ID, {- disabled: process.env.NODE_ENV !== 'production',-})+ disabled: process.env.NODE_ENV !== "production",+});// Track pageviews on all requests-fastify.addHook('onRequest', async (request) => {- swetrix.trackPageView(request.ip, request.headers['user-agent'], {+fastify.addHook("onRequest", async (request) => {+ swetrix.trackPageView(request.ip, request.headers["user-agent"], {pg: request.url,- lc: request.headers['accept-language']?.split(',')[0],- ref: request.headers['referer'],- })-})+ lc: request.headers["accept-language"]?.split(",")[0],+ ref: request.headers["referer"],+ });+});-fastify.get('/', async () => {- return { message: 'Hello World' }-})+fastify.get("/", async () => {+ return { message: "Hello World" };+});-fastify.post('/api/contact', async (request) => {- swetrix.track(request.ip, request.headers['user-agent'], {- ev: 'CONTACT_FORM_SUBMITTED',- page: '/contact',- })+fastify.post("/api/contact", async (request) => {+ swetrix.track(request.ip, request.headers["user-agent"], {+ ev: "CONTACT_FORM_SUBMITTED",+ page: "/contact",+ });- return { success: true }-})+ return { success: true };+});// Error trackingfastify.setErrorHandler((error, request, reply) => {- swetrix.trackError(request.ip, request.headers['user-agent'], {- name: error.name || 'Error',+ swetrix.trackError(request.ip, request.headers["user-agent"], {+ name: error.name || "Error",message: error.message,stackTrace: error.stack,pg: request.url,- })+ });- reply.status(500).send({ error: 'Internal Server Error' })-})+ reply.status(500).send({ error: "Internal Server Error" });+});fastify.listen({ port: 3000 }, (err) => {if (err) {- fastify.log.error(err)- process.exit(1)+ fastify.log.error(err);+ process.exit(1);}-})+});```## Check your installation@@ -439,9 +437,9 @@ Deploy your application (or temporarily enable `devMode`) and make a few requestIf you're self-hosting the [Swetrix API](https://github.com/Swetrix/swetrix-api), point the `apiURL` option to your instance:```javascript-const swetrix = new Swetrix('YOUR_PROJECT_ID', {- apiURL: 'https://your-swetrix-instance.com/log',-})+const swetrix = new Swetrix("YOUR_PROJECT_ID", {+ apiURL: "https://your-swetrix-instance.com/log",+});```## Further readingdiff --git a/docs/content/docs/integrations/flask.mdx b/docs/content/docs/integrations/flask.mdxindex 22ec8bdb7..c7ce12a71 100644--- a/docs/content/docs/integrations/flask.mdx+++ b/docs/content/docs/integrations/flask.mdx@@ -18,25 +18,25 @@ Flask uses Jinja2 templates, and most projects define a shared base template tha```html<!DOCTYPE html><html lang="en">-<head>- <meta charset="utf-8">- <meta name="viewport" content="width=device-width, initial-scale=1">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" /><title>{% block title %}My App{% endblock %}</title>{% block styles %}{% endblock %}<!-- Swetrix Analytics --><script src="https://swetrix.org/swetrix.js" defer></script>-</head>-<body>+ </head>+ <body>{% block content %}{% endblock %}<!-- Swetrix Analytics --><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -48,23 +48,18 @@ Flask uses Jinja2 templates, and most projects define a shared base template tha</noscript>{% block scripts %}{% endblock %}-</body>+ </body></html>```All page templates that extend this base will automatically include the tracking script:```html-{% extends "base.html" %}--{% block title %}Home{% endblock %}--{% block content %}- <h1>Welcome to my Flask app</h1>+{% extends "base.html" %} {% block title %}Home{% endblock %} {% block content %}+<h1>Welcome to my Flask app</h1>{% endblock %}```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -76,7 +71,7 @@ To avoid polluting your analytics with local page views, wrap the snippet in an```html{% if config.ENV == 'production' or not config.DEBUG %}- <script src="https://swetrix.org/swetrix.js" defer></script>+<script src="https://swetrix.org/swetrix.js" defer></script>{% endif %}```@@ -84,29 +79,28 @@ And for the body initialisation:```html{% if config.ENV == 'production' or not config.DEBUG %}- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })- </script>+<script>+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });+</script>- <noscript>- <img- src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"- alt=""- referrerpolicy="no-referrer-when-downgrade"- />- </noscript>+<noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+</noscript>{% endif %}```-<Callout type="info">During development, Swetrix ignores `localhost` traffic by default. If you want to verify tracking locally without changing your environment, you can temporarily set `devMode: true`:```js-swetrix.init('YOUR_PROJECT_ID', { devMode: true })+swetrix.init("YOUR_PROJECT_ID", { devMode: true });```Remember to remove this before deploying.@@ -136,21 +130,21 @@ app.config['SWETRIX_PROJECT_ID'] = os.environ.get('SWETRIX_PROJECT_ID', '')```html{% if config.SWETRIX_PROJECT_ID %}- <script src="https://swetrix.org/swetrix.js" defer></script>- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('{{ config.SWETRIX_PROJECT_ID }}')- swetrix.trackViews()- })- </script>+<script src="https://swetrix.org/swetrix.js" defer></script>+<script>+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("{{ config.SWETRIX_PROJECT_ID }}");+ swetrix.trackViews();+ });+</script>- <noscript>- <img- src="https://api.swetrix.com/log/noscript?pid={{ config.SWETRIX_PROJECT_ID }}"- alt=""- referrerpolicy="no-referrer-when-downgrade"- />- </noscript>+<noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid={{ config.SWETRIX_PROJECT_ID }}"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+</noscript>{% endif %}```@@ -178,11 +172,11 @@ Enable automatic client-side error monitoring by adding `trackErrors()` to the i```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- swetrix.trackErrors()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ swetrix.trackErrors();+ });</script>```@@ -198,22 +192,22 @@ Track when users submit a registration form:```html<form id="register-form" method="POST" action="/register">- <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">- <input type="email" name="email" placeholder="[email protected]">- <button type="submit">Register</button>+ <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />+ <input type="email" name="email" placeholder="[email protected]" />+ <button type="submit">Register</button></form><script>- document.getElementById('register-form')?.addEventListener('submit', function () {- if (typeof swetrix !== 'undefined') {+ document.getElementById("register-form")?.addEventListener("submit", function () {+ if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'REGISTER_FORM_SUBMITTED',+ ev: "REGISTER_FORM_SUBMITTED",meta: {page: window.location.pathname,},- })+ });}- })+ });</script>```@@ -223,20 +217,20 @@ Track clicks on external links across your site. Add this to your base template:```html<script>- document.addEventListener('DOMContentLoaded', function () {+ document.addEventListener("DOMContentLoaded", function () {document.querySelectorAll('a[href^="http"]').forEach(function (link) {if (link.hostname !== window.location.hostname) {- link.addEventListener('click', function () {- if (typeof swetrix !== 'undefined') {+ link.addEventListener("click", function () {+ if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'OUTBOUND_CLICK',+ ev: "OUTBOUND_CLICK",meta: { url: link.href },- })+ });}- })+ });}- })- })+ });+ });</script>```@@ -256,25 +250,23 @@ If your application is structured with [blueprints](https://flask.palletsprojectIf a blueprint uses its own base template, add the Swetrix snippet there as well, or create a shared partial:```html-{# templates/partials/swetrix.html #}--{% if config.SWETRIX_PROJECT_ID %}- <script src="https://swetrix.org/swetrix.js" defer></script>- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('{{ config.SWETRIX_PROJECT_ID }}')- swetrix.trackViews()- swetrix.trackErrors()- })- </script>+{# templates/partials/swetrix.html #} {% if config.SWETRIX_PROJECT_ID %}+<script src="https://swetrix.org/swetrix.js" defer></script>+<script>+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("{{ config.SWETRIX_PROJECT_ID }}");+ swetrix.trackViews();+ swetrix.trackErrors();+ });+</script>- <noscript>- <img- src="https://api.swetrix.com/log/noscript?pid={{ config.SWETRIX_PROJECT_ID }}"- alt=""- referrerpolicy="no-referrer-when-downgrade"- />- </noscript>+<noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid={{ config.SWETRIX_PROJECT_ID }}"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+</noscript>{% endif %}```@@ -296,10 +288,10 @@ npm install swetrix``````javascript-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";-Swetrix.init('YOUR_PROJECT_ID')-Swetrix.trackViews()+Swetrix.init("YOUR_PROJECT_ID");+Swetrix.trackViews();```See the relevant frontend framework integration guide ([React](/react-integration), [Vue](/vue-integration), etc.) for framework-specific details.diff --git a/docs/content/docs/integrations/framer.mdx b/docs/content/docs/integrations/framer.mdxindex ee82448e0..5c912d5c9 100644--- a/docs/content/docs/integrations/framer.mdx+++ b/docs/content/docs/integrations/framer.mdx@@ -3,19 +3,21 @@ title: Framerslug: /framer-integration----After you sign up on Swetrix and create a new project, the only thing left is to add it to your website.## Installation1. Log in to your [Framer](https://www.framer.com) account.2. In the dashboard, click on the website you want to add Swetrix to:+<img alt="Framer Dashboard" src="/docs/img/framer-1.png" />3. Open the website settings:+<img alt="Framer Website page" src="/docs/img/framer-2.png" />4. Scroll down to the `Custom Code` section:+<img alt="Framer Website page" src="/docs/img/framer-3.png" />5. Add the following code to the `End of <body> tag` section:@@ -23,10 +25,10 @@ After you sign up on Swetrix and create a new project, the only thing left is to```html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -38,7 +40,6 @@ After you sign up on Swetrix and create a new project, the only thing left is to</noscript>```-<Callout type="warn">It's important to remember to replace `YOUR_PROJECT_ID` with your actual Project ID, which you can find in the Swetrix Dashboard, otherwise tracking will not work!diff --git a/docs/content/docs/integrations/gatsby.mdx b/docs/content/docs/integrations/gatsby.mdxindex 7ecb60a65..5d7d1708c 100644--- a/docs/content/docs/integrations/gatsby.mdx+++ b/docs/content/docs/integrations/gatsby.mdx@@ -20,18 +20,17 @@ Gatsby provides a [`gatsby-browser.js`](https://www.gatsbyjs.com/docs/reference/Create or update `gatsby-browser.js` in your project root:```js-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export const onClientEntry = () => {- Swetrix.init('YOUR_PROJECT_ID')-}+ Swetrix.init("YOUR_PROJECT_ID");+};export const onRouteUpdate = () => {- Swetrix.trackViews()-}+ Swetrix.trackViews();+};```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -44,7 +43,7 @@ To track visitors who have JavaScript disabled, add a noscript image pixel usingCreate or update `gatsby-ssr.js` in your project root:```jsx-import React from 'react'+import React from "react";export const onRenderBody = ({ setPostBodyComponents }) => {setPostBodyComponents([@@ -55,8 +54,8 @@ export const onRenderBody = ({ setPostBodyComponents }) => {referrerPolicy="no-referrer-when-downgrade"/></noscript>,- ])-}+ ]);+};```## Disable tracking in development@@ -64,19 +63,18 @@ export const onRenderBody = ({ setPostBodyComponents }) => {By default, Swetrix ignores `localhost` traffic. If you want to be explicit about it, you can conditionally disable tracking based on your environment:```js-Swetrix.init('YOUR_PROJECT_ID', {- disabled: process.env.NODE_ENV === 'development',-})+Swetrix.init("YOUR_PROJECT_ID", {+ disabled: process.env.NODE_ENV === "development",+});```-<Callout type="info">If you want to verify tracking locally during development, set `devMode: true` instead:```js-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {devMode: true,-})+});```Remember to remove this before deploying to production.@@ -92,16 +90,16 @@ Build and deploy your site with `gatsby build && gatsby serve` (or deploy to youEnable automatic client-side error monitoring by adding `trackErrors()` to your `gatsby-browser.js`. This captures unhandled JavaScript errors and reports them to Swetrix.```js-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export const onClientEntry = () => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackErrors()-}+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackErrors();+};export const onRouteUpdate = () => {- Swetrix.trackViews()-}+ Swetrix.trackViews();+};```Errors will appear in the **Errors** tab of your project dashboard. See the [tracking script reference](/swetrix-js-reference#trackerrors) for options like `sampleRate` and `callback`.@@ -113,52 +111,48 @@ Custom events let you track specific user interactions — button clicks, form s### Example: tracking button clicks```jsx-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export default function PricingCTA() {const handleClick = () => {Swetrix.track({- ev: 'PRICING_CTA_CLICK',+ ev: "PRICING_CTA_CLICK",meta: {- plan: 'pro',- location: 'hero',+ plan: "pro",+ location: "hero",},- })- }+ });+ };- return (- <button onClick={handleClick}>- Upgrade to Pro- </button>- )+ return <button onClick={handleClick}>Upgrade to Pro</button>;}```### Example: tracking form submissions```jsx-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export default function NewsletterForm() {const handleSubmit = (e) => {- e.preventDefault()+ e.preventDefault();Swetrix.track({- ev: 'NEWSLETTER_SIGNUP',+ ev: "NEWSLETTER_SIGNUP",meta: {- source: 'footer',+ source: "footer",},- })+ });// ...submit logic- }+ };return (<form onSubmit={handleSubmit}><input type="email" placeholder="[email protected]" required /><button type="submit">Subscribe</button></form>- )+ );}```@@ -184,7 +178,7 @@ GATSBY_SWETRIX_PID=YOUR_PROJECT_ID**2. Reference it in `gatsby-browser.js`:**```js-Swetrix.init(process.env.GATSBY_SWETRIX_PID)+Swetrix.init(process.env.GATSBY_SWETRIX_PID);```## Further readingdiff --git a/docs/content/docs/integrations/ghost.mdx b/docs/content/docs/integrations/ghost.mdxindex 47b4dab9c..e61ccb46b 100644--- a/docs/content/docs/integrations/ghost.mdx+++ b/docs/content/docs/integrations/ghost.mdx@@ -20,10 +20,10 @@ After you sign up on Swetrix and create a new project, the only thing left is to```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -35,7 +35,6 @@ After you sign up on Swetrix and create a new project, the only thing left is to</noscript>```-<Callout type="warn">It's very important not to forget to replace `YOUR_PROJECT_ID` with your actual Project ID you can find in the Dashboard, otherwise tracking won't work!diff --git a/docs/content/docs/integrations/gitbook.mdx b/docs/content/docs/integrations/gitbook.mdxindex deabf228d..983688b11 100644--- a/docs/content/docs/integrations/gitbook.mdx+++ b/docs/content/docs/integrations/gitbook.mdx@@ -28,10 +28,10 @@ GitBook's custom script injection requires:```html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script>```@@ -39,7 +39,6 @@ GitBook's custom script injection requires:Click **Save** to apply the script to your documentation site.-<Callout type="warn">Don't forget to replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -63,7 +62,6 @@ If the Head section supports multiple code blocks, you can also add a noscript pOpen your documentation site through your custom domain in a new browser tab or incognito window. Browse through a few pages. Within a minute you should see new pageviews appearing in your Swetrix dashboard.-<Callout type="info">Make sure you're accessing the site via your custom domain, not the default `*.gitbook.io` URL. Custom scripts only load on custom domains.@@ -82,11 +80,11 @@ Update the script in your Head section:```html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- swetrix.trackErrors()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ swetrix.trackErrors();+ });</script>```diff --git a/docs/content/docs/integrations/google-search-console.mdx b/docs/content/docs/integrations/google-search-console.mdxindex 332e348a2..1aba23979 100644--- a/docs/content/docs/integrations/google-search-console.mdx+++ b/docs/content/docs/integrations/google-search-console.mdx@@ -18,7 +18,6 @@ By connecting GSC, you can unlock valuable SEO insights without leaving Swetrix:## How to Set Up-<Callout type="info" title="Prerequisites">You must have a Google Search Console account with your website property already verified.diff --git a/docs/content/docs/integrations/google-tag-manager.mdx b/docs/content/docs/integrations/google-tag-manager.mdxindex f13222700..26f78a84c 100644--- a/docs/content/docs/integrations/google-tag-manager.mdx+++ b/docs/content/docs/integrations/google-tag-manager.mdx@@ -3,10 +3,8 @@ title: Google Tag Managerslug: /gtm-integration----Google Tag Manager (GTM) allows you to add tracking scripts to your website without modifying your codebase directly. This guide walks you through integrating Swetrix via GTM.-<Callout>GTM adds extra complexity and is blocked by many adblockers, which may reduce tracking reliability. The Swetrix tracking script is lightweight and we recommend [adding it directly](/install-script) when possible. You can also [set up a proxy](/adblockers/how-to) to mitigate adblocker interference.@@ -19,12 +17,15 @@ Normally you'd add Swetrix to your site with a simple `<script>` tag. However, G## Installation1. Sign in to your Google Tag Manager account, click on **Tags** and then **New**.+<img alt="Creating a new tag" src="/docs/img/integrations/google/gt-1.png" />2. Under the **Tag Configuration** section, click on "Choose a tag type to begin set-up...".+<img alt="Tag Configuration" src="/docs/img/integrations/google/gt-2.png" />3. Select **Custom HTML**.+<img alt="Custom HTML" src="/docs/img/integrations/google/gt-3.png" />4. In the HTML input field, paste the following code:@@ -32,18 +33,17 @@ Normally you'd add Swetrix to your site with a simple `<script>` tag. However, G```html<script>(function () {- var el = document.createElement('script')- el.src = 'https://swetrix.org/swetrix.js'+ var el = document.createElement("script");+ el.src = "https://swetrix.org/swetrix.js";el.onload = function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- }- document.head.appendChild(el)- })()+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ };+ document.head.appendChild(el);+ })();</script>```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the Swetrix dashboard, otherwise tracking won't work.You can also refer to the [tracking script reference](/swetrix-js-reference) for more advanced configuration options (e.g. `hash`, `search`, `respectDNT`).@@ -53,9 +53,11 @@ You can also refer to the [tracking script reference](/swetrix-js-reference) for5. Under **Triggering**, click on "Choose a trigger to make this tag fire..." and select **All Pages** (or set up a more specific trigger to limit which pages Swetrix runs on).6. Give your tag a name — change "Untitled Tag" to something like **Swetrix Analytics**. The result should look similar to this:+<img alt="Final result" src="/docs/img/integrations/google/gt-4.png" />7. Click **Save**. A list of tags will be displayed - you should see your new Swetrix tag in the list. Click the **Submit** button in the top right corner.+<img alt="Tags list" src="/docs/img/integrations/google/gt-5.png" />8. Add a description for your changes in the pop-up window and click **Publish**.@@ -77,13 +79,13 @@ Create an additional **Custom HTML** tag in GTM and set a trigger for the intera```html<script>- if (typeof swetrix !== 'undefined') {+ if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'signup_cta_clicked',+ ev: "signup_cta_clicked",meta: {- page: window.location.pathname- }- })+ page: window.location.pathname,+ },+ });}</script>```@@ -96,16 +98,16 @@ Create a **Custom HTML** tag and reference the variables:```html<script>- if (typeof swetrix !== 'undefined') {+ if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'element_clicked',+ ev: "element_clicked",meta: {- page: '{{Page URL}}',- referrer: '{{Referrer}}',- click_text: '{{Click Text}}',- click_url: '{{Click URL}}'- }- })+ page: "{{Page URL}}",+ referrer: "{{Referrer}}",+ click_text: "{{Click Text}}",+ click_url: "{{Click URL}}",+ },+ });}</script>```@@ -117,17 +119,17 @@ Then attach a trigger for the specific interaction — for example, **Click - AlSince Swetrix is available globally once loaded via GTM, you can also call `swetrix.track()` directly from your website code:```javascript-document.getElementById('cta-button')?.addEventListener('click', function () {- if (typeof swetrix !== 'undefined') {+document.getElementById("cta-button")?.addEventListener("click", function () {+ if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'cta_clicked',+ ev: "cta_clicked",meta: {button_text: this.textContent,- page: window.location.pathname- }- })+ page: window.location.pathname,+ },+ });}-})+});```### Example events@@ -135,24 +137,23 @@ document.getElementById('cta-button')?.addEventListener('click', function () {```javascript// Form submissionswetrix.track({- ev: 'form_submitted',- meta: { form_id: 'contact_form' }-})+ ev: "form_submitted",+ meta: { form_id: "contact_form" },+});// File downloadswetrix.track({- ev: 'file_downloaded',- meta: { file_name: 'whitepaper.pdf', file_type: 'pdf' }-})+ ev: "file_downloaded",+ meta: { file_name: "whitepaper.pdf", file_type: "pdf" },+});// Video engagementswetrix.track({- ev: 'video_played',- meta: { video_title: 'Product Demo' }-})+ ev: "video_played",+ meta: { video_title: "Product Demo" },+});```-<Callout type="info">Event names can contain any characters (including spaces and unicode) with a maximum length of 256 characters. The `meta` object supports up to 20 keys with a combined value length under 1000 characters.@@ -165,26 +166,26 @@ You can enable automatic client-side error monitoring by adding `swetrix.trackEr```html<script>(function () {- var el = document.createElement('script')- el.src = 'https://swetrix.org/swetrix.js'+ var el = document.createElement("script");+ el.src = "https://swetrix.org/swetrix.js";el.onload = function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- swetrix.trackErrors()- }- document.head.appendChild(el)- })()+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ swetrix.trackErrors();+ };+ document.head.appendChild(el);+ })();</script>```This captures unhandled JavaScript errors and sends them to Swetrix automatically. You can also track errors manually from GTM or your website code:```javascript-if (typeof swetrix !== 'undefined') {+if (typeof swetrix !== "undefined") {swetrix.trackError({- name: 'PaymentError',- message: 'Card declined',- })+ name: "PaymentError",+ message: "Card declined",+ });}```diff --git a/docs/content/docs/integrations/hexo.mdx b/docs/content/docs/integrations/hexo.mdxindex 01bb06e49..c2c381131 100644--- a/docs/content/docs/integrations/hexo.mdx+++ b/docs/content/docs/integrations/hexo.mdx@@ -18,10 +18,10 @@ In your active theme's directory, create the file `themes/<your-theme>/layout/_p```html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('<%= theme.swetrix_project_id || "YOUR_PROJECT_ID" %>')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init('<%= theme.swetrix_project_id || "YOUR_PROJECT_ID" %>');+ swetrix.trackViews();+ });</script><noscript>@@ -33,7 +33,6 @@ In your active theme's directory, create the file `themes/<your-theme>/layout/_p</noscript>```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -113,10 +112,10 @@ By default, Swetrix ignores traffic from `localhost`, so page views during `hexo<% if (config.env === 'production' || !config.env) { %><script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('<%= theme.swetrix_project_id || "YOUR_PROJECT_ID" %>')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init('<%= theme.swetrix_project_id || "YOUR_PROJECT_ID" %>');+ swetrix.trackViews();+ });</script><noscript>@@ -141,7 +140,6 @@ And build for production with:NODE_ENV=production hexo generate```-<Callout type="info">Since Swetrix ignores `localhost` traffic by default, the environment-based conditional is optional. It's useful if you want to avoid loading the script entirely during development.@@ -154,11 +152,11 @@ Enable automatic client-side error monitoring by adding `trackErrors()` alongsid```html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- swetrix.trackErrors()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ swetrix.trackErrors();+ });</script>```@@ -171,9 +169,7 @@ Custom events let you track specific user interactions — button clicks, form s### Inline event tracking```html-<button onclick="swetrix.track({ ev: 'SIGNUP_CLICK' })">- Sign up-</button>+<button onclick="swetrix.track({ ev: 'SIGNUP_CLICK' })">Sign up</button>```### Example: tracking form submissions@@ -185,17 +181,17 @@ Custom events let you track specific user interactions — button clicks, form s</form><script>- document.addEventListener('DOMContentLoaded', function () {- var form = document.getElementById('contact-form')- if (!form || typeof swetrix === 'undefined') return+ document.addEventListener("DOMContentLoaded", function () {+ var form = document.getElementById("contact-form");+ if (!form || typeof swetrix === "undefined") return;- form.addEventListener('submit', function () {+ form.addEventListener("submit", function () {swetrix.track({- ev: 'NEWSLETTER_SIGNUP',- meta: { source: 'footer' },- })- })- })+ ev: "NEWSLETTER_SIGNUP",+ meta: { source: "footer" },+ });+ });+ });</script>```@@ -217,10 +213,10 @@ npm install swetrixThen use it in a client-side script bundled with your theme:```js-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";-Swetrix.init('YOUR_PROJECT_ID')-Swetrix.trackViews()+Swetrix.init("YOUR_PROJECT_ID");+Swetrix.trackViews();```## Check your installationdiff --git a/docs/content/docs/integrations/htmx.mdx b/docs/content/docs/integrations/htmx.mdxindex f90aa7af6..6031c75bc 100644--- a/docs/content/docs/integrations/htmx.mdx+++ b/docs/content/docs/integrations/htmx.mdx@@ -16,10 +16,10 @@ Place the following just before the closing `</body>` tag in your base template:```html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -31,7 +31,6 @@ Place the following just before the closing `</body>` tag in your base template:</noscript>```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -62,10 +61,10 @@ Here's a complete base layout with htmx and Swetrix:<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -91,10 +90,10 @@ Add the scripts to your base template (e.g. `templates/base.html`):{% if not debug %}<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script>{% endif %}```@@ -105,10 +104,10 @@ Add the scripts to your base template (e.g. `templates/base.html`):{% if not config.DEBUG %}<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script>{% endif %}```@@ -119,10 +118,10 @@ Add the scripts to your base template (e.g. `templates/base.html`):{{ if eq .Env "production" }}<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script>{{ end }}```@@ -133,11 +132,11 @@ Enable automatic client-side error monitoring by adding `trackErrors()` alongsid```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- swetrix.trackErrors()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ swetrix.trackErrors();+ });</script>```@@ -150,9 +149,7 @@ Custom events let you track specific user interactions — button clicks, form s### Inline event tracking```html-<button onclick="swetrix.track({ ev: 'SIGNUP_CLICK' })">- Sign up-</button>+<button onclick="swetrix.track({ ev: 'SIGNUP_CLICK' })">Sign up</button>```### Tracking htmx-triggered actions@@ -167,15 +164,16 @@ You can hook into htmx events to track actions like form submissions that happen<div id="result"></div><script>- document.querySelector('form[hx-post="/subscribe"]')- .addEventListener('htmx:afterRequest', function (event) {- if (event.detail.successful && typeof swetrix !== 'undefined') {+ document+ .querySelector('form[hx-post="/subscribe"]')+ .addEventListener("htmx:afterRequest", function (event) {+ if (event.detail.successful && typeof swetrix !== "undefined") {swetrix.track({- ev: 'NEWSLETTER_SIGNUP',- meta: { source: 'footer' },- })+ ev: "NEWSLETTER_SIGNUP",+ meta: { source: "footer" },+ });}- })+ });</script>```diff --git a/docs/content/docs/integrations/hugo.mdx b/docs/content/docs/integrations/hugo.mdxindex f223a8a81..109e6ec31 100644--- a/docs/content/docs/integrations/hugo.mdx+++ b/docs/content/docs/integrations/hugo.mdx@@ -17,10 +17,10 @@ In your Hugo project, create the file `layouts/partials/swetrix-analytics.html`{{ if not .Site.IsServer }}<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -35,7 +35,6 @@ In your Hugo project, create the file `layouts/partials/swetrix-analytics.html`The `{{ if not .Site.IsServer }}` condition ensures the tracking script is only included in production builds (`hugo`) and not during local development (`hugo server`). This prevents inflating your analytics with local page views.-<Callout type="warn">It's very important not to forget to replace `YOUR_PROJECT_ID` with your actual Project ID you can find in the Dashboard, otherwise tracking won't work!@@ -63,10 +62,10 @@ Update `layouts/partials/swetrix-analytics.html`:{{ if and (not .Site.IsServer) .Site.Params.swetrixProjectID }}<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('{{ .Site.Params.swetrixProjectID }}')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("{{ .Site.Params.swetrixProjectID }}");+ swetrix.trackViews();+ });</script><noscript>diff --git a/docs/content/docs/integrations/jekyll.mdx b/docs/content/docs/integrations/jekyll.mdxindex dad94fae2..08175c674 100644--- a/docs/content/docs/integrations/jekyll.mdx+++ b/docs/content/docs/integrations/jekyll.mdx@@ -17,10 +17,10 @@ In your Jekyll project, create the file `_includes/swetrix-analytics.html` with{% if jekyll.environment == "production" %}<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -35,7 +35,6 @@ In your Jekyll project, create the file `_includes/swetrix-analytics.html` withThe `{% if jekyll.environment == "production" %}` condition ensures the tracking script is only included in production builds. This prevents inflating your analytics with local page views during development.-<Callout type="warn">It's very important not to forget to replace `YOUR_PROJECT_ID` with your actual Project ID you can find in the Dashboard, otherwise tracking won't work!@@ -61,7 +60,6 @@ Jekyll doesn't set the environment to `production` by default when building locaJEKYLL_ENV=production jekyll build```-<Callout type="info">If you deploy via **GitHub Pages**, the environment is automatically set to `production` — no extra configuration needed.@@ -84,10 +82,10 @@ swetrix:{% if jekyll.environment == "production" and site.swetrix.project_id %}<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('{{ site.swetrix.project_id }}')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("{{ site.swetrix.project_id }}");+ swetrix.trackViews();+ });</script><noscript>@@ -108,11 +106,11 @@ To enable automatic client-side error monitoring, add `trackErrors()` after `ini{% if jekyll.environment == "production" %}<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- swetrix.trackErrors()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ swetrix.trackErrors();+ });</script><noscript>@@ -132,20 +130,18 @@ Errors will appear in the **Errors** tab of your project dashboard. See the [traYou can track custom events (button clicks, form submissions, etc.) anywhere on your site by calling `swetrix.track()`:```html-<button onclick="swetrix.track({ ev: 'SIGNUP_CLICK' })">- Sign up-</button>+<button onclick="swetrix.track({ ev: 'SIGNUP_CLICK' })">Sign up</button>```For events with metadata:```javascriptswetrix.track({- ev: 'NEWSLETTER_SIGNUP',+ ev: "NEWSLETTER_SIGNUP",meta: {- source: 'footer',+ source: "footer",},-})+});```### Event naming rulesdiff --git a/docs/content/docs/integrations/joomla.mdx b/docs/content/docs/integrations/joomla.mdxindex 867de2026..09ede7ad2 100644--- a/docs/content/docs/integrations/joomla.mdx+++ b/docs/content/docs/integrations/joomla.mdx@@ -32,10 +32,10 @@ Switch to the **Editor** tab. If the WYSIWYG editor is active, switch it to sour```html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -47,7 +47,6 @@ Switch to the **Editor** tab. If the WYSIWYG editor is active, switch it to sour</noscript>```-<Callout type="warn">Don't forget to replace `YOUR_PROJECT_ID` with your actual Project ID from the Swetrix dashboard, otherwise tracking won't work.@@ -76,10 +75,10 @@ Paste the following just before the closing `</body>` tag:```html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -91,7 +90,6 @@ Paste the following just before the closing `</body>` tag:</noscript>```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the Swetrix dashboard.@@ -99,7 +97,6 @@ Replace `YOUR_PROJECT_ID` with your actual Project ID from the Swetrix dashboard3. Click **Save**.-<Callout>Template updates may overwrite your changes. If you update your template, verify the Swetrix snippet is still present. Making a copy of the template before updating is a good precaution.@@ -113,14 +110,14 @@ Example — tracking a contact form submission:```html<script>- document.addEventListener('DOMContentLoaded', function () {- var form = document.querySelector('#contact-form')- if (!form || typeof swetrix === 'undefined') return-- form.addEventListener('submit', function () {- swetrix.track({ ev: 'contact_form_submitted' })- })- })+ document.addEventListener("DOMContentLoaded", function () {+ var form = document.querySelector("#contact-form");+ if (!form || typeof swetrix === "undefined") return;++ form.addEventListener("submit", function () {+ swetrix.track({ ev: "contact_form_submitted" });+ });+ });</script>```diff --git a/docs/content/docs/integrations/laravel.mdx b/docs/content/docs/integrations/laravel.mdxindex 9fcb5d03c..91c0f8712 100644--- a/docs/content/docs/integrations/laravel.mdx+++ b/docs/content/docs/integrations/laravel.mdx@@ -25,25 +25,21 @@ Open your layout file and add the Swetrix script just before the closing `</head```html<!DOCTYPE html><html lang="{{ str_replace('_', '-', app()->getLocale()) }}">-<head>- <meta charset="utf-8">- <meta name="viewport" content="width=device-width, initial-scale=1">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" /><title>{{ config('app.name', 'Laravel') }}</title>- @vite(['resources/css/app.css', 'resources/js/app.js'])-- {{-- Swetrix Analytics --}}+ @vite(['resources/css/app.css', 'resources/js/app.js']) {{-- Swetrix Analytics --}}<script src="https://swetrix.org/swetrix.js" defer></script>-</head>-<body>- @yield('content')-- {{-- Swetrix Analytics --}}+ </head>+ <body>+ @yield('content') {{-- Swetrix Analytics --}}<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -53,11 +49,10 @@ Open your layout file and add the Swetrix script just before the closing `</headreferrerpolicy="no-referrer-when-downgrade"/></noscript>-</body>+ </body></html>```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -69,7 +64,7 @@ To avoid polluting your analytics with local page views, wrap the snippet in an```html@production- <script src="https://swetrix.org/swetrix.js" defer></script>+<script src="https://swetrix.org/swetrix.js" defer></script>@endproduction```@@ -77,31 +72,30 @@ And for the body initialisation:```html@production- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })- </script>+<script>+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });+</script>- <noscript>- <img- src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"- alt=""- referrerpolicy="no-referrer-when-downgrade"- />- </noscript>+<noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+</noscript>@endproduction```The `@production` Blade directive ensures the script is only included when `APP_ENV=production`.-<Callout type="info">During development, Swetrix ignores `localhost` traffic by default. If you want to verify tracking locally without changing your environment, you can temporarily set `devMode: true`:```js-swetrix.init('YOUR_PROJECT_ID', { devMode: true })+swetrix.init("YOUR_PROJECT_ID", { devMode: true });```Remember to remove this before deploying.@@ -134,21 +128,21 @@ return [```html@production- <script src="https://swetrix.org/swetrix.js" defer></script>- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('{{ config('services.swetrix.project_id') }}')- swetrix.trackViews()- })- </script>+<script src="https://swetrix.org/swetrix.js" defer></script>+<script>+ document.addEventListener('DOMContentLoaded', function () {+ swetrix.init('{{ config('services.swetrix.project_id') }}')+ swetrix.trackViews()+ })+</script>- <noscript>- <img- src="https://api.swetrix.com/log/noscript?pid={{ config('services.swetrix.project_id') }}"- alt=""- referrerpolicy="no-referrer-when-downgrade"- />- </noscript>+<noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid={{ config('services.swetrix.project_id') }}"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+</noscript>@endproduction```@@ -184,22 +178,21 @@ Track when users submit a contact form:```html<form id="contact-form" method="POST" action="/contact">- @csrf- {{-- form fields --}}- <button type="submit">Send message</button>+ @csrf {{-- form fields --}}+ <button type="submit">Send message</button></form><script>- document.getElementById('contact-form')?.addEventListener('submit', function () {- if (typeof swetrix !== 'undefined') {+ document.getElementById("contact-form")?.addEventListener("submit", function () {+ if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'CONTACT_FORM_SUBMITTED',+ ev: "CONTACT_FORM_SUBMITTED",meta: {page: window.location.pathname,},- })+ });}- })+ });</script>```@@ -209,20 +202,20 @@ Track clicks on external links across your site. You can add this to your main l```html<script>- document.addEventListener('DOMContentLoaded', function () {+ document.addEventListener("DOMContentLoaded", function () {document.querySelectorAll('a[href^="http"]').forEach(function (link) {if (link.hostname !== window.location.hostname) {- link.addEventListener('click', function () {- if (typeof swetrix !== 'undefined') {+ link.addEventListener("click", function () {+ if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'OUTBOUND_CLICK',+ ev: "OUTBOUND_CLICK",meta: { url: link.href },- })+ });}- })+ });}- })- })+ });+ });</script>```@@ -244,13 +237,13 @@ Swetrix's `trackViews()` function listens for History API changes, so Inertia naFor Livewire, if you use `wire:navigate` for SPA-style navigation, Swetrix will similarly pick up the URL changes. If you experience any gaps, you can manually fire a page view after navigation:```js-document.addEventListener('livewire:navigated', function () {- if (typeof swetrix !== 'undefined') {+document.addEventListener("livewire:navigated", function () {+ if (typeof swetrix !== "undefined") {swetrix.pageview({payload: { pg: window.location.pathname },- })+ });}-})+});```## Further readingdiff --git a/docs/content/docs/integrations/mkdocs.mdx b/docs/content/docs/integrations/mkdocs.mdxindex 25c54c19e..11b3fa7ab 100644--- a/docs/content/docs/integrations/mkdocs.mdx+++ b/docs/content/docs/integrations/mkdocs.mdx@@ -30,32 +30,25 @@ theme:Create the file `overrides/main.html` in your project root with the following content:```html-{% extends "base.html" %}--{% block extrahead %}- {{ super() }}- <script src="https://swetrix.org/swetrix.js" defer></script>- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })- </script>-{% endblock %}--{% block content %}- {{ super() }}- <noscript>- <img- src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"- alt=""- referrerpolicy="no-referrer-when-downgrade"- />- </noscript>+{% extends "base.html" %} {% block extrahead %} {{ super() }}+<script src="https://swetrix.org/swetrix.js" defer></script>+<script>+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });+</script>+{% endblock %} {% block content %} {{ super() }}+<noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+</noscript>{% endblock %}```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -86,28 +79,24 @@ theme:Create `overrides/main.html` (the file name depends on your theme's base template). For the default `readthedocs` theme:```html-{% extends "base.html" %}--{% block footer %}- {{ super() }}- <script src="https://swetrix.org/swetrix.js" defer></script>- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })- </script>- <noscript>- <img- src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"- alt=""- referrerpolicy="no-referrer-when-downgrade"- />- </noscript>+{% extends "base.html" %} {% block footer %} {{ super() }}+<script src="https://swetrix.org/swetrix.js" defer></script>+<script>+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });+</script>+<noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+</noscript>{% endblock %}```-<Callout type="info">Check your theme's documentation for the available template blocks. Most themes expose a `footer`, `scripts`, or `extra` block you can extend.@@ -128,33 +117,25 @@ extra:**2. Update the override template:**```html-{% extends "base.html" %}--{% block extrahead %}- {{ super() }}- {% if config.extra.swetrix and config.extra.swetrix.project_id %}- <script src="https://swetrix.org/swetrix.js" defer></script>- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('{{ config.extra.swetrix.project_id }}')- swetrix.trackViews()- })- </script>- {% endif %}-{% endblock %}--{% block content %}- {{ super() }}- {% if config.extra.swetrix and config.extra.swetrix.project_id %}- <noscript>- <img- src="https://api.swetrix.com/log/noscript?pid={{ config.extra.swetrix.project_id }}"- alt=""- referrerpolicy="no-referrer-when-downgrade"- />- </noscript>- {% endif %}-{% endblock %}+{% extends "base.html" %} {% block extrahead %} {{ super() }} {% if config.extra.swetrix and+config.extra.swetrix.project_id %}+<script src="https://swetrix.org/swetrix.js" defer></script>+<script>+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("{{ config.extra.swetrix.project_id }}");+ swetrix.trackViews();+ });+</script>+{% endif %} {% endblock %} {% block content %} {{ super() }} {% if config.extra.swetrix and+config.extra.swetrix.project_id %}+<noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid={{ config.extra.swetrix.project_id }}"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+</noscript>+{% endif %} {% endblock %}```## Disable tracking in development@@ -163,7 +144,6 @@ By default, Swetrix ignores traffic from `localhost`, so page views during `mkdoIf you want to avoid loading the script entirely during development, you can use an environment variable via a [MkDocs hook](https://www.mkdocs.org/user-guide/configuration/#hooks). However, since localhost traffic is already ignored, this is typically unnecessary.-<Callout type="info">Since Swetrix ignores `localhost` traffic by default, your development page views won't appear in the dashboard even without any special configuration.@@ -174,18 +154,15 @@ Since Swetrix ignores `localhost` traffic by default, your development page viewEnable automatic client-side error monitoring by adding `trackErrors()` alongside your existing initialisation:```html-{% extends "base.html" %}--{% block extrahead %}- {{ super() }}- <script src="https://swetrix.org/swetrix.js" defer></script>- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- swetrix.trackErrors()- })- </script>+{% extends "base.html" %} {% block extrahead %} {{ super() }}+<script src="https://swetrix.org/swetrix.js" defer></script>+<script>+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ swetrix.trackErrors();+ });+</script>{% endblock %}```@@ -200,9 +177,7 @@ Custom events let you track specific user interactions — button clicks, form sYou can add event tracking to any element on a Markdown page using raw HTML:```html-<button onclick="swetrix.track({ ev: 'FEEDBACK_CLICK' })">- Send feedback-</button>+<button onclick="swetrix.track({ ev: 'FEEDBACK_CLICK' })">Send feedback</button>```### Example: tracking outbound linksdiff --git a/docs/content/docs/integrations/nestjs.mdx b/docs/content/docs/integrations/nestjs.mdxindex c2b7db071..ea5e75fca 100644--- a/docs/content/docs/integrations/nestjs.mdx+++ b/docs/content/docs/integrations/nestjs.mdx@@ -21,37 +21,34 @@ Create a dedicated module and service to keep your analytics logic organised and```typescript// src/swetrix/swetrix.service.ts-import { Injectable } from '@nestjs/common'-import { Swetrix } from '@swetrix/node'-import { ConfigService } from '@nestjs/config'+import { Injectable } from "@nestjs/common";+import { Swetrix } from "@swetrix/node";+import { ConfigService } from "@nestjs/config";@Injectable()export class SwetrixService {- private readonly swetrix: Swetrix+ private readonly swetrix: Swetrix;constructor(private readonly configService: ConfigService) {- this.swetrix = new Swetrix(- this.configService.get<string>('SWETRIX_PROJECT_ID'),- {- disabled: this.configService.get('NODE_ENV') !== 'production',- },- )+ this.swetrix = new Swetrix(this.configService.get<string>("SWETRIX_PROJECT_ID"), {+ disabled: this.configService.get("NODE_ENV") !== "production",+ });}trackPageView(ip: string, userAgent: string, options?: Record<string, any>) {- return this.swetrix.trackPageView(ip, userAgent, options)+ return this.swetrix.trackPageView(ip, userAgent, options);}track(ip: string, userAgent: string, options: Record<string, any>) {- return this.swetrix.track(ip, userAgent, options)+ return this.swetrix.track(ip, userAgent, options);}trackError(ip: string, userAgent: string, options: Record<string, any>) {- return this.swetrix.trackError(ip, userAgent, options)+ return this.swetrix.trackError(ip, userAgent, options);}heartbeat(ip: string, userAgent: string) {- return this.swetrix.heartbeat(ip, userAgent)+ return this.swetrix.heartbeat(ip, userAgent);}getFeatureFlag(@@ -61,11 +58,11 @@ export class SwetrixService {options?: Record<string, any>,defaultValue?: boolean,) {- return this.swetrix.getFeatureFlag(name, ip, userAgent, options, defaultValue)+ return this.swetrix.getFeatureFlag(name, ip, userAgent, options, defaultValue);}getFeatureFlags(ip: string, userAgent: string, options?: Record<string, any>) {- return this.swetrix.getFeatureFlags(ip, userAgent, options)+ return this.swetrix.getFeatureFlags(ip, userAgent, options);}getExperiment(@@ -75,23 +72,23 @@ export class SwetrixService {options?: Record<string, any>,defaultVariant?: string | null,) {- return this.swetrix.getExperiment(experimentId, ip, userAgent, options, defaultVariant)+ return this.swetrix.getExperiment(experimentId, ip, userAgent, options, defaultVariant);}getProfileId(ip: string, userAgent: string) {- return this.swetrix.getProfileId(ip, userAgent)+ return this.swetrix.getProfileId(ip, userAgent);}getSessionId(ip: string, userAgent: string) {- return this.swetrix.getSessionId(ip, userAgent)+ return this.swetrix.getSessionId(ip, userAgent);}clearFeatureFlagsCache() {- this.swetrix.clearFeatureFlagsCache()+ this.swetrix.clearFeatureFlagsCache();}clearExperimentsCache() {- this.swetrix.clearExperimentsCache()+ this.swetrix.clearExperimentsCache();}}```@@ -100,8 +97,8 @@ export class SwetrixService {```typescript// src/swetrix/swetrix.module.ts-import { Global, Module } from '@nestjs/common'-import { SwetrixService } from './swetrix.service'+import { Global, Module } from "@nestjs/common";+import { SwetrixService } from "./swetrix.service";@Global()@Module({@@ -117,20 +114,16 @@ The `@Global()` decorator makes the module available everywhere without needing```typescript// src/app.module.ts-import { Module } from '@nestjs/common'-import { ConfigModule } from '@nestjs/config'-import { SwetrixModule } from './swetrix/swetrix.module'+import { Module } from "@nestjs/common";+import { ConfigModule } from "@nestjs/config";+import { SwetrixModule } from "./swetrix/swetrix.module";@Module({- imports: [- ConfigModule.forRoot({ isGlobal: true }),- SwetrixModule,- ],+ imports: [ConfigModule.forRoot({ isGlobal: true }), SwetrixModule],})export class AppModule {}```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), or set the `SWETRIX_PROJECT_ID` environment variable.@@ -146,30 +139,25 @@ An interceptor lets you track pageviews automatically on every request without r```typescript// src/swetrix/swetrix.interceptor.ts-import {- Injectable,- NestInterceptor,- ExecutionContext,- CallHandler,-} from '@nestjs/common'-import { Observable } from 'rxjs'-import { SwetrixService } from './swetrix.service'+import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from "@nestjs/common";+import { Observable } from "rxjs";+import { SwetrixService } from "./swetrix.service";@Injectable()export class SwetrixInterceptor implements NestInterceptor {constructor(private readonly swetrix: SwetrixService) {}intercept(context: ExecutionContext, next: CallHandler): Observable<any> {- const req = context.switchToHttp().getRequest()+ const req = context.switchToHttp().getRequest();// Fire-and-forget — don't block the response- this.swetrix.trackPageView(req.ip, req.headers['user-agent'], {+ this.swetrix.trackPageView(req.ip, req.headers["user-agent"], {pg: req.path,- lc: req.headers['accept-language']?.split(',')[0],- ref: req.headers['referer'],- })+ lc: req.headers["accept-language"]?.split(",")[0],+ ref: req.headers["referer"],+ });- return next.handle()+ return next.handle();}}```@@ -178,23 +166,22 @@ Register it globally in your `main.ts`:```typescript// src/main.ts-import { NestFactory } from '@nestjs/core'-import { AppModule } from './app.module'-import { SwetrixInterceptor } from './swetrix/swetrix.interceptor'-import { SwetrixService } from './swetrix/swetrix.service'+import { NestFactory } from "@nestjs/core";+import { AppModule } from "./app.module";+import { SwetrixInterceptor } from "./swetrix/swetrix.interceptor";+import { SwetrixService } from "./swetrix/swetrix.service";async function bootstrap() {- const app = await NestFactory.create(AppModule)+ const app = await NestFactory.create(AppModule);- const swetrixService = app.get(SwetrixService)- app.useGlobalInterceptors(new SwetrixInterceptor(swetrixService))+ const swetrixService = app.get(SwetrixService);+ app.useGlobalInterceptors(new SwetrixInterceptor(swetrixService));- await app.listen(3000)+ await app.listen(3000);}-bootstrap()+bootstrap();```-<Callout type="info">By not awaiting `trackPageView`, analytics calls happen in the background without adding latency to your responses. This is the recommended pattern for production.@@ -203,8 +190,8 @@ By not awaiting `trackPageView`, analytics calls happen in the background withouIf your NestJS app runs behind a reverse proxy (e.g. Nginx, Cloudflare, or a load balancer), enable the Express `trust proxy` setting in `main.ts` so `req.ip` returns the real client IP:```typescript-const app = await NestFactory.create(AppModule)-app.getHttpAdapter().getInstance().set('trust proxy', true)+const app = await NestFactory.create(AppModule);+app.getHttpAdapter().getInstance().set("trust proxy", true);```### Per-route tracking@@ -212,9 +199,9 @@ app.getHttpAdapter().getInstance().set('trust proxy', true)You can also track pageviews in individual controllers by injecting the service:```typescript-import { Controller, Get, Req } from '@nestjs/common'-import { Request } from 'express'-import { SwetrixService } from '../swetrix/swetrix.service'+import { Controller, Get, Req } from "@nestjs/common";+import { Request } from "express";+import { SwetrixService } from "../swetrix/swetrix.service";@Controller()export class AppController {@@ -222,11 +209,11 @@ export class AppController {@Get()getHome(@Req() req: Request) {- this.swetrix.trackPageView(req.ip, req.headers['user-agent'], {- pg: '/',- })+ this.swetrix.trackPageView(req.ip, req.headers["user-agent"], {+ pg: "/",+ });- return { message: 'Hello World' }+ return { message: "Hello World" };}}```@@ -235,39 +222,39 @@ export class AppController {The third argument to `trackPageView` is an options object:-| Option | Type | Description |-| --- | --- | --- |-| `pg` | `string` | Page path (e.g. `/home`) |-| `lc` | `string` | Visitor locale (e.g. `en-US`) |-| `ref` | `string` | Referrer URL |-| `so` | `string` | Traffic source (e.g. `utm_source`) |-| `me` | `string` | Traffic medium (e.g. `utm_medium`) |-| `ca` | `string` | Campaign (e.g. `utm_campaign`) |-| `unique` | `boolean` | Only save unique visits |-| `meta` | `object` | Custom metadata key-value pairs |+| Option | Type | Description |+| -------- | --------- | ---------------------------------- |+| `pg` | `string` | Page path (e.g. `/home`) |+| `lc` | `string` | Visitor locale (e.g. `en-US`) |+| `ref` | `string` | Referrer URL |+| `so` | `string` | Traffic source (e.g. `utm_source`) |+| `me` | `string` | Traffic medium (e.g. `utm_medium`) |+| `ca` | `string` | Campaign (e.g. `utm_campaign`) |+| `unique` | `boolean` | Only save unique visits |+| `meta` | `object` | Custom metadata key-value pairs |## Tracking custom eventsTrack specific actions — API calls, form submissions, purchases, etc.:```typescript-import { Controller, Post, Req, Body } from '@nestjs/common'-import { Request } from 'express'-import { SwetrixService } from '../swetrix/swetrix.service'+import { Controller, Post, Req, Body } from "@nestjs/common";+import { Request } from "express";+import { SwetrixService } from "../swetrix/swetrix.service";-@Controller('api')+@Controller("api")export class SubscriptionController {constructor(private readonly swetrix: SwetrixService) {}- @Post('subscribe')+ @Post("subscribe")subscribe(@Req() req: Request, @Body() body: { plan: string }) {- this.swetrix.track(req.ip, req.headers['user-agent'], {- ev: 'NEWSLETTER_SUBSCRIBE',- page: '/subscribe',+ this.swetrix.track(req.ip, req.headers["user-agent"], {+ ev: "NEWSLETTER_SUBSCRIBE",+ page: "/subscribe",meta: { plan: body.plan },- })+ });- return { success: true }+ return { success: true };}}```@@ -287,38 +274,30 @@ Use a NestJS exception filter to report errors to Swetrix automatically:```typescript// src/swetrix/swetrix-exception.filter.ts-import {- Catch,- ArgumentsHost,- HttpException,- HttpStatus,-} from '@nestjs/common'-import { BaseExceptionFilter } from '@nestjs/core'-import { SwetrixService } from './swetrix.service'+import { Catch, ArgumentsHost, HttpException, HttpStatus } from "@nestjs/common";+import { BaseExceptionFilter } from "@nestjs/core";+import { SwetrixService } from "./swetrix.service";@Catch()export class SwetrixExceptionFilter extends BaseExceptionFilter {constructor(private readonly swetrix: SwetrixService) {- super()+ super();}catch(exception: unknown, host: ArgumentsHost) {- const ctx = host.switchToHttp()- const req = ctx.getRequest()+ const ctx = host.switchToHttp();+ const req = ctx.getRequest();- const error =- exception instanceof Error- ? exception- : new Error(String(exception))+ const error = exception instanceof Error ? exception : new Error(String(exception));- this.swetrix.trackError(req.ip, req.headers['user-agent'], {- name: error.name || 'Error',+ this.swetrix.trackError(req.ip, req.headers["user-agent"], {+ name: error.name || "Error",message: error.message,stackTrace: error.stack,pg: req.path,- })+ });- super.catch(exception, host)+ super.catch(exception, host);}}```@@ -326,25 +305,25 @@ export class SwetrixExceptionFilter extends BaseExceptionFilter {Register the filter globally in `main.ts`:```typescript-const swetrixService = app.get(SwetrixService)-app.useGlobalFilters(new SwetrixExceptionFilter(swetrixService))+const swetrixService = app.get(SwetrixService);+app.useGlobalFilters(new SwetrixExceptionFilter(swetrixService));```You can also track errors from specific services:```typescripttry {- const data = await this.httpService.get('https://api.example.com/data')- return data+ const data = await this.httpService.get("https://api.example.com/data");+ return data;} catch (err) {this.swetrix.trackError(ip, userAgent, {name: err.name,message: err.message,stackTrace: err.stack,- pg: '/api/data',- })+ pg: "/api/data",+ });- throw new InternalServerErrorException('Failed to fetch data')+ throw new InternalServerErrorException("Failed to fetch data");}```@@ -370,9 +349,9 @@ async getDashboard(@Req() req: Request) {You can also fetch all flags at once:```typescript-const flags = await this.swetrix.getFeatureFlags(ip, userAgent)+const flags = await this.swetrix.getFeatureFlags(ip, userAgent);-if (flags['beta-feature']) {+if (flags["beta-feature"]) {// Enable beta feature}```@@ -380,7 +359,7 @@ if (flags['beta-feature']) {Feature flags are cached for 5 minutes. To force a refresh:```typescript-this.swetrix.clearFeatureFlagsCache()+this.swetrix.clearFeatureFlagsCache();```## A/B testing (experiments)@@ -432,12 +411,9 @@ async getCheckout(@Req() req: Request) {The service example above already disables tracking when `NODE_ENV` isn't `production`. You can also use `devMode` to log calls to the console during development:```typescript-this.swetrix = new Swetrix(- this.configService.get<string>('SWETRIX_PROJECT_ID'),- {- devMode: this.configService.get('NODE_ENV') === 'development',- },-)+this.swetrix = new Swetrix(this.configService.get<string>("SWETRIX_PROJECT_ID"), {+ devMode: this.configService.get("NODE_ENV") === "development",+});```## Using environment variables for your Project ID@@ -459,9 +435,9 @@ Deploy your application (or temporarily enable `devMode`) and make a few requestIf you're self-hosting the [Swetrix API](https://github.com/Swetrix/swetrix-api), point the `apiURL` option to your instance:```typescript-this.swetrix = new Swetrix('YOUR_PROJECT_ID', {- apiURL: 'https://your-swetrix-instance.com/log',-})+this.swetrix = new Swetrix("YOUR_PROJECT_ID", {+ apiURL: "https://your-swetrix-instance.com/log",+});```## Further readingdiff --git a/docs/content/docs/integrations/nextjs.mdx b/docs/content/docs/integrations/nextjs.mdxindex dc6f50dc5..3913ffb27 100644--- a/docs/content/docs/integrations/nextjs.mdx+++ b/docs/content/docs/integrations/nextjs.mdx@@ -27,20 +27,21 @@ Create a client component that initialises Swetrix. `trackViews()` automaticallyCreate a new file at `src/components/Analytics.tsx` (or `src/components/Analytics.jsx` if you're not using TypeScript):```tsx-'use client'+"use client";-import { useEffect } from 'react'-import * as Swetrix from 'swetrix'+import { useEffect } from "react";+import * as Swetrix from "swetrix";export default function Analytics() {useEffect(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- }, [])+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ }, []);- return null+ return null;}```+</Step><Step>### Add it to your root layout@@ -48,13 +49,9 @@ export default function Analytics() {Open `src/app/layout.tsx` and render the `Analytics` component:```tsx-import Analytics from '@/components/Analytics'+import Analytics from "@/components/Analytics";-export default function RootLayout({- children,-}: {- children: React.ReactNode-}) {+export default function RootLayout({ children }: { children: React.ReactNode }) {return (<html lang="en"><body>@@ -62,9 +59,10 @@ export default function RootLayout({<Analytics /></body></html>- )+ );}```+</Step></Steps>@@ -82,7 +80,6 @@ Your project structure should look like this:</Folder></Files>-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -94,17 +91,17 @@ Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboarIf you're using the Pages Router, add Swetrix to your `_app.tsx` (or `_app.jsx`) file. `trackViews()` automatically detects route changes, so a single call is all you need.```tsx-import { useEffect } from 'react'-import type { AppProps } from 'next/app'-import * as Swetrix from 'swetrix'+import { useEffect } from "react";+import type { AppProps } from "next/app";+import * as Swetrix from "swetrix";export default function App({ Component, pageProps }: AppProps) {useEffect(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- }, [])+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ }, []);- return <Component {...pageProps} />+ return <Component {...pageProps} />;}```@@ -136,7 +133,7 @@ Add to `src/app/layout.tsx` inside `<body>`:Add to `pages/_document.tsx` inside `<body>`:```tsx-import { Html, Head, Main, NextScript } from 'next/document'+import { Html, Head, Main, NextScript } from "next/document";export default function Document() {return (@@ -154,7 +151,7 @@ export default function Document() {</noscript></body></Html>- )+ );}```@@ -166,19 +163,18 @@ export default function Document() {By default, Swetrix ignores `localhost` traffic. If you want to be explicit about it, you can conditionally disable tracking based on your environment:```tsx-Swetrix.init('YOUR_PROJECT_ID', {- disabled: process.env.NODE_ENV === 'development',-})+Swetrix.init("YOUR_PROJECT_ID", {+ disabled: process.env.NODE_ENV === "development",+});```-<Callout type="info">If you want to verify tracking locally during development, set `devMode: true` instead:```tsx-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {devMode: true,-})+});```Remember to remove this before deploying to production.@@ -200,10 +196,10 @@ Update `src/components/Analytics.tsx`:```tsxuseEffect(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- Swetrix.trackErrors()-}, [])+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ Swetrix.trackErrors();+}, []);```</Tab>@@ -213,10 +209,10 @@ Update `_app.tsx`:```tsxuseEffect(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- Swetrix.trackErrors()-}, [])+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ Swetrix.trackErrors();+}, []);```</Tab>@@ -231,56 +227,52 @@ Custom events let you track specific user interactions — button clicks, form s### Example: tracking button clicks```tsx-'use client'+"use client";-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export default function PricingCTA() {const handleClick = () => {Swetrix.track({- ev: 'PRICING_CTA_CLICK',+ ev: "PRICING_CTA_CLICK",meta: {- plan: 'pro',- location: 'hero',+ plan: "pro",+ location: "hero",},- })- }+ });+ };- return (- <button onClick={handleClick}>- Upgrade to Pro- </button>- )+ return <button onClick={handleClick}>Upgrade to Pro</button>;}```### Example: tracking form submissions```tsx-'use client'+"use client";-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export default function NewsletterForm() {const handleSubmit = (e: React.FormEvent) => {- e.preventDefault()+ e.preventDefault();Swetrix.track({- ev: 'NEWSLETTER_SIGNUP',+ ev: "NEWSLETTER_SIGNUP",meta: {- source: 'footer',+ source: "footer",},- })+ });// ...submit logic- }+ };return (<form onSubmit={handleSubmit}><input type="email" placeholder="[email protected]" required /><button type="submit">Subscribe</button></form>- )+ );}```@@ -289,33 +281,33 @@ export default function NewsletterForm() {Create a reusable component for external links:```tsx-'use client'+"use client";-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";interface TrackedLinkProps {- href: string- children: React.ReactNode- eventName?: string+ href: string;+ children: React.ReactNode;+ eventName?: string;}export default function TrackedLink({href,children,- eventName = 'OUTBOUND_CLICK',+ eventName = "OUTBOUND_CLICK",}: TrackedLinkProps) {const handleClick = () => {Swetrix.track({ev: eventName,meta: { url: href },- })- }+ });+ };return (<a href={href} target="_blank" rel="noopener noreferrer" onClick={handleClick}>{children}</a>- )+ );}```@@ -341,7 +333,7 @@ NEXT_PUBLIC_SWETRIX_PID=YOUR_PROJECT_ID**2. Reference it in your analytics component:**```tsx-Swetrix.init(process.env.NEXT_PUBLIC_SWETRIX_PID!)+Swetrix.init(process.env.NEXT_PUBLIC_SWETRIX_PID!);```## Bypassing adblockers with a proxydiff --git a/docs/content/docs/integrations/nextra.mdx b/docs/content/docs/integrations/nextra.mdxindex eb9502a0f..9c7378a6d 100644--- a/docs/content/docs/integrations/nextra.mdx+++ b/docs/content/docs/integrations/nextra.mdx@@ -24,18 +24,18 @@ Nextra 4 uses the Next.js App Router. Create a client component that initialisesCreate a new file at `src/components/Analytics.tsx` (or `components/Analytics.tsx` depending on your project structure):```tsx-'use client'+"use client";-import { useEffect } from 'react'-import * as Swetrix from 'swetrix'+import { useEffect } from "react";+import * as Swetrix from "swetrix";export default function Analytics() {useEffect(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- }, [])+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ }, []);- return null+ return null;}```@@ -44,13 +44,9 @@ export default function Analytics() {Open your root layout file (typically `app/layout.tsx` or `src/app/layout.tsx`) and render the `Analytics` component:```tsx-import Analytics from '@/components/Analytics'+import Analytics from "@/components/Analytics";-export default function RootLayout({- children,-}: {- children: React.ReactNode-}) {+export default function RootLayout({ children }: { children: React.ReactNode }) {return (<html lang="en"><body>@@ -58,11 +54,10 @@ export default function RootLayout({<Analytics /></body></html>- )+ );}```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -73,23 +68,22 @@ Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboarNextra 2 and 3 use the Next.js Pages Router. You can initialise Swetrix in your custom `_app` file. If you don't have one yet, create `pages/_app.tsx` (or `pages/_app.jsx`):```tsx-import { useEffect } from 'react'-import type { AppProps } from 'next/app'-import * as Swetrix from 'swetrix'+import { useEffect } from "react";+import type { AppProps } from "next/app";+import * as Swetrix from "swetrix";export default function App({ Component, pageProps }: AppProps) {useEffect(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- }, [])+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ }, []);- return <Component {...pageProps} />+ return <Component {...pageProps} />;}```If your project already has a custom `_app` file, simply add the `useEffect` block to the existing component.-<Callout type="info">If you're using Nextra's `_app.mdx` convention instead of `_app.tsx`, you can switch to `_app.tsx` for this setup or wrap the Swetrix initialisation in a layout component imported into your MDX app file.@@ -114,7 +108,7 @@ To track visitors who have JavaScript disabled, add a noscript image pixel.**Nextra 2 / 3** — add to `pages/_document.tsx` inside `<body>`:```tsx-import { Html, Head, Main, NextScript } from 'next/document'+import { Html, Head, Main, NextScript } from "next/document";export default function Document() {return (@@ -132,7 +126,7 @@ export default function Document() {</noscript></body></Html>- )+ );}```@@ -141,19 +135,18 @@ export default function Document() {By default, Swetrix ignores `localhost` traffic. If you want to be explicit about it, you can conditionally disable tracking based on your environment:```tsx-Swetrix.init('YOUR_PROJECT_ID', {- disabled: process.env.NODE_ENV === 'development',-})+Swetrix.init("YOUR_PROJECT_ID", {+ disabled: process.env.NODE_ENV === "development",+});```-<Callout type="info">If you want to verify tracking locally during development, set `devMode: true` instead:```tsx-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {devMode: true,-})+});```Remember to remove this before deploying to production.@@ -172,20 +165,20 @@ Enable automatic client-side error monitoring by adding `trackErrors()` to your```tsxuseEffect(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- Swetrix.trackErrors()-}, [])+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ Swetrix.trackErrors();+}, []);```**Nextra 2 / 3** — update `_app.tsx`:```tsxuseEffect(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- Swetrix.trackErrors()-}, [])+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ Swetrix.trackErrors();+}, []);```Errors will appear in the **Errors** tab of your project dashboard. See the [tracking script reference](/swetrix-js-reference#trackerrors) for options like `sampleRate` and `callback`.@@ -199,46 +192,46 @@ Custom events let you track specific user interactions — button clicks, form sTrack whether visitors found a page helpful. Create a component at `components/DocsFeedback.tsx`:```tsx-'use client'+"use client";-import { useState } from 'react'-import { usePathname } from 'next/navigation'-import * as Swetrix from 'swetrix'+import { useState } from "react";+import { usePathname } from "next/navigation";+import * as Swetrix from "swetrix";export default function DocsFeedback() {- const pathname = usePathname()- const [submitted, setSubmitted] = useState(false)+ const pathname = usePathname();+ const [submitted, setSubmitted] = useState(false);const sendFeedback = (answer: string) => {Swetrix.track({- ev: 'DOCS_FEEDBACK',+ ev: "DOCS_FEEDBACK",meta: {answer,path: pathname,},- })+ });- setSubmitted(true)- }+ setSubmitted(true);+ };if (submitted) {- return <p>Thank you for your feedback!</p>+ return <p>Thank you for your feedback!</p>;}return (<div><p>Was this page helpful?</p>- <button onClick={() => sendFeedback('Yes')}>Yes</button>- <button onClick={() => sendFeedback('No')}>No</button>+ <button onClick={() => sendFeedback("Yes")}>Yes</button>+ <button onClick={() => sendFeedback("No")}>No</button></div>- )+ );}```You can then use this component in any MDX page:```mdx-import DocsFeedback from '@/components/DocsFeedback'+import DocsFeedback from "@/components/DocsFeedback";# Getting started@@ -252,40 +245,40 @@ Your page content here...Create a reusable component for external links:```tsx-'use client'+"use client";-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";interface TrackedLinkProps {- href: string- children: React.ReactNode- eventName?: string+ href: string;+ children: React.ReactNode;+ eventName?: string;}export default function TrackedLink({href,children,- eventName = 'OUTBOUND_CLICK',+ eventName = "OUTBOUND_CLICK",}: TrackedLinkProps) {const handleClick = () => {Swetrix.track({ev: eventName,meta: { url: href },- })- }+ });+ };return (<a href={href} target="_blank" rel="noopener noreferrer" onClick={handleClick}>{children}</a>- )+ );}```Usage in MDX:```mdx-import TrackedLink from '@/components/TrackedLink'+import TrackedLink from "@/components/TrackedLink";Check out the <TrackedLink href="https://github.com/example/repo">source code</TrackedLink>.```@@ -312,7 +305,7 @@ NEXT_PUBLIC_SWETRIX_PID=YOUR_PROJECT_ID**2. Reference it in your analytics component:**```tsx-Swetrix.init(process.env.NEXT_PUBLIC_SWETRIX_PID!)+Swetrix.init(process.env.NEXT_PUBLIC_SWETRIX_PID!);```## Further readingdiff --git a/docs/content/docs/integrations/nuxt.mdx b/docs/content/docs/integrations/nuxt.mdxindex 2c9182ffa..2a0c595bc 100644--- a/docs/content/docs/integrations/nuxt.mdx+++ b/docs/content/docs/integrations/nuxt.mdx@@ -20,12 +20,12 @@ npm install swetrixNuxt plugins run once when your app initialises, making them the ideal place to set up analytics. Create `plugins/swetrix.client.ts` (the `.client` suffix ensures it only runs in the browser):```ts-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export default defineNuxtPlugin(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()-})+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+});```That's it — Nuxt auto-registers files in the `plugins/` directory. `trackViews()` automatically detects client-side route changes, so page views are tracked on every navigation.@@ -41,7 +41,6 @@ That's it — Nuxt auto-registers files in the `plugins/` directory. `trackViews<File name="nuxt.config.ts" /></Files>-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -74,26 +73,25 @@ By default, Swetrix ignores `localhost` traffic. If you want to be explicit abouUpdate `plugins/swetrix.client.ts`:```ts-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export default defineNuxtPlugin(() => {- const config = useRuntimeConfig()+ const config = useRuntimeConfig();Swetrix.init(config.public.swetrixPid, {disabled: process.dev,- })- Swetrix.trackViews()-})+ });+ Swetrix.trackViews();+});```-<Callout type="info">If you want to verify tracking locally during development, set `devMode: true` instead:```ts-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {devMode: true,-})+});```Remember to remove this before deploying to production.@@ -111,13 +109,13 @@ Enable automatic client-side error monitoring by adding `trackErrors()` to yourUpdate `plugins/swetrix.client.ts`:```ts-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export default defineNuxtPlugin(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- Swetrix.trackErrors()-})+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ Swetrix.trackErrors();+});```Errors will appear in the **Errors** tab of your project dashboard. See the [tracking script reference](/swetrix-js-reference#trackerrors) for options like `sampleRate` and `callback`.@@ -130,15 +128,15 @@ Custom events let you track specific user interactions — button clicks, form s```vue<script setup lang="ts">-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";function handleClick() {Swetrix.track({- ev: 'SIGNUP_CTA_CLICK',+ ev: "SIGNUP_CTA_CLICK",meta: {- location: 'navbar',+ location: "navbar",},- })+ });}</script>@@ -151,15 +149,15 @@ function handleClick() {```vue<script setup lang="ts">-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";function handleSubmit() {Swetrix.track({- ev: 'CONTACT_FORM_SUBMITTED',+ ev: "CONTACT_FORM_SUBMITTED",meta: {- source: 'support_page',+ source: "support_page",},- })+ });// ...submit logic}@@ -180,23 +178,23 @@ Create a reusable component for external links. Save as `components/TrackedLink.```vue<script setup lang="ts">-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";const props = withDefaults(defineProps<{- href: string- eventName?: string+ href: string;+ eventName?: string;}>(),{- eventName: 'OUTBOUND_CLICK',+ eventName: "OUTBOUND_CLICK",},-)+);function handleClick() {Swetrix.track({ev: props.eventName,meta: { url: props.href },- })+ });}</script>@@ -228,11 +226,12 @@ Rather than hardcoding your Project ID, use Nuxt's [runtime config](https://nuxtexport default defineNuxtConfig({runtimeConfig: {public: {- swetrixPid: '',+ swetrixPid: "",},},-})+});```+</Step><Step>### Set the environment variable@@ -240,14 +239,16 @@ export default defineNuxtConfig({```NUXT_PUBLIC_SWETRIX_PID=YOUR_PROJECT_ID```+</Step><Step>### Reference it in your plugin```ts-const config = useRuntimeConfig()-Swetrix.init(config.public.swetrixPid)+const config = useRuntimeConfig();+Swetrix.init(config.public.swetrixPid);```+</Step></Steps>diff --git a/docs/content/docs/integrations/preact.mdx b/docs/content/docs/integrations/preact.mdxindex 9b136c436..18c43c043 100644--- a/docs/content/docs/integrations/preact.mdx+++ b/docs/content/docs/integrations/preact.mdx@@ -22,17 +22,16 @@ If your app doesn't use client-side routing, you can initialise Swetrix once inOpen `src/index.tsx` (or `src/index.jsx`):```tsx-import { render } from 'preact'-import * as Swetrix from 'swetrix'-import App from './App'+import { render } from "preact";+import * as Swetrix from "swetrix";+import App from "./App";-Swetrix.init('YOUR_PROJECT_ID')-Swetrix.trackViews()+Swetrix.init("YOUR_PROJECT_ID");+Swetrix.trackViews();-render(<App />, document.getElementById('app')!)+render(<App />, document.getElementById("app")!);```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -65,20 +64,19 @@ To track visitors who have JavaScript disabled, add a noscript image pixel to yoBy default, Swetrix ignores `localhost` traffic. You can also explicitly disable it based on your environment:```tsx-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {disabled: import.meta.env.DEV, // Vite// disabled: process.env.NODE_ENV === 'development', // Preact CLI / webpack-})+});```-<Callout type="info">If you want to verify tracking locally during development, set `devMode: true` instead:```tsx-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {devMode: true,-})+});```Remember to remove this before deploying to production.@@ -96,17 +94,17 @@ Enable automatic client-side error monitoring by adding `trackErrors()` to yourUpdate your analytics setup:```tsx-import { useEffect } from 'preact/hooks'-import * as Swetrix from 'swetrix'+import { useEffect } from "preact/hooks";+import * as Swetrix from "swetrix";export default function App() {useEffect(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- Swetrix.trackErrors()- }, [])+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ Swetrix.trackErrors();+ }, []);- return <main>{/* your app */}</main>+ return <main>{/* your app */}</main>;}```@@ -119,40 +117,40 @@ Custom events let you track specific user interactions — button clicks, form s### Example: tracking button clicks```tsx-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export default function SignUpButton() {const handleClick = () => {Swetrix.track({- ev: 'SIGNUP_CTA_CLICK',+ ev: "SIGNUP_CTA_CLICK",meta: {- location: 'navbar',+ location: "navbar",},- })- }+ });+ };- return <button onClick={handleClick}>Sign up</button>+ return <button onClick={handleClick}>Sign up</button>;}```### Example: tracking form submissions```tsx-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export default function ContactForm() {const handleSubmit = (e: Event) => {- e.preventDefault()+ e.preventDefault();Swetrix.track({- ev: 'CONTACT_FORM_SUBMITTED',+ ev: "CONTACT_FORM_SUBMITTED",meta: {- source: 'support_page',+ source: "support_page",},- })+ });// ...submit logic- }+ };return (<form onSubmit={handleSubmit}>@@ -160,7 +158,7 @@ export default function ContactForm() {<textarea placeholder="How can we help?" required /><button type="submit">Send</button></form>- )+ );}```@@ -169,32 +167,32 @@ export default function ContactForm() {Create a reusable component for external links:```tsx-import * as Swetrix from 'swetrix'-import type { ComponentChildren } from 'preact'+import * as Swetrix from "swetrix";+import type { ComponentChildren } from "preact";interface TrackedLinkProps {- href: string- children: ComponentChildren- eventName?: string+ href: string;+ children: ComponentChildren;+ eventName?: string;}export default function TrackedLink({href,children,- eventName = 'OUTBOUND_CLICK',+ eventName = "OUTBOUND_CLICK",}: TrackedLinkProps) {const handleClick = () => {Swetrix.track({ev: eventName,meta: { url: href },- })- }+ });+ };return (<a href={href} target="_blank" rel="noopener noreferrer" onClick={handleClick}>{children}</a>- )+ );}```@@ -218,7 +216,7 @@ VITE_SWETRIX_PID=YOUR_PROJECT_ID``````tsx-Swetrix.init(import.meta.env.VITE_SWETRIX_PID)+Swetrix.init(import.meta.env.VITE_SWETRIX_PID);```**Preact CLI / webpack** — prefix with `PREACT_APP_`:@@ -228,7 +226,7 @@ PREACT_APP_SWETRIX_PID=YOUR_PROJECT_ID``````tsx-Swetrix.init(process.env.PREACT_APP_SWETRIX_PID!)+Swetrix.init(process.env.PREACT_APP_SWETRIX_PID!);```## Using React compat aliasesdiff --git a/docs/content/docs/integrations/prestashop.mdx b/docs/content/docs/integrations/prestashop.mdxindex 5261a075f..ad99f0804 100644--- a/docs/content/docs/integrations/prestashop.mdx+++ b/docs/content/docs/integrations/prestashop.mdx@@ -29,10 +29,10 @@ In the module's configuration, add the following code to the **header** (`<head>```html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -46,7 +46,6 @@ In the module's configuration, add the following code to the **header** (`<head>3. Save the module configuration.-<Callout type="warn">Don't forget to replace `YOUR_PROJECT_ID` with your actual Project ID from the Swetrix dashboard, otherwise tracking won't work.@@ -70,10 +69,10 @@ Paste the following just before the closing `</head>` section (or at the end of```html<script src="https://swetrix.org/swetrix.js" defer></script><script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -87,13 +86,11 @@ Paste the following just before the closing `</head>` section (or at the end of3. Save the file.-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the Swetrix dashboard.</Callout>-<Callout>Always use a **child theme** when editing template files. Changes to the parent theme will be lost when you update PrestaShop or the theme. To create a child theme, copy your theme folder, rename it, and update the `theme.yml` file with the new name and parent reference.@@ -109,7 +106,6 @@ If you don't see data, open your browser's developer tools (F12), check the **CoBeyond basic page views, you can track purchases and other e-commerce interactions as custom events using `swetrix.track()`. You can view these events and their metadata in the **Custom events** section of your Swetrix dashboard. Refer to the [tracking script reference](/swetrix-js-reference) for full API details.-<Callout type="info">Always **back up your theme** before editing template files.@@ -122,31 +118,30 @@ To track completed orders, add a script to PrestaShop's order confirmation page.```html{literal}<script>- document.addEventListener('DOMContentLoaded', function () {- if (typeof swetrix === 'undefined') return-{/literal}+ document.addEventListener('DOMContentLoaded', function () {+ if (typeof swetrix === 'undefined') return+ {/literal}-{if isset($order)}- swetrix.track({- ev: 'purchase',- meta: {- order_id: '{$order.details.reference}',- total: '{$order.totals.total.amount}',- currency: '{$order.totals.total.value|regex_replace:"/[^A-Z]/":""}',- items: '{$order.products|count}'- }- })-{/if}+ {if isset($order)}+ swetrix.track({+ ev: 'purchase',+ meta: {+ order_id: '{$order.details.reference}',+ total: '{$order.totals.total.amount}',+ currency: '{$order.totals.total.value|regex_replace:"/[^A-Z]/":""}',+ items: '{$order.products|count}'+ }+ })+ {/if}-{literal}- })+ {literal}+ })</script>{/literal}```PrestaShop uses the **Smarty** templating engine. The `{$variable}` syntax is processed server-side to inject order data, while `{literal}` blocks prevent Smarty from trying to parse the JavaScript code.-<Callout>The exact Smarty variables may differ depending on your PrestaShop version and theme. Check your theme's existing `order-confirmation.tpl` to see which variables are available.@@ -159,30 +154,29 @@ To track when a visitor adds a product to their cart, add a script to your produ```html{literal}<script>- document.addEventListener('DOMContentLoaded', function () {- var addToCartBtn = document.querySelector('.add-to-cart')- if (!addToCartBtn || typeof swetrix === 'undefined') return+ document.addEventListener("DOMContentLoaded", function () {+ var addToCartBtn = document.querySelector(".add-to-cart");+ if (!addToCartBtn || typeof swetrix === "undefined") return;- addToCartBtn.addEventListener('click', function () {- var nameEl = document.querySelector('h1[itemprop="name"]')- var priceEl = document.querySelector('[itemprop="price"]')- var qtyInput = document.querySelector('#quantity_wanted')+ addToCartBtn.addEventListener("click", function () {+ var nameEl = document.querySelector('h1[itemprop="name"]');+ var priceEl = document.querySelector('[itemprop="price"]');+ var qtyInput = document.querySelector("#quantity_wanted");swetrix.track({- ev: 'added_to_cart',+ ev: "added_to_cart",meta: {- name: nameEl ? nameEl.textContent.trim() : '',- price: priceEl ? priceEl.getAttribute('content') || priceEl.textContent.trim() : '',- quantity: qtyInput ? qtyInput.value : '1'- }- })- })- })+ name: nameEl ? nameEl.textContent.trim() : "",+ price: priceEl ? priceEl.getAttribute("content") || priceEl.textContent.trim() : "",+ quantity: qtyInput ? qtyInput.value : "1",+ },+ });+ });+ });</script>{/literal}```-<Callout>The `.add-to-cart` selector is standard in PrestaShop's default themes (Classic and similar). If your theme uses a different class or structure, adjust the selector to match your "Add to Cart" button.diff --git a/docs/content/docs/integrations/qwik.mdx b/docs/content/docs/integrations/qwik.mdxindex fb10a64d5..6023b91b0 100644--- a/docs/content/docs/integrations/qwik.mdx+++ b/docs/content/docs/integrations/qwik.mdx@@ -22,17 +22,17 @@ Swetrix must run in the browser. In Qwik, use `useVisibleTask$` to execute clienOpen `src/routes/layout.tsx` and add Swetrix initialisation:```tsx-import { component$, Slot, useVisibleTask$ } from '@builder.io/qwik'-import * as Swetrix from 'swetrix'+import { component$, Slot, useVisibleTask$ } from "@builder.io/qwik";+import * as Swetrix from "swetrix";export default component$(() => {useVisibleTask$(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- })+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ });- return <Slot />-})+ return <Slot />;+});```### Standalone Qwik (without Qwik City)@@ -55,7 +55,6 @@ export const App = component$(() => {})```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -80,19 +79,18 @@ To track visitors who have JavaScript disabled, add a noscript image pixel to yoBy default, Swetrix ignores `localhost` traffic. You can also explicitly disable it in development:```tsx-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {disabled: import.meta.env.DEV,-})+});```-<Callout type="info">If you want to verify tracking locally during development, set `devMode: true` instead:```tsx-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {devMode: true,-})+});```Remember to remove this before deploying to production.@@ -111,10 +109,10 @@ Update your root layout:```tsxuseVisibleTask$(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- Swetrix.trackErrors()-})+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ Swetrix.trackErrors();+});```Errors will appear in the **Errors** tab of your project dashboard. See the [tracking script reference](/swetrix-js-reference#trackerrors) for options like `sampleRate` and `callback`.@@ -126,33 +124,33 @@ Custom events let you track specific user interactions — button clicks, form s### Example: tracking button clicks```tsx-import { component$ } from '@builder.io/qwik'-import * as Swetrix from 'swetrix'+import { component$ } from "@builder.io/qwik";+import * as Swetrix from "swetrix";export const UpgradeButton = component$(() => {return (<buttononClick$={() => {Swetrix.track({- ev: 'UPGRADE_CTA_CLICK',+ ev: "UPGRADE_CTA_CLICK",meta: {- plan: 'pro',- location: 'pricing',+ plan: "pro",+ location: "pricing",},- })+ });}}>Upgrade to Pro</button>- )-})+ );+});```### Example: tracking form submissions```tsx-import { component$ } from '@builder.io/qwik'-import * as Swetrix from 'swetrix'+import { component$ } from "@builder.io/qwik";+import * as Swetrix from "swetrix";export const ContactForm = component$(() => {return (@@ -160,34 +158,34 @@ export const ContactForm = component$(() => {preventdefault:submitonSubmit$={() => {Swetrix.track({- ev: 'CONTACT_FORM_SUBMITTED',+ ev: "CONTACT_FORM_SUBMITTED",meta: {- source: 'support_page',+ source: "support_page",},- })+ });}}><input type="email" placeholder="[email protected]" required /><textarea placeholder="How can we help?" required /><button type="submit">Send</button></form>- )-})+ );+});```### Example: tracking outbound links```tsx-import { component$ } from '@builder.io/qwik'-import * as Swetrix from 'swetrix'+import { component$ } from "@builder.io/qwik";+import * as Swetrix from "swetrix";interface TrackedLinkProps {- href: string- eventName?: string+ href: string;+ eventName?: string;}export const TrackedLink = component$<TrackedLinkProps>(- ({ href, eventName = 'OUTBOUND_CLICK' }) => {+ ({ href, eventName = "OUTBOUND_CLICK" }) => {return (<ahref={href}@@ -197,14 +195,14 @@ export const TrackedLink = component$<TrackedLinkProps>(Swetrix.track({ev: eventName,meta: { url: href },- })+ });}}><Slot /></a>- )+ );},-)+);```### Event naming rules@@ -229,7 +227,7 @@ VITE_SWETRIX_PID=YOUR_PROJECT_ID**2. Use it in your layout:**```tsx-Swetrix.init(import.meta.env.VITE_SWETRIX_PID)+Swetrix.init(import.meta.env.VITE_SWETRIX_PID);```## Further readingdiff --git a/docs/content/docs/integrations/react.mdx b/docs/content/docs/integrations/react.mdxindex 40fff3db1..522470f6d 100644--- a/docs/content/docs/integrations/react.mdx+++ b/docs/content/docs/integrations/react.mdx@@ -22,22 +22,21 @@ If your app doesn't use client-side routing, you can initialise Swetrix once inOpen `src/main.tsx` (Vite) or `src/index.tsx` (CRA):```tsx-import React from 'react'-import ReactDOM from 'react-dom/client'-import * as Swetrix from 'swetrix'-import App from './App'+import React from "react";+import ReactDOM from "react-dom/client";+import * as Swetrix from "swetrix";+import App from "./App";-Swetrix.init('YOUR_PROJECT_ID')-Swetrix.trackViews()+Swetrix.init("YOUR_PROJECT_ID");+Swetrix.trackViews();-ReactDOM.createRoot(document.getElementById('root')!).render(+ReactDOM.createRoot(document.getElementById("root")!).render(<React.StrictMode><App /></React.StrictMode>,-)+);```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -70,20 +69,19 @@ To track visitors who have JavaScript disabled, add a noscript image pixel to yoBy default, Swetrix ignores `localhost` traffic. You can also explicitly disable it based on your environment:```tsx-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {disabled: import.meta.env.DEV, // Vite// disabled: process.env.NODE_ENV === 'development', // CRA-})+});```-<Callout type="info">If you want to verify tracking locally during development, set `devMode: true` instead:```tsx-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {devMode: true,-})+});```Remember to remove this before deploying to production.@@ -102,10 +100,10 @@ Update your analytics setup:```tsxuseEffect(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- Swetrix.trackErrors()-}, [])+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ Swetrix.trackErrors();+}, []);```Errors will appear in the **Errors** tab of your project dashboard. See the [tracking script reference](/swetrix-js-reference#trackerrors) for options like `sampleRate` and `callback`.@@ -117,40 +115,40 @@ Custom events let you track specific user interactions — button clicks, form s### Example: tracking button clicks```tsx-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export default function SignUpButton() {const handleClick = () => {Swetrix.track({- ev: 'SIGNUP_CTA_CLICK',+ ev: "SIGNUP_CTA_CLICK",meta: {- location: 'navbar',+ location: "navbar",},- })- }+ });+ };- return <button onClick={handleClick}>Sign up</button>+ return <button onClick={handleClick}>Sign up</button>;}```### Example: tracking form submissions```tsx-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export default function ContactForm() {const handleSubmit = (e: React.FormEvent) => {- e.preventDefault()+ e.preventDefault();Swetrix.track({- ev: 'CONTACT_FORM_SUBMITTED',+ ev: "CONTACT_FORM_SUBMITTED",meta: {- source: 'support_page',+ source: "support_page",},- })+ });// ...submit logic- }+ };return (<form onSubmit={handleSubmit}>@@ -158,7 +156,7 @@ export default function ContactForm() {<textarea placeholder="How can we help?" required /><button type="submit">Send</button></form>- )+ );}```@@ -167,31 +165,31 @@ export default function ContactForm() {Create a reusable component for external links:```tsx-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";interface TrackedLinkProps {- href: string- children: React.ReactNode- eventName?: string+ href: string;+ children: React.ReactNode;+ eventName?: string;}export default function TrackedLink({href,children,- eventName = 'OUTBOUND_CLICK',+ eventName = "OUTBOUND_CLICK",}: TrackedLinkProps) {const handleClick = () => {Swetrix.track({ev: eventName,meta: { url: href },- })- }+ });+ };return (<a href={href} target="_blank" rel="noopener noreferrer" onClick={handleClick}>{children}</a>- )+ );}```@@ -215,7 +213,7 @@ VITE_SWETRIX_PID=YOUR_PROJECT_ID``````tsx-Swetrix.init(import.meta.env.VITE_SWETRIX_PID)+Swetrix.init(import.meta.env.VITE_SWETRIX_PID);```**Create React App** — prefix with `REACT_APP_`:@@ -225,7 +223,7 @@ REACT_APP_SWETRIX_PID=YOUR_PROJECT_ID``````tsx-Swetrix.init(process.env.REACT_APP_SWETRIX_PID!)+Swetrix.init(process.env.REACT_APP_SWETRIX_PID!);```## Further readingdiff --git a/docs/content/docs/integrations/remix.mdx b/docs/content/docs/integrations/remix.mdxindex 2092267c8..9965ab25b 100644--- a/docs/content/docs/integrations/remix.mdx+++ b/docs/content/docs/integrations/remix.mdx@@ -22,16 +22,16 @@ Since Swetrix runs in the browser, you need a client-only component that initialCreate `app/components/Analytics.tsx`:```tsx-import { useEffect } from 'react'-import * as Swetrix from 'swetrix'+import { useEffect } from "react";+import * as Swetrix from "swetrix";export default function Analytics() {useEffect(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- }, [])+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ }, []);- return null+ return null;}```@@ -40,14 +40,8 @@ export default function Analytics() {Open `app/root.tsx` and render the `Analytics` component inside the `<body>`. Use Remix's `ClientOnly` approach — since Swetrix must run in the browser, wrap the import so it only loads client-side:```tsx-import {- Links,- Meta,- Outlet,- Scripts,- ScrollRestoration,-} from '@remix-run/react'-import Analytics from '~/components/Analytics'+import { Links, Meta, Outlet, Scripts, ScrollRestoration } from "@remix-run/react";+import Analytics from "~/components/Analytics";export default function App() {return (@@ -65,13 +59,12 @@ export default function App() {<Analytics /></body></html>- )+ );}```Swetrix guards against server-side execution internally, so the component is safe to render in the root route without extra checks.-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -96,19 +89,18 @@ To track visitors who have JavaScript disabled, add a noscript image pixel to yoBy default, Swetrix ignores `localhost` traffic. You can also explicitly disable it in development:```tsx-Swetrix.init('YOUR_PROJECT_ID', {- disabled: process.env.NODE_ENV === 'development',-})+Swetrix.init("YOUR_PROJECT_ID", {+ disabled: process.env.NODE_ENV === "development",+});```-<Callout type="info">If you want to verify tracking locally during development, set `devMode: true` instead:```tsx-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {devMode: true,-})+});```Remember to remove this before deploying to production.@@ -127,10 +119,10 @@ Update `app/components/Analytics.tsx`:```tsxuseEffect(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- Swetrix.trackErrors()-}, [])+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ Swetrix.trackErrors();+}, []);```Errors will appear in the **Errors** tab of your project dashboard. See the [tracking script reference](/swetrix-js-reference#trackerrors) for options like `sampleRate` and `callback`.@@ -142,20 +134,20 @@ Custom events let you track specific user interactions — button clicks, form s### Example: tracking button clicks```tsx-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export default function UpgradeButton() {const handleClick = () => {Swetrix.track({- ev: 'UPGRADE_CTA_CLICK',+ ev: "UPGRADE_CTA_CLICK",meta: {- plan: 'pro',- location: 'pricing',+ plan: "pro",+ location: "pricing",},- })- }+ });+ };- return <button onClick={handleClick}>Upgrade to Pro</button>+ return <button onClick={handleClick}>Upgrade to Pro</button>;}```@@ -164,56 +156,56 @@ export default function UpgradeButton() {Remix encourages server-side form handling via `action` functions. You can track submissions on the client before the form posts:```tsx-import { Form } from '@remix-run/react'-import * as Swetrix from 'swetrix'+import { Form } from "@remix-run/react";+import * as Swetrix from "swetrix";export default function WaitlistForm() {const handleSubmit = () => {Swetrix.track({- ev: 'WAITLIST_SIGNUP',+ ev: "WAITLIST_SIGNUP",meta: {- source: 'landing_page',+ source: "landing_page",},- })- }+ });+ };return (<Form method="post" onSubmit={handleSubmit}><input type="email" name="email" placeholder="[email protected]" required /><button type="submit">Join waitlist</button></Form>- )+ );}```### Example: tracking outbound links```tsx-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";interface TrackedLinkProps {- href: string- children: React.ReactNode- eventName?: string+ href: string;+ children: React.ReactNode;+ eventName?: string;}export default function TrackedLink({href,children,- eventName = 'OUTBOUND_CLICK',+ eventName = "OUTBOUND_CLICK",}: TrackedLinkProps) {const handleClick = () => {Swetrix.track({ev: eventName,meta: { url: href },- })- }+ });+ };return (<a href={href} target="_blank" rel="noopener noreferrer" onClick={handleClick}>{children}</a>- )+ );}```@@ -240,15 +232,15 @@ SWETRIX_PID=YOUR_PROJECT_ID```tsx// app/root.tsx-import { json } from '@remix-run/node'-import type { LoaderFunctionArgs } from '@remix-run/node'+import { json } from "@remix-run/node";+import type { LoaderFunctionArgs } from "@remix-run/node";export async function loader({ request }: LoaderFunctionArgs) {return json({ENV: {SWETRIX_PID: process.env.SWETRIX_PID,},- })+ });}```@@ -257,10 +249,10 @@ export async function loader({ request }: LoaderFunctionArgs) {In your root component, render the environment variables as a script tag:```tsx-import { useLoaderData } from '@remix-run/react'+import { useLoaderData } from "@remix-run/react";export default function App() {- const { ENV } = useLoaderData<typeof loader>()+ const { ENV } = useLoaderData<typeof loader>();return (<html lang="en">@@ -276,14 +268,14 @@ export default function App() {<Analytics /></body></html>- )+ );}```Then in your analytics component:```tsx-Swetrix.init(window.ENV.SWETRIX_PID)+Swetrix.init(window.ENV.SWETRIX_PID);```## Bypassing adblockers with a proxy@@ -293,33 +285,32 @@ Some adblockers may block requests to the Swetrix API domain. Remix apps are comIf your Remix app runs on a Node server, you can add a proxy route at `app/routes/sproxy.$.tsx`:```tsx-import type { LoaderFunctionArgs } from '@remix-run/node'+import type { LoaderFunctionArgs } from "@remix-run/node";export async function loader({ request }: LoaderFunctionArgs) {- const url = new URL(request.url)- const target = `https://api.swetrix.com/log${url.pathname.replace('/sproxy', '')}${url.search}`+ const url = new URL(request.url);+ const target = `https://api.swetrix.com/log${url.pathname.replace("/sproxy", "")}${url.search}`;return fetch(target, {method: request.method,headers: request.headers,- body: request.method !== 'GET' ? await request.text() : undefined,- })+ body: request.method !== "GET" ? await request.text() : undefined,+ });}export async function action({ request }: LoaderFunctionArgs) {- return loader({ request, params: {}, context: {} })+ return loader({ request, params: {}, context: {} });}```Then update your analytics initialisation:```tsx-Swetrix.init('YOUR_PROJECT_ID', {- apiURL: '/sproxy',-})+Swetrix.init("YOUR_PROJECT_ID", {+ apiURL: "/sproxy",+});```-<Callout>Use a generic route name instead of `/analytics` or `/log` — common names are blocked by adblockers.diff --git a/docs/content/docs/integrations/ruby-on-rails.mdx b/docs/content/docs/integrations/ruby-on-rails.mdxindex eed2ed50b..430d81206 100644--- a/docs/content/docs/integrations/ruby-on-rails.mdx+++ b/docs/content/docs/integrations/ruby-on-rails.mdx@@ -18,40 +18,37 @@ Open `app/views/layouts/application.html.erb` and add the Swetrix script inside```html<!DOCTYPE html><html>-<head>- <title><%= content_for(:title) || "My App" %></title>- <meta name="viewport" content="width=device-width, initial-scale=1">- <%= csrf_meta_tags %>- <%= csp_meta_tag %>- <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>- <%= javascript_importmap_tags %>-- <!-- Swetrix Analytics -->- <script src="https://swetrix.org/swetrix.js" defer></script>-</head>-<body>- <%= yield %>-- <!-- Swetrix Analytics -->- <script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })- </script>-- <noscript>- <img- src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"- alt=""- referrerpolicy="no-referrer-when-downgrade"- />- </noscript>-</body>+ <head>+ <title><%= content_for(:title) || "My App" %></title>+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= stylesheet_link_tag "application",+ "data-turbo-track": "reload" %> <%= javascript_importmap_tags %>++ <!-- Swetrix Analytics -->+ <script src="https://swetrix.org/swetrix.js" defer></script>+ </head>+ <body>+ <%= yield %>++ <!-- Swetrix Analytics -->+ <script>+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });+ </script>++ <noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"+ alt=""+ referrerpolicy="no-referrer-when-downgrade"+ />+ </noscript>+ </body></html>```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -88,12 +85,11 @@ And for the body initialisation:<% end %>```-<Callout type="info">During development, Swetrix ignores `localhost` traffic by default. If you want to verify tracking locally without changing your environment, you can temporarily set `devMode: true`:```js-swetrix.init('YOUR_PROJECT_ID', { devMode: true })+swetrix.init("YOUR_PROJECT_ID", { devMode: true });```Remember to remove this before deploying.@@ -157,11 +153,11 @@ Enable automatic client-side error monitoring by adding `trackErrors()` to the i```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- swetrix.trackErrors()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ swetrix.trackErrors();+ });</script>```@@ -176,22 +172,20 @@ Custom events let you track specific user interactions — form submissions, butTrack when users submit a sign-up form:```html-<%= form_with url: "/signup", id: "signup-form" do |f| %>- <%= f.email_field :email, placeholder: "[email protected]" %>- <%= f.submit "Sign up" %>-<% end %>+<%= form_with url: "/signup", id: "signup-form" do |f| %> <%= f.email_field :email, placeholder:+"[email protected]" %> <%= f.submit "Sign up" %> <% end %><script>- document.getElementById('signup-form')?.addEventListener('submit', function () {- if (typeof swetrix !== 'undefined') {+ document.getElementById("signup-form")?.addEventListener("submit", function () {+ if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'SIGNUP_FORM_SUBMITTED',+ ev: "SIGNUP_FORM_SUBMITTED",meta: {page: window.location.pathname,},- })+ });}- })+ });</script>```@@ -201,20 +195,20 @@ Track clicks on external links across your site. Add this to your layout file:```html<script>- document.addEventListener('DOMContentLoaded', function () {+ document.addEventListener("DOMContentLoaded", function () {document.querySelectorAll('a[href^="http"]').forEach(function (link) {if (link.hostname !== window.location.hostname) {- link.addEventListener('click', function () {- if (typeof swetrix !== 'undefined') {+ link.addEventListener("click", function () {+ if (typeof swetrix !== "undefined") {swetrix.track({- ev: 'OUTBOUND_CLICK',+ ev: "OUTBOUND_CLICK",meta: { url: link.href },- })+ });}- })+ });}- })- })+ });+ });</script>```@@ -242,10 +236,10 @@ bin/importmap pin swetrixThen use it in your JavaScript entry point (e.g. `app/javascript/application.js`):```javascript-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";-Swetrix.init('YOUR_PROJECT_ID')-Swetrix.trackViews()+Swetrix.init("YOUR_PROJECT_ID");+Swetrix.trackViews();```### With jsbundling (esbuild, webpack, rollup)@@ -259,10 +253,10 @@ yarn add swetrixThen import it in your JavaScript entry point:```javascript-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";-Swetrix.init('YOUR_PROJECT_ID')-Swetrix.trackViews()+Swetrix.init("YOUR_PROJECT_ID");+Swetrix.trackViews();```## Further readingdiff --git a/docs/content/docs/integrations/shopify.mdx b/docs/content/docs/integrations/shopify.mdxindex 3304a4366..c747d20d2 100644--- a/docs/content/docs/integrations/shopify.mdx+++ b/docs/content/docs/integrations/shopify.mdx@@ -22,10 +22,10 @@ Integrate Swetrix with your Shopify store to track page views, monitor user beha```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -39,13 +39,11 @@ Integrate Swetrix with your Shopify store to track page views, monitor user beha6. Click **Save**.-<Callout type="warn">Don't forget to replace `YOUR_PROJECT_ID` with your actual Project ID from the Swetrix dashboard, otherwise tracking won't work.</Callout>-<Callout>Theme updates may overwrite your changes. If you update your theme, check that the Swetrix snippet is still present in `theme.liquid`. Duplicating your theme before updating is a good precaution.@@ -59,7 +57,6 @@ After adding the script, visit your store and browse a few pages. Within a minutBeyond basic page views, you can track key e-commerce interactions as custom events. This involves adding small Liquid and JavaScript snippets to your theme files.-<Callout type="info">Always **back up your theme** before editing code. If you're not comfortable with Liquid templates, consider working with a Shopify developer.@@ -135,7 +132,6 @@ Add this script to your product template, below the product viewed snippet:{% endraw %}```-<Callout>Many Shopify themes add items to the cart via AJAX without a full page reload. If yours does, the `submit` listener above may not fire. In that case you'll need to hook into your theme's JavaScript cart events or use a [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to detect cart changes.@@ -181,8 +177,7 @@ Track confirmed purchases on the Shopify "Thank you" (order status) page.3. In the **Additional scripts** box, paste:```html-{% raw %}-{% if first_time_accessed %}+{% raw %} {% if first_time_accessed %}<script src="https://swetrix.org/swetrix.js" defer></script><script>document.addEventListener('DOMContentLoaded', function () {@@ -203,11 +198,9 @@ Track confirmed purchases on the Shopify "Thank you" (order status) page.})})</script>-{% endif %}-{% endraw %}+{% endif %} {% endraw %}```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual project ID. The order status page is hosted on a different domain, so the Swetrix script needs to be loaded again here.diff --git a/docs/content/docs/integrations/solidjs.mdx b/docs/content/docs/integrations/solidjs.mdxindex 43b78306e..2609c02b6 100644--- a/docs/content/docs/integrations/solidjs.mdx+++ b/docs/content/docs/integrations/solidjs.mdx@@ -24,16 +24,16 @@ SolidStart is the official meta-framework for SolidJS with file-based routing anCreate a new file at `src/components/Analytics.tsx`:```tsx-import { onMount } from 'solid-js'-import * as Swetrix from 'swetrix'+import { onMount } from "solid-js";+import * as Swetrix from "swetrix";export default function Analytics() {onMount(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- })+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ });- return null+ return null;}```@@ -44,25 +44,26 @@ export default function Analytics() {Open `src/app.tsx` and render the `Analytics` component inside the `<Router>`:```tsx-import { Router } from '@solidjs/router'-import { FileRoutes } from '@solidjs/start/router'-import Analytics from '~/components/Analytics'+import { Router } from "@solidjs/router";+import { FileRoutes } from "@solidjs/start/router";+import Analytics from "~/components/Analytics";export default function App() {return (- <Router root={(props) => (- <>- <Analytics />- {props.children}- </>- )}>+ <Router+ root={(props) => (+ <>+ <Analytics />+ {props.children}+ </>+ )}+ ><FileRoutes /></Router>- )+ );}```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -75,14 +76,14 @@ For a standalone SolidJS SPA without SolidStart, initialise Swetrix in your entrOpen `src/index.tsx`:```tsx-import { render } from 'solid-js/web'-import * as Swetrix from 'swetrix'-import App from './App'+import { render } from "solid-js/web";+import * as Swetrix from "swetrix";+import App from "./App";-Swetrix.init('YOUR_PROJECT_ID')-Swetrix.trackViews()+Swetrix.init("YOUR_PROJECT_ID");+Swetrix.trackViews();-render(() => <App />, document.getElementById('root')!)+render(() => <App />, document.getElementById("root")!);```### Noscript fallback (optional)@@ -108,19 +109,18 @@ To track visitors who have JavaScript disabled, add a noscript image pixel to yoBy default, Swetrix ignores `localhost` traffic. You can also explicitly disable it based on your environment:```tsx-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {disabled: import.meta.env.DEV,-})+});```-<Callout type="info">If you want to verify tracking locally during development, set `devMode: true` instead:```tsx-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {devMode: true,-})+});```Remember to remove this before deploying to production.@@ -139,10 +139,10 @@ Update your analytics component:```tsxonMount(() => {- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()- Swetrix.trackErrors()-})+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();+ Swetrix.trackErrors();+});```Errors will appear in the **Errors** tab of your project dashboard. See the [tracking script reference](/swetrix-js-reference#trackerrors) for options like `sampleRate` and `callback`.@@ -154,40 +154,40 @@ Custom events let you track specific user interactions — button clicks, form s### Example: tracking button clicks```tsx-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export default function SignUpButton() {const handleClick = () => {Swetrix.track({- ev: 'SIGNUP_CTA_CLICK',+ ev: "SIGNUP_CTA_CLICK",meta: {- location: 'hero',+ location: "hero",},- })- }+ });+ };- return <button onClick={handleClick}>Sign up</button>+ return <button onClick={handleClick}>Sign up</button>;}```### Example: tracking form submissions```tsx-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";export default function ContactForm() {const handleSubmit = (e: SubmitEvent) => {- e.preventDefault()+ e.preventDefault();Swetrix.track({- ev: 'CONTACT_FORM_SUBMITTED',+ ev: "CONTACT_FORM_SUBMITTED",meta: {- source: 'support_page',+ source: "support_page",},- })+ });// ...submit logic- }+ };return (<form onSubmit={handleSubmit}>@@ -195,7 +195,7 @@ export default function ContactForm() {<textarea placeholder="How can we help?" required /><button type="submit">Send</button></form>- )+ );}```@@ -221,7 +221,7 @@ VITE_SWETRIX_PID=YOUR_PROJECT_ID**2. Reference it in your analytics component:**```tsx-Swetrix.init(import.meta.env.VITE_SWETRIX_PID)+Swetrix.init(import.meta.env.VITE_SWETRIX_PID);```## Further readingdiff --git a/docs/content/docs/integrations/squarespace.mdx b/docs/content/docs/integrations/squarespace.mdxindex 0ef09ff2d..aabf25024 100644--- a/docs/content/docs/integrations/squarespace.mdx+++ b/docs/content/docs/integrations/squarespace.mdx@@ -30,10 +30,10 @@ In the **Footer** field, paste the following to initialise tracking:```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -49,7 +49,6 @@ In the **Footer** field, paste the following to initialise tracking:Click **Save** at the top of the Code Injection panel.-<Callout type="warn">Don't forget to replace `YOUR_PROJECT_ID` with your actual Project ID from the Swetrix dashboard, otherwise tracking won't work.@@ -59,7 +58,6 @@ Don't forget to replace `YOUR_PROJECT_ID` with your actual Project ID from the SAfter saving, open your Squarespace site in a new tab (or an incognito window) and browse a few pages. Within a minute you should see new pageviews appearing in your Swetrix dashboard.-<Callout type="info">The tracking script only runs on your live published site. You won't see analytics data while previewing pages inside the Squarespace editor.@@ -73,14 +71,14 @@ For example, to track newsletter sign-ups:```html<script>- document.addEventListener('DOMContentLoaded', function () {- var form = document.querySelector('.newsletter-block form')- if (!form || typeof swetrix === 'undefined') return-- form.addEventListener('submit', function () {- swetrix.track({ ev: 'newsletter_signup' })- })- })+ document.addEventListener("DOMContentLoaded", function () {+ var form = document.querySelector(".newsletter-block form");+ if (!form || typeof swetrix === "undefined") return;++ form.addEventListener("submit", function () {+ swetrix.track({ ev: "newsletter_signup" });+ });+ });</script>```diff --git a/docs/content/docs/integrations/sveltekit.mdx b/docs/content/docs/integrations/sveltekit.mdxindex cc27d247e..0f9956ed4 100644--- a/docs/content/docs/integrations/sveltekit.mdx+++ b/docs/content/docs/integrations/sveltekit.mdx@@ -14,6 +14,7 @@ After you sign up on Swetrix and create a new project, the only thing left is to```bashnpm install swetrix```+</Step><Step>### Create or update your layout file@@ -23,14 +24,14 @@ Make your layout file look like this:```html<script>- import { onMount } from 'svelte'- import { dev } from '$app/environment'- import * as Swetrix from 'swetrix'+ import { onMount } from "svelte";+ import { dev } from "$app/environment";+ import * as Swetrix from "swetrix";onMount(() => {- Swetrix.init('YOUR_PROJECT_ID', { devMode: dev, disabled: dev })- Swetrix.trackViews()- })+ Swetrix.init("YOUR_PROJECT_ID", { devMode: dev, disabled: dev });+ Swetrix.trackViews();+ });</script><!-- Your site's content gets injected here -->@@ -38,10 +39,10 @@ Make your layout file look like this:````trackViews()` automatically detects client-side route changes, so you only need to call it once.+</Step></Steps>-<Callout type="warn">It's very important not to forget to replace `YOUR_PROJECT_ID` with your actual Project ID you can find in the Dashboard, otherwise tracking won't work!diff --git a/docs/content/docs/integrations/thrivecart.mdx b/docs/content/docs/integrations/thrivecart.mdxindex 70043496b..64fa27f30 100644--- a/docs/content/docs/integrations/thrivecart.mdx+++ b/docs/content/docs/integrations/thrivecart.mdx@@ -23,15 +23,15 @@ Paste the following into the **header scripts** section:```html<script>(function () {- var s = document.createElement('script')- s.src = 'https://swetrix.org/swetrix.js'- s.defer = true+ var s = document.createElement("script");+ s.src = "https://swetrix.org/swetrix.js";+ s.defer = true;s.onload = function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- }- document.head.appendChild(s)- })()+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ };+ document.head.appendChild(s);+ })();</script><noscript>@@ -47,7 +47,6 @@ Paste the following into the **header scripts** section:Save your changes and visit your checkout page. Within a minute you should see pageviews appearing in your Swetrix dashboard.-<Callout type="warn">Don't forget to replace `YOUR_PROJECT_ID` with your actual Project ID from the Swetrix dashboard, otherwise tracking won't work.@@ -70,49 +69,49 @@ Paste the following into the success page header scripts:```html<script>(function () {- var EVENT_NAME = 'purchase'+ var EVENT_NAME = "purchase";var EVENT_META = {- product: 'Your Product Name',- value: '97.00',- currency: 'USD'- }- var PROJECT_ID = 'YOUR_PROJECT_ID'+ product: "Your Product Name",+ value: "97.00",+ currency: "USD",+ };+ var PROJECT_ID = "YOUR_PROJECT_ID";// Prevent duplicate events on page refresh- var storageKey = 'swx_' + EVENT_NAME + '_sent'+ var storageKey = "swx_" + EVENT_NAME + "_sent";try {- if (sessionStorage.getItem(storageKey) === '1') return+ if (sessionStorage.getItem(storageKey) === "1") return;} catch (e) {}function sendEvent() {- swetrix.track({ ev: EVENT_NAME, meta: EVENT_META })+ swetrix.track({ ev: EVENT_NAME, meta: EVENT_META });try {- sessionStorage.setItem(storageKey, '1')+ sessionStorage.setItem(storageKey, "1");} catch (e) {}}function waitForSwetrix(timeout) {- var start = Date.now()- ;(function poll() {- if (typeof swetrix !== 'undefined' && typeof swetrix.track === 'function') {- return sendEvent()+ var start = Date.now();+ (function poll() {+ if (typeof swetrix !== "undefined" && typeof swetrix.track === "function") {+ return sendEvent();}if (Date.now() - start < timeout) {- return setTimeout(poll, 150)+ return setTimeout(poll, 150);}- })()+ })();}// Load the Swetrix script- var s = document.createElement('script')- s.src = 'https://swetrix.org/swetrix.js'- s.defer = true+ var s = document.createElement("script");+ s.src = "https://swetrix.org/swetrix.js";+ s.defer = true;s.onload = function () {- swetrix.init(PROJECT_ID)- waitForSwetrix(5000)- }- document.head.appendChild(s)- })()+ swetrix.init(PROJECT_ID);+ waitForSwetrix(5000);+ };+ document.head.appendChild(s);+ })();</script>```@@ -120,21 +119,21 @@ Paste the following into the success page header scripts:Update the variables at the top of the script:-| Variable | Description |-| --- | --- |+| Variable | Description |+| ------------ | --------------------------------------------------------------------------------------------------------------------------------- || `EVENT_NAME` | The custom event name (e.g. `Purchase`, `Checkout Complete`). Can contain any characters with a maximum length of 256 characters. |-| `EVENT_META` | An object with event metadata. All values must be strings. |-| `PROJECT_ID` | Your Swetrix Project ID. |+| `EVENT_META` | An object with event metadata. All values must be strings. |+| `PROJECT_ID` | Your Swetrix Project ID. |The `EVENT_META` object can contain any key-value pairs relevant to your product. For example:```javascriptvar EVENT_META = {- product: 'Online Course — SEO Masterclass',- value: '197.00',- currency: 'USD',- plan: 'lifetime'-}+ product: "Online Course — SEO Masterclass",+ value: "197.00",+ currency: "USD",+ plan: "lifetime",+};```Refer to the [tracking script reference](/swetrix-js-reference) for details on `swetrix.track()` and the metadata constraints (max 20 keys, values must be primitives, total value length under 1000 characters).diff --git a/docs/content/docs/integrations/tilda.mdx b/docs/content/docs/integrations/tilda.mdxindex 716cef848..a0e280951 100644--- a/docs/content/docs/integrations/tilda.mdx+++ b/docs/content/docs/integrations/tilda.mdx@@ -26,10 +26,10 @@ In the **Before closing </body> tag** field, paste the following to initia```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -45,7 +45,6 @@ In the **Before closing </body> tag** field, paste the following to initiaClick **Save** and then **Publish** your site to apply the changes.-<Callout type="warn">Don't forget to replace `YOUR_PROJECT_ID` with your actual Project ID from the Swetrix dashboard, otherwise tracking won't work.@@ -55,7 +54,6 @@ Don't forget to replace `YOUR_PROJECT_ID` with your actual Project ID from the SAfter publishing, open your Tilda site in a new tab (or an incognito window) and browse a few pages. Within a minute you should see new pageviews appearing in your Swetrix dashboard.-<Callout type="info">The tracking script only runs on your published site. You won't see analytics data while previewing pages inside the Tilda editor.@@ -69,14 +67,14 @@ For example, to track form submissions:```html<script>- document.addEventListener('DOMContentLoaded', function () {- var form = document.querySelector('.t-form')- if (!form || typeof swetrix === 'undefined') return-- form.addEventListener('submit', function () {- swetrix.track({ ev: 'form_submit' })- })- })+ document.addEventListener("DOMContentLoaded", function () {+ var form = document.querySelector(".t-form");+ if (!form || typeof swetrix === "undefined") return;++ form.addEventListener("submit", function () {+ swetrix.track({ ev: "form_submit" });+ });+ });</script>```diff --git a/docs/content/docs/integrations/vitepress.mdx b/docs/content/docs/integrations/vitepress.mdxindex e374c6b34..5f322ccb9 100644--- a/docs/content/docs/integrations/vitepress.mdx+++ b/docs/content/docs/integrations/vitepress.mdx@@ -14,17 +14,14 @@ There are two ways to add Swetrix to a VitePress site: via the **config file** (Add the Swetrix tracking script to your `.vitepress/config.ts` (or `.js` / `.mts`):```ts-import { defineConfig } from 'vitepress'+import { defineConfig } from "vitepress";export default defineConfig({// ...your existing confighead: [+ ["script", { src: "https://swetrix.org/swetrix.js", defer: "" }],[- 'script',- { src: 'https://swetrix.org/swetrix.js', defer: '' },- ],- [- 'script',+ "script",{},`document.addEventListener('DOMContentLoaded', function () {swetrix.init('YOUR_PROJECT_ID')@@ -32,12 +29,11 @@ export default defineConfig({})`,],],-})+});```The empty string for `defer` is intentional — VitePress renders it as a boolean attribute (`<script defer>`).-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -54,19 +50,19 @@ npm install swetrixThen extend your VitePress theme to initialise Swetrix. Create or edit `.vitepress/theme/index.ts`:```ts-import DefaultTheme from 'vitepress/theme'-import type { Theme } from 'vitepress'-import * as Swetrix from 'swetrix'+import DefaultTheme from "vitepress/theme";+import type { Theme } from "vitepress";+import * as Swetrix from "swetrix";export default {extends: DefaultTheme,enhanceApp() {- if (typeof window === 'undefined') return+ if (typeof window === "undefined") return;- Swetrix.init('YOUR_PROJECT_ID')- Swetrix.trackViews()+ Swetrix.init("YOUR_PROJECT_ID");+ Swetrix.trackViews();},-} satisfies Theme+} satisfies Theme;````trackViews()` automatically detects client-side route changes, so you only need to call it once.@@ -80,12 +76,12 @@ export default defineConfig({head: [// ...your script tags[- 'noscript',+ "noscript",{},`<img src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID" alt="" referrerpolicy="no-referrer-when-downgrade" />`,],],-})+});```## SPA navigation@@ -99,19 +95,16 @@ By default, Swetrix ignores `localhost` traffic. If you want to be explicit abou**Option A — conditional `head` config:**```ts-import { defineConfig } from 'vitepress'+import { defineConfig } from "vitepress";-const isProd = process.env.NODE_ENV === 'production'+const isProd = process.env.NODE_ENV === "production";export default defineConfig({head: isProd? [+ ["script", { src: "https://swetrix.org/swetrix.js", defer: "" }],[- 'script',- { src: 'https://swetrix.org/swetrix.js', defer: '' },- ],- [- 'script',+ "script",{},`document.addEventListener('DOMContentLoaded', function () {swetrix.init('YOUR_PROJECT_ID')@@ -120,25 +113,24 @@ export default defineConfig({],]: [],-})+});```**Option B — `disabled` flag with the npm package:**```ts-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {disabled: import.meta.env.DEV,-})+});```-<Callout type="info">If you want to verify tracking locally during development, set `devMode: true` instead:```ts-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {devMode: true,-})+});```Remember to remove this before deploying to production.@@ -156,19 +148,19 @@ Enable automatic client-side error monitoring to capture unhandled JavaScript er**Option A — update the inline script in your config:**```js-document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- swetrix.trackErrors()-})+document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ swetrix.trackErrors();+});```**Option B — update your theme setup:**```ts-Swetrix.init('YOUR_PROJECT_ID')-Swetrix.trackViews()-Swetrix.trackErrors()+Swetrix.init("YOUR_PROJECT_ID");+Swetrix.trackViews();+Swetrix.trackErrors();```Errors will appear in the **Errors** tab of your project dashboard. See the [tracking script reference](/swetrix-js-reference#trackerrors) for options like `sampleRate` and `callback`.@@ -183,23 +175,23 @@ Track whether visitors find a page helpful:```vue<script setup lang="ts">-import { ref } from 'vue'-import { useRoute } from 'vitepress'-import * as Swetrix from 'swetrix'+import { ref } from "vue";+import { useRoute } from "vitepress";+import * as Swetrix from "swetrix";-const route = useRoute()-const submitted = ref(false)+const route = useRoute();+const submitted = ref(false);function sendFeedback(answer: string) {Swetrix.track({- ev: 'DOCS_FEEDBACK',+ ev: "DOCS_FEEDBACK",meta: {answer,path: route.path,},- })+ });- submitted.value = true+ submitted.value = true;}</script>@@ -221,23 +213,23 @@ Create a reusable component for external links. Save as `.vitepress/theme/compon```vue<script setup lang="ts">-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";const props = withDefaults(defineProps<{- href: string- eventName?: string+ href: string;+ eventName?: string;}>(),{- eventName: 'OUTBOUND_CLICK',+ eventName: "OUTBOUND_CLICK",},-)+);function handleClick() {Swetrix.track({ev: props.eventName,meta: { url: props.href },- })+ });}</script>diff --git a/docs/content/docs/integrations/vue.mdx b/docs/content/docs/integrations/vue.mdxindex 189ddbcbd..2990cdd1f 100644--- a/docs/content/docs/integrations/vue.mdx+++ b/docs/content/docs/integrations/vue.mdx@@ -22,17 +22,16 @@ If your app doesn't use client-side routing, you can initialise Swetrix once inOpen `src/main.ts` (or `src/main.js`):```ts-import { createApp } from 'vue'-import * as Swetrix from 'swetrix'-import App from './App.vue'+import { createApp } from "vue";+import * as Swetrix from "swetrix";+import App from "./App.vue";-Swetrix.init('YOUR_PROJECT_ID')-Swetrix.trackViews()+Swetrix.init("YOUR_PROJECT_ID");+Swetrix.trackViews();-createApp(App).mount('#app')+createApp(App).mount("#app");```-<Callout type="warn">Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.@@ -65,19 +64,18 @@ To track visitors who have JavaScript disabled, add a noscript image pixel to yoBy default, Swetrix ignores `localhost` traffic. You can also explicitly disable it based on your environment:```ts-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {disabled: import.meta.env.DEV,-})+});```-<Callout type="info">If you want to verify tracking locally during development, set `devMode: true` instead:```ts-Swetrix.init('YOUR_PROJECT_ID', {+Swetrix.init("YOUR_PROJECT_ID", {devMode: true,-})+});```Remember to remove this before deploying to production.@@ -95,9 +93,9 @@ Enable automatic client-side error monitoring by adding `trackErrors()` to yourUpdate your plugin:```ts-Swetrix.init('YOUR_PROJECT_ID')-Swetrix.trackViews()-Swetrix.trackErrors()+Swetrix.init("YOUR_PROJECT_ID");+Swetrix.trackViews();+Swetrix.trackErrors();```Errors will appear in the **Errors** tab of your project dashboard. See the [tracking script reference](/swetrix-js-reference#trackerrors) for options like `sampleRate` and `callback`.@@ -110,15 +108,15 @@ Custom events let you track specific user interactions — button clicks, form s```vue<script setup lang="ts">-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";function handleClick() {Swetrix.track({- ev: 'SIGNUP_CTA_CLICK',+ ev: "SIGNUP_CTA_CLICK",meta: {- location: 'navbar',+ location: "navbar",},- })+ });}</script>@@ -131,15 +129,15 @@ function handleClick() {```vue<script setup lang="ts">-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";function handleSubmit() {Swetrix.track({- ev: 'CONTACT_FORM_SUBMITTED',+ ev: "CONTACT_FORM_SUBMITTED",meta: {- source: 'support_page',+ source: "support_page",},- })+ });// ...submit logic}@@ -160,23 +158,23 @@ Create a reusable component for external links. Save as `src/components/TrackedL```vue<script setup lang="ts">-import * as Swetrix from 'swetrix'+import * as Swetrix from "swetrix";const props = withDefaults(defineProps<{- href: string- eventName?: string+ href: string;+ eventName?: string;}>(),{- eventName: 'OUTBOUND_CLICK',+ eventName: "OUTBOUND_CLICK",},-)+);function handleClick() {Swetrix.track({ev: props.eventName,meta: { url: props.href },- })+ });}</script>@@ -205,7 +203,7 @@ VITE_SWETRIX_PID=YOUR_PROJECT_ID``````ts-Swetrix.init(import.meta.env.VITE_SWETRIX_PID)+Swetrix.init(import.meta.env.VITE_SWETRIX_PID);```## Further readingdiff --git a/docs/content/docs/integrations/webflow.mdx b/docs/content/docs/integrations/webflow.mdxindex d0d370318..b67bc0c60 100644--- a/docs/content/docs/integrations/webflow.mdx+++ b/docs/content/docs/integrations/webflow.mdx@@ -3,13 +3,13 @@ title: Webflowslug: /webflow-integration----After you sign up on Swetrix and create a new project, the only thing left is to add it to your website.## Installation1. Log in to your Webflow account.2. Open up your project, go to the `Project Settings > Custom Code` section:+<img alt="Webflow screenshot" src="/docs/img/webflow-int.png" />3. In the `Head code` section you need to add the following:@@ -22,10 +22,10 @@ After you sign up on Swetrix and create a new project, the only thing left is to```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -37,7 +37,6 @@ After you sign up on Swetrix and create a new project, the only thing left is to</noscript>```-<Callout type="warn">It's very important not to forget to replace `YOUR_PROJECT_ID` with your actual Project ID you can find in the Dashboard, otherwise tracking won't work!@@ -49,7 +48,6 @@ After installing Swetrix tracking script, go to your website and visit some pageWithin a minute you should be able to see new pageviews being added to your project's dahsboard.-<Callout type="info">Custom scripts will only appear on the published Webflow site.diff --git a/docs/content/docs/integrations/weebly.mdx b/docs/content/docs/integrations/weebly.mdxindex f233dec44..e9cc852b8 100644--- a/docs/content/docs/integrations/weebly.mdx+++ b/docs/content/docs/integrations/weebly.mdx@@ -31,10 +31,10 @@ In the **Footer Code** field, paste the following:```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -50,7 +50,6 @@ In the **Footer Code** field, paste the following:Click **Save**, then **Publish** your site to apply the changes.-<Callout type="warn">Don't forget to replace `YOUR_PROJECT_ID` with your actual Project ID from the Swetrix dashboard, otherwise tracking won't work.@@ -60,7 +59,6 @@ Don't forget to replace `YOUR_PROJECT_ID` with your actual Project ID from the SAfter publishing, open your Weebly site in a new tab (or an incognito window) and browse a few pages. Within a minute you should see new pageviews appearing in your Swetrix dashboard.-<Callout type="info">The tracking script only runs on your published site. You won't see analytics data while previewing inside the Weebly editor.@@ -72,14 +70,14 @@ You can use `swetrix.track()` to capture custom interactions — button clicks,```html<script>- document.addEventListener('DOMContentLoaded', function () {- var form = document.querySelector('form')- if (!form || typeof swetrix === 'undefined') return-- form.addEventListener('submit', function () {- swetrix.track({ ev: 'form_submission' })- })- })+ document.addEventListener("DOMContentLoaded", function () {+ var form = document.querySelector("form");+ if (!form || typeof swetrix === "undefined") return;++ form.addEventListener("submit", function () {+ swetrix.track({ ev: "form_submission" });+ });+ });</script>```diff --git a/docs/content/docs/integrations/wix.mdx b/docs/content/docs/integrations/wix.mdxindex 0245a2afe..3bd960f4c 100644--- a/docs/content/docs/integrations/wix.mdx+++ b/docs/content/docs/integrations/wix.mdx@@ -25,10 +25,10 @@ After you sign up on Swetrix and create a new project, the only thing left is to```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -43,7 +43,6 @@ After you sign up on Swetrix and create a new project, the only thing left is to10. Select `Body - end` when asked where to place the code snippet.11. Click `Apply` again, and done!-<Callout type="warn">It's very important not to forget to replace `YOUR_PROJECT_ID` with your actual Project ID you can find in the Dashboard, otherwise tracking won't work!diff --git a/docs/content/docs/integrations/woocommerce.mdx b/docs/content/docs/integrations/woocommerce.mdxindex 2dd88826b..9570c7468 100644--- a/docs/content/docs/integrations/woocommerce.mdx+++ b/docs/content/docs/integrations/woocommerce.mdx@@ -11,7 +11,6 @@ Before adding e-commerce event tracking, make sure the Swetrix tracking script iYou'll also need access to your child theme's `functions.php` file or a custom site-specific plugin. All of the PHP snippets below should be placed there.-<Callout type="warn">Do **not** edit your parent theme's `functions.php` directly — those changes will be lost when the theme updates. Always use a [child theme](https://developer.wordpress.org/themes/advanced-topics/child-themes/) or a simple custom plugin.@@ -27,7 +26,6 @@ Beyond basic page views, you can track key e-commerce interactions as custom eveYou can view these events and their metadata in the **Custom events** section of your Swetrix dashboard. Refer to the [tracking script reference](/swetrix-js-reference) for full API details.-<Callout type="info">Always **back up your site** before editing theme files. If you're not comfortable editing PHP, consider working with a WordPress developer.@@ -128,7 +126,6 @@ function swetrix_track_ajax_add_to_cart() {}```-<Callout>The AJAX listener above sends limited product details because full product data isn't readily available client-side on archive pages. If you need richer metadata (name, price, SKU), you can output it as `data-*` attributes on the add-to-cart button using the `woocommerce_loop_add_to_cart_link` filter, then read those attributes in the JavaScript handler.@@ -214,7 +211,6 @@ function swetrix_track_purchase($order_id) {The `_swetrix_tracked` order meta flag ensures the purchase event only fires once, preventing duplicate tracking if the customer refreshes the thank-you page.-<Callout>The `meta` field accepts up to 20 keys and a combined value length of 1000 characters. Because of this limit, individual item details are condensed into a single `items` string (e.g. `SKU-001 x2, SKU-002 x1`). If you only need the item count rather than a breakdown, replace the `items` field with `item_count`.diff --git a/docs/content/docs/integrations/wordpress.mdx b/docs/content/docs/integrations/wordpress.mdxindex 782fe7b72..f67f6bf17 100644--- a/docs/content/docs/integrations/wordpress.mdx+++ b/docs/content/docs/integrations/wordpress.mdx@@ -12,16 +12,19 @@ After you sign up on Swetrix and create a new project, the only thing left is to### Log in to WordpressLog in to your Wordpress account.+</Step><Step>### Install a code injection pluginInstall a plugin for adding the code to your HTML, for instance the [Insert Headers and Footers plugin](https://wordpress.org/plugins/insert-headers-and-footers).+</Step><Step>### Open the Custom Code sectionOpen up your project, go to the `Project Settings > Custom Code` section.+</Step><Step>### Add the script to the header@@ -31,6 +34,7 @@ To the `Scripts in Header` section you need to add the following:```html<script src="https://swetrix.org/swetrix.js" defer></script>```+</Step><Step>### Add the initialisation to the footer@@ -39,10 +43,10 @@ In the `Scripts in Footer` section you need to add the following:```html<script>- document.addEventListener('DOMContentLoaded', function () {- swetrix.init('YOUR_PROJECT_ID')- swetrix.trackViews()- })+ document.addEventListener("DOMContentLoaded", function () {+ swetrix.init("YOUR_PROJECT_ID");+ swetrix.trackViews();+ });</script><noscript>@@ -53,10 +57,10 @@ In the `Scripts in Footer` section you need to add the following:/></noscript>```+</Step></Steps>-<Callout type="warn">It's very important not to forget to replace `YOUR_PROJECT_ID` with your actual Project ID you can find in the Dashboard, otherwise tracking won't work!diff --git a/docs/content/docs/introduction.mdx b/docs/content/docs/introduction.mdxindex 2883bd6a2..b927a14c8 100644--- a/docs/content/docs/introduction.mdx+++ b/docs/content/docs/introduction.mdx@@ -10,7 +10,8 @@ Swetrix is an open-source, lightweight, and privacy-focused web analytics platfoTrusted by thousands of websites worldwide, Swetrix is fully independent, self-funded, and [open source](https://github.com/Swetrix). Unlike traditional analytics tools, Swetrix doesn't use cookies and is fully compliant with GDPR, CCPA, and PECR.<Callout type="info">-New to web analytics? Swetrix is designed to be simple. You can be up and running in under 5 minutes — no technical expertise required.+ New to web analytics? Swetrix is designed to be simple. You can be up and running in under 5+ minutes — no technical expertise required.</Callout><img alt="Swetrix Dashboard" src="https://swetrix.com/assets/screenshot_dark.png" />@@ -32,27 +33,27 @@ Understand your visitors, traffic sources, and page views at a glance.</Card><Card title="Goal Conversions" href="/analytics-dashboard/goals">-Track signups, purchases, downloads, and other important actions.+ Track signups, purchases, downloads, and other important actions.</Card><Card title="Funnel Analysis" href="/analytics-dashboard/funnels">-Follow the visitor journey from landing page to conversion.+ Follow the visitor journey from landing page to conversion.</Card><Card title="Error Tracking" href="/error-tracking">-Monitor and debug JavaScript errors in real-time.+ Monitor and debug JavaScript errors in real-time.</Card><Card title="Revenue Tracking" href="/analytics-dashboard/revenue-tracking">-Attribute revenue to your marketing campaigns and traffic sources.+ Attribute revenue to your marketing campaigns and traffic sources.</Card><Card title="Stats API" href="/statistics-api">-Build custom dashboards and integrations with your analytics data.+ Build custom dashboards and integrations with your analytics data.</Card><Card title="Profiles & Sessions" href="/analytics-dashboard/profiles-and-sessions">-See individual user journeys and session-level behavior.+ See individual user journeys and session-level behavior.</Card><Card title="Self-hosting" href="/selfhosting/how-to">diff --git a/docs/content/docs/script-reference.mdx b/docs/content/docs/script-reference.mdxindex 0054d5f59..19bde5b93 100644--- a/docs/content/docs/script-reference.mdx+++ b/docs/content/docs/script-reference.mdx@@ -4,7 +4,6 @@ slug: /swetrix-js-referenceicon: FileCode----The Swetrix.js is a highly customisable tracking script. The following is a reference of all the available functions and options it provides.## init()@@ -20,13 +19,13 @@ It takes two arguments:Here's an example of how to use this function with all the available options:```javascript-swetrix.init('YOUR_PROJECT_ID', {+swetrix.init("YOUR_PROJECT_ID", {devMode: false,disabled: false,respectDNT: false,- apiURL: 'https://api.swetrix.com/log',- profileId: 'user-123',-})+ apiURL: "https://api.swetrix.com/log",+ profileId: "user-123",+});```| Name | Description | Default value |@@ -34,12 +33,11 @@ swetrix.init('YOUR_PROJECT_ID', {| devMode | When set to `true`, localhost events will be sent to server. | `false` || disabled | When set to true, the tracking library won't send any data to server.<br />Useful for development purposes when this value is set based on '.env' var. | `false` || respectDNT | By setting this flag to true, we will not collect ANY kind of data about the user with the DNT setting. <br />This setting is not true by default because our service anonymises all incoming data and does not pass it on to any third parties under any circumstances. | `false` |-| apiURL | If you use Swetrix Cloud, you don't need to change this parameter. If you're self-hosting Swetrix CE, you should put the URL of your API instance here, like `[BASE_URL]/backend/v1/log`. | `'https://api.swetrix.com/log'` |+| apiURL | If you use Swetrix Cloud, you don't need to change this parameter. If you're self-hosting Swetrix CE, you should put the URL of your API instance here, like `[BASE_URL]/backend/v1/log`. | `'https://api.swetrix.com/log'` || profileId | Optional profile ID for long-term user tracking (MAU/DAU). If set, it will be used for all pageviews and events unless overridden per-call. This allows you to track users across sessions and devices. | `undefined` |## track()-<Callout type="warn">It is important to ensure that no [Personal Data](https://en.wikipedia.org/wiki/Personal_data) that could identify a specific individual is transmitted in a metadata or custom event name field. Personally identifiable information (PII) is any information that can uniquely identify an individual, including full name, email address, phone number, credit card number, etc.All other information is anonymised.@@ -54,18 +52,18 @@ Here's an example of how to use this function with all the available options:```javascriptswetrix.track({- ev: 'YOUR_EVENT_NAME',+ ev: "YOUR_EVENT_NAME",unique: false,- profileId: 'user-123',-})+ profileId: "user-123",+});```-| Name | Description | Default value |-| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |-| ev | The event identifier you want to track. Can contain any characters (including spaces, unicode, etc.) with a maximum length of 256 characters. | REQUIRED PARAMETER |-| unique | If true, only 1 event with the same ID will be saved per user session.<br />The principle of this parameter is similar to page views and unique views. | `false` |-| meta | An object that contains event-related metadata. The values of the object must be a primitive type (string, number, boolean, null) which will be converted to a string, the maximum number of keys allowed is `20` and the total length of the values combined must be less than `1000` characters.<br /> This feature is useful if you want to track additional data about your custom events, for example the custom event name might be `Sign up` and the metadata might be `{ affiliate: 'Yes', footer: 'No' }`. | `{}` |-| profileId | Optional profile ID for long-term user tracking. Overrides the global profileId if set. | `undefined` |+| Name | Description | Default value |+| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |+| ev | The event identifier you want to track. Can contain any characters (including spaces, unicode, etc.) with a maximum length of 256 characters. | REQUIRED PARAMETER |+| unique | If true, only 1 event with the same ID will be saved per user session.<br />The principle of this parameter is similar to page views and unique views. | `false` |+| meta | An object that contains event-related metadata. The values of the object must be a primitive type (string, number, boolean, null) which will be converted to a string, the maximum number of keys allowed is `20` and the total length of the values combined must be less than `1000` characters.<br /> This feature is useful if you want to track additional data about your custom events, for example the custom event name might be `Sign up` and the metadata might be `{ affiliate: 'Yes', footer: 'No' }`. | `{}` |+| profileId | Optional profile ID for long-term user tracking. Overrides the global profileId if set. | `undefined` |## trackViews()@@ -100,16 +98,16 @@ swetrix.trackViews({hash: false,search: false,callback: undefined,-})+});```-| Name | Description | Default value |-| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- |-| unique | If true, only unique events will be saved. This param is useful when tracking single-page landing websites. | `false` |+| Name | Description | Default value |+| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- |+| unique | If true, only unique events will be saved. This param is useful when tracking single-page landing websites. | `false` || callback | A callback used to edit / prevent sending pageviews.<br />It accepts an object with pageview event data as a parameter which has the following structure: <br />lc: string \| undefined<br />tz: string \| undefined<br />ref: string \| undefined<br />so: string \| undefined<br />me: string \| undefined<br />ca: string \| undefined<br />meta: object \| undefined ("object" should contain string values only)<br />pg: string \| null \| undefined<br />profileId: string \| undefined<br /><br />The callback is supposed to return the edited payload or `false` to prevent sending the pageview. If `true` is returned, the payload will be sent as-is. | `undefined` |-| heartbeatOnBackground | Send Heartbeat requests when the website tab is not active in the browser.<br />Setting this to `true` means that users who opened your website in inactive browser tab or window will not be counted into users realtime statistics.<br />Setting this to true is usually useful for services like Spotify or Youtube. | `false` |-| hash | Set to `true` to enable hash-based routing. For example if you have pages like `/#/path` or want to track pages like `/path#hash`. | `false` |-| search | Set to `true` to enable search-based routing. For example if you have pages like `/path?search`. Although it's not recommended in most cases, you can set both `hash` and `search` to `true` at the same time, in which case the pageview event will be fired when either the hash or the search part of the URL changes (again, both the hash and the search are sent to the server). | `false` |+| heartbeatOnBackground | Send Heartbeat requests when the website tab is not active in the browser.<br />Setting this to `true` means that users who opened your website in inactive browser tab or window will not be counted into users realtime statistics.<br />Setting this to true is usually useful for services like Spotify or Youtube. | `false` |+| hash | Set to `true` to enable hash-based routing. For example if you have pages like `/#/path` or want to track pages like `/path#hash`. | `false` |+| search | Set to `true` to enable search-based routing. For example if you have pages like `/path?search`. Although it's not recommended in most cases, you can set both `hash` and `search` to `true` at the same time, in which case the pageview event will be fired when either the hash or the search part of the URL changes (again, both the hash and the search are sent to the server). | `false` |The `trackViews` function returns a `Promise` with an object with some methods allowing you to alter the behaviour of page tracking:@@ -136,22 +134,22 @@ Here are some examples of how to use this function:// Track a page view with a path '/hello'.swetrix.pageview({payload: {- pg: '/hello',+ pg: "/hello",},-})+});// Track a page view with a path '/hello' and some metadata.swetrix.pageview({payload: {- pg: '/hello',- lc: 'de-DE',+ pg: "/hello",+ lc: "de-DE",meta: {- author: 'Andrii',- type: 'story',+ author: "Andrii",+ type: "story",},- profileId: 'user-123',+ profileId: "user-123",},-})+});```## trackErrors()@@ -177,7 +175,7 @@ Here's an example of how to use this function with all the available options:swetrix.trackErrors({sampleRate: 1,callback: undefined,-})+});```| Name | Description | Default value |@@ -212,19 +210,19 @@ Here is an example of how to use this function:```javascriptswetrix.trackError({- name: 'ParseError',- message: 'Malformed input',+ name: "ParseError",+ message: "Malformed input",lineno: 1520,colno: 26,- filename: 'https://example.com/broken.js',+ filename: "https://example.com/broken.js",stackTrace: `Uncaught Error: Malformed inputat query (:10:11)at database (:6:5)at controller (:2:5)`,meta: {- level: 'Critical',+ level: "Critical",},-})+});```## getFeatureFlags()@@ -233,12 +231,13 @@ Fetches all feature flags for the project. Results are cached for 5 minutes by d```javascriptconst flags = await swetrix.getFeatureFlags({- profileId: 'user-123'-})+ profileId: "user-123",+});// Returns: { 'flag-1': true, 'flag-2': false }```Arguments:+1. `options` (optional): `{ profileId?: string }`2. `forceRefresh` (optional): `boolean` - If true, bypasses the cache.@@ -247,12 +246,13 @@ Arguments:Gets the value of a single feature flag.```javascript-const isEnabled = await swetrix.getFeatureFlag('new-feature', {- profileId: 'user-123'-})+const isEnabled = await swetrix.getFeatureFlag("new-feature", {+ profileId: "user-123",+});```Arguments:+1. `key`: `string` - The feature flag key.2. `options` (optional): `{ profileId?: string }`3. `defaultValue` (optional): `boolean` - Default value if flag not found (default: `false`).@@ -262,7 +262,7 @@ Arguments:Clears the cached feature flags and experiments, forcing a fresh fetch on the next call.```javascript-swetrix.clearFeatureFlagsCache()+swetrix.clearFeatureFlagsCache();```## getExperiments()@@ -271,12 +271,13 @@ Fetches all A/B test experiments for the project.```javascriptconst experiments = await swetrix.getExperiments({- profileId: 'user-123'-})+ profileId: "user-123",+});// Returns: { 'experiment-1': 'variant-a', 'experiment-2': 'control' }```Arguments:+1. `options` (optional): `{ profileId?: string }`2. `forceRefresh` (optional): `boolean` - If true, bypasses the cache.@@ -285,12 +286,13 @@ Arguments:Gets the variant key for a specific A/B test experiment.```javascript-const variant = await swetrix.getExperiment('checkout-redesign', {- profileId: 'user-123'-})+const variant = await swetrix.getExperiment("checkout-redesign", {+ profileId: "user-123",+});```Arguments:+1. `experimentId`: `string` - The experiment ID.2. `options` (optional): `{ profileId?: string }`3. `defaultVariant` (optional): `string | null` - Default variant if not found (default: `null`).@@ -300,7 +302,7 @@ Arguments:Gets the anonymous profile ID for the current visitor. If `profileId` was set via `init`, returns that. Otherwise, requests server to generate one from IP/UA hash. This ID can be used for revenue attribution.```javascript-const profileId = await swetrix.getProfileId()+const profileId = await swetrix.getProfileId();```## getSessionId()@@ -308,5 +310,5 @@ const profileId = await swetrix.getProfileId()Gets the current session ID for the visitor. Session IDs are generated server-side based on IP and user agent.```javascript-const sessionId = await swetrix.getSessionId()+const sessionId = await swetrix.getSessionId();```diff --git a/docs/content/docs/selfhosting/configuring.mdx b/docs/content/docs/selfhosting/configuring.mdxindex f7f78affa..de0ce7213 100644--- a/docs/content/docs/selfhosting/configuring.mdx+++ b/docs/content/docs/selfhosting/configuring.mdx@@ -3,7 +3,6 @@ title: Configuringslug: /selfhosting/configuring----<Callout>The easiest way to get started with Swetrix is by [using our cloud service](https://swetrix.com). We do all the dirty work for you: hosting, maintenance, backups, worldwide CDN, etc. Using Cloud you still own the data, you can export it or delete it at any time you want. By using Swetrix Cloud you support maintenance and development of the product, which eventually makes it better.@@ -13,11 +12,10 @@ The following environment variables are available for configuration:## Frontend (swetrix image)-| Variable | Default | Description |-| --------- | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- |+| Variable | Default | Description |+| ---------- | ------------------------ | --------------------------------------- || `BASE_URL` | `http://localhost:8080/` | Public URL of your Swetrix CE instance. |-<Callout type="info">The `BASE_URL` must be publicly reachable from your users' browsers. Do not set it to a Docker network hostname like `http://swetrix-api:8080` or `http://swetrix-api:5005`. Use a public domain or IP that resolves from the internet, for example `https://statistics.example.com`.@@ -27,13 +25,13 @@ The `BASE_URL` must be publicly reachable from your users' browsers. Do not set### Basic configuration-| Variable | Default | Description |-| -------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `SECRET_KEY_BASE` | _auto-generated by `configure.sh`_ | Secret used for auth keys and login sessions. Must be set. |-| `CLIENT_IP_HEADER` | `null` | Defines what header should be used to get IP address (e.g. cf-connecting-ip, x-real-ip, etc.). If not set, Swetrix will use `x-forwarded-for` header. |-| `DISABLE_REGISTRATION` | `true` | When set to `true` - Swetrix will disable user registration, except for the initial user. |-| `IP_GEOLOCATION_DB_PATH` | `` | Path to the `.mmdb` file for IP geolocation database. By default Swetrix uses IP to City Lite database by DB-IP. |-| `IS_PRIMARY_NODE` | `true` | You should not touch this variable unless you know what you are doing. It's used to spin off multiple API instances in a cluster, where only one of them will be primary. If changed to `false`, things like cron task manager will be disabled for this instance. |+| Variable | Default | Description |+| ------------------------ | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `SECRET_KEY_BASE` | _auto-generated by `configure.sh`_ | Secret used for auth keys and login sessions. Must be set. |+| `CLIENT_IP_HEADER` | `null` | Defines what header should be used to get IP address (e.g. cf-connecting-ip, x-real-ip, etc.). If not set, Swetrix will use `x-forwarded-for` header. |+| `DISABLE_REGISTRATION` | `true` | When set to `true` - Swetrix will disable user registration, except for the initial user. |+| `IP_GEOLOCATION_DB_PATH` | `` | Path to the `.mmdb` file for IP geolocation database. By default Swetrix uses IP to City Lite database by DB-IP. |+| `IS_PRIMARY_NODE` | `true` | You should not touch this variable unless you know what you are doing. It's used to spin off multiple API instances in a cluster, where only one of them will be primary. If changed to `false`, things like cron task manager will be disabled for this instance. |### Email configuration (SMTP)@@ -54,14 +52,14 @@ If you don't have an SMTP provider, some regular email providers offer this funcSwetrix Community Edition also supports OIDC authentication. To enable it, you need to set the following variables:-| Variable | Default | Description |-| -------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------- |-| `OIDC_ENABLED` | `false` | Must be set to `true` to enable OIDC authentication. |-| `OIDC_ONLY_AUTH` | `false` | If set to `true` - Swetrix will only allow users to authenticate via OIDC (i.e. regular login / registration form will not work). |-| `OIDC_DISCOVERY_URL` | | URL of the OIDC discovery endpoint, for example `https://example.com/.well-known/openid-configuration` |-| `OIDC_CLIENT_ID` | | OIDC client ID |-| `OIDC_CLIENT_SECRET` | | OIDC client secret |-| `OIDC_PROMPT` | `select_account` | OIDC prompt |+| Variable | Default | Description |+| -------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------- |+| `OIDC_ENABLED` | `false` | Must be set to `true` to enable OIDC authentication. |+| `OIDC_ONLY_AUTH` | `false` | If set to `true` - Swetrix will only allow users to authenticate via OIDC (i.e. regular login / registration form will not work). |+| `OIDC_DISCOVERY_URL` | | URL of the OIDC discovery endpoint, for example `https://example.com/.well-known/openid-configuration` |+| `OIDC_CLIENT_ID` | | OIDC client ID |+| `OIDC_CLIENT_SECRET` | | OIDC client secret |+| `OIDC_PROMPT` | `select_account` | OIDC prompt |## Redisdiff --git a/docs/content/docs/selfhosting/how-to.mdx b/docs/content/docs/selfhosting/how-to.mdxindex d98bee00d..0a9a40971 100644--- a/docs/content/docs/selfhosting/how-to.mdx+++ b/docs/content/docs/selfhosting/how-to.mdx@@ -5,7 +5,6 @@ slug: /selfhosting/how-toSwetrix supports self-hosting via Docker. You can run Swetrix on your own server or on a cloud provider of your choice. It's easy to set up and maintain, no need to be a Docker expert.-<Callout>The easiest way to get started with Swetrix is by [using our cloud service](https://swetrix.com). We do all the dirty work for you: hosting, maintenance, backups, worldwide CDN, etc. Using Cloud you still own the data, you can export it or delete it at any time you want. By using Swetrix Cloud you support maintenance and development of the product, which eventually makes it better.@@ -62,6 +61,7 @@ This script will also check if you have Docker and Docker Compose installed, and```The script will save the environment variables to a `.env` file in the repository directory. You can later change them manually if needed. Please refer to the [configuration section](/selfhosting/configuring) for more information.+</Step><Step>### Run the containers@@ -73,6 +73,7 @@ docker compose up -d```After you run this command, the following containers will be started:+- swetrix-fe - the frontend server (internal port 3000)- swetrix-api - the main API server (internal port 5005)- nginx-proxy - routes requests to the frontend and API (port 80 by default)@@ -80,6 +81,7 @@ After you run this command, the following containers will be started:- Clickhouse server for analytics and transactional dataAfter starting the container you can access the dashboard at `http://{host}:80` (or your configured reverse-proxy domain).+</Step></Steps>@@ -92,6 +94,7 @@ Usually, Swetrix releases come with database migrations that you'll need to applSwetrix v5 routes API requests through the web entrypoint. Instead of exposing 2 different services (web & backend) to the internet, you only expose one (the web endpoint) and route API requests internally.The default routing is:+- Frontend: /- API: /backend/ (proxied to swetrix-api)@@ -111,25 +114,27 @@ If you use another reverse proxy in front of Swetrix (for example for TLS terminIf you are already using Traefik, you can omit the nginx-proxy service and route requests directly to the Swetrix containers by path.swetrix-fe labels:+```yaml- - traefik.enable=true- - traefik.http.routers.swetrix_fe.rule=Host(`analytics.example.com`) && PathPrefix(`/`)- - traefik.http.routers.swetrix_fe.entrypoints=https- - traefik.http.routers.swetrix_fe.tls=true- - traefik.http.routers.swetrix_fe.priority=1- - traefik.http.services.swetrix_fe.loadbalancer.server.port=3000+- traefik.enable=true+- traefik.http.routers.swetrix_fe.rule=Host(`analytics.example.com`) && PathPrefix(`/`)+- traefik.http.routers.swetrix_fe.entrypoints=https+- traefik.http.routers.swetrix_fe.tls=true+- traefik.http.routers.swetrix_fe.priority=1+- traefik.http.services.swetrix_fe.loadbalancer.server.port=3000```swetrix-api labels:+```yaml- - traefik.enable=true- - traefik.http.routers.swetrix_be.rule=Host(`analytics.example.com`) && PathPrefix(`/backend/`)- - traefik.http.routers.swetrix_be.entrypoints=https- - traefik.http.routers.swetrix_be.tls=true- - traefik.http.routers.swetrix_be.priority=100- - traefik.http.middlewares.swetrix_be_strip.stripprefix.prefixes=/backend- - traefik.http.routers.swetrix_be.middlewares=swetrix_be_strip- - traefik.http.services.swetrix_be.loadbalancer.server.port=5005+- traefik.enable=true+- traefik.http.routers.swetrix_be.rule=Host(`analytics.example.com`) && PathPrefix(`/backend/`)+- traefik.http.routers.swetrix_be.entrypoints=https+- traefik.http.routers.swetrix_be.tls=true+- traefik.http.routers.swetrix_be.priority=100+- traefik.http.middlewares.swetrix_be_strip.stripprefix.prefixes=/backend+- traefik.http.routers.swetrix_be.middlewares=swetrix_be_strip+- traefik.http.services.swetrix_be.loadbalancer.server.port=5005```</Tab>diff --git a/docs/content/docs/selfhosting/meta.json b/docs/content/docs/selfhosting/meta.jsonindex e210849e3..1fae29ec7 100644--- a/docs/content/docs/selfhosting/meta.json+++ b/docs/content/docs/selfhosting/meta.json@@ -1,7 +1,4 @@{"title": "Self-hosting",- "pages": [- "how-to",- "configuring"- ]+ "pages": ["how-to", "configuring"]}diff --git a/docs/content/docs/sitesettings/annotations.mdx b/docs/content/docs/sitesettings/annotations.mdxindex 71998a509..46dfad61a 100644--- a/docs/content/docs/sitesettings/annotations.mdx+++ b/docs/content/docs/sitesettings/annotations.mdx@@ -3,7 +3,6 @@ title: Annotationsslug: /annotations----Annotations allow you to mark specific dates on your analytics charts with notes. This is useful for tracking how real-world events—like a new marketing campaign, a product launch, or a server outage—correlate with changes in your traffic or performance data.### Creating an annotation@@ -14,7 +13,10 @@ You can create an annotation directly from any time-series chart on your dashboa2. **Right-click** on the specific date point on the chart where you want to add a note.3. Select **Add annotation** from the context menu.-<img alt="Chart context menu with Add Annotation option" src="/docs/img/sitesettings/annotation-create-modal.png" />+<img+ alt="Chart context menu with Add Annotation option"+ src="/docs/img/sitesettings/annotation-create-modal.png"+/>A modal will appear where you can enter the details:diff --git a/docs/content/docs/sitesettings/embed-your-analytics-dashboard-into-your-website.mdx b/docs/content/docs/sitesettings/embed-your-analytics-dashboard-into-your-website.mdxindex 5a6541530..6ff1dd00a 100644--- a/docs/content/docs/sitesettings/embed-your-analytics-dashboard-into-your-website.mdx+++ b/docs/content/docs/sitesettings/embed-your-analytics-dashboard-into-your-website.mdx@@ -3,7 +3,6 @@ title: Embed your analytics dashboard into your websiteslug: /how-to-embed----You can embed your Swetrix analytics dashboard into any other website using an iframe. This is useful if you're building a custom admin panel, a dashboard for your customers or just want to show your stats to your visitors.<Steps>@@ -11,6 +10,7 @@ You can embed your Swetrix analytics dashboard into any other website using an i### Get your sharable linkFirst, you need to find the sharable link to your dashboard. You can get it in your [site settings](/how-to-access-site-settings) page. For people to be able to access your dashboard, you need to make it public or password-protected.+</Step><Step>### Write the HTML embed code@@ -25,11 +25,13 @@ Now you need to write the HTML code for the iframe. You can do this in any texttitle="Test"></iframe>```+</Step><Step>### Paste the code into your websiteNow you can paste the code into your website's HTML. You can put it anywhere you want, but it's usually best to put it in a dedicated page or section.+</Step></Steps>diff --git a/docs/content/docs/sitesettings/get-analytics-email-reports.mdx b/docs/content/docs/sitesettings/get-analytics-email-reports.mdxindex 40ebc6042..fe5636ef4 100644--- a/docs/content/docs/sitesettings/get-analytics-email-reports.mdx+++ b/docs/content/docs/sitesettings/get-analytics-email-reports.mdx@@ -3,7 +3,6 @@ title: Get analytics email reportsslug: /get-analytics-email-reports----You can send regular email reports to your team or clients to keep them updated on your website's traffic. You can set up the frequency of the reports and the recipients.### How to set up email reports@@ -14,7 +13,10 @@ You can send regular email reports to your team or clients to keep them updated4. Enter the email address of the recipient. They don't necessarily need to have a Swetrix account.5. Select the frequency of the reports: quarterly, monthly, weekly, or daily.-<img alt="Settings from the Dashboard page" src="/docs/img/sitesettings/add_email_subscribers.png" />+<img+ alt="Settings from the Dashboard page"+ src="/docs/img/sitesettings/add_email_subscribers.png"+/>### How to remove users from the email reportsdiff --git a/docs/content/docs/sitesettings/get-traffic-alerts.mdx b/docs/content/docs/sitesettings/get-traffic-alerts.mdxindex 88d425c22..855d5551c 100644--- a/docs/content/docs/sitesettings/get-traffic-alerts.mdx+++ b/docs/content/docs/sitesettings/get-traffic-alerts.mdx@@ -3,7 +3,6 @@ title: Get traffic alertsslug: /get-traffic-alerts----You can set up alerts to get notified when your website's traffic exceeds a certain threshold, or when a certain custom event occurs (like sale, or a signup). You can also set up alerts to be notified when there are client-side errors on your website.You can set up integrations with Telegram, Slack or Discord to get alert notifications in real-time there.diff --git a/docs/content/docs/sitesettings/how-to-access-site-settings.mdx b/docs/content/docs/sitesettings/how-to-access-site-settings.mdxindex 5bc45298c..4e4ed848e 100644--- a/docs/content/docs/sitesettings/how-to-access-site-settings.mdx+++ b/docs/content/docs/sitesettings/how-to-access-site-settings.mdx@@ -3,7 +3,6 @@ title: How to access site settingsslug: /how-to-access-site-settings----You can access your site settings in two ways:<Tabs items={["From the dashboard", "From the analytics page"]}>@@ -11,14 +10,20 @@ You can access your site settings in two ways:Click on the 'Settings' icon in the top right corner of site on the dashboard page.-<img alt="Settings from the Dashboard page" src="/docs/img/sitesettings/settings_from_dashboard.png" />+<img+ alt="Settings from the Dashboard page"+ src="/docs/img/sitesettings/settings_from_dashboard.png"+/></Tab><Tab value="From the analytics page">Click on the 'Settings' tab in the top navigation bar of your site's analytics page.-<img alt="Settings from the sites analytics page" src="/docs/img/sitesettings/settings_from_project.png" />+<img+ alt="Settings from the sites analytics page"+ src="/docs/img/sitesettings/settings_from_project.png"+/></Tab></Tabs>diff --git a/docs/content/docs/sitesettings/how-to-invite-users-to-your-website.mdx b/docs/content/docs/sitesettings/how-to-invite-users-to-your-website.mdxindex 56d008b84..430dd463e 100644--- a/docs/content/docs/sitesettings/how-to-invite-users-to-your-website.mdx+++ b/docs/content/docs/sitesettings/how-to-invite-users-to-your-website.mdx@@ -3,12 +3,10 @@ title: How to invite users to your websiteslug: /how-to-invite-users-to-your-website----Swetrix allows you to invite other people to your website. This is useful if you want to give access to your team, clients or other people without sharing your login credentials.You can invite any person to your website, but they need to have a Swetrix account. At the same time, they don't necessarily need to have a paid subscription to be invited to and access your website.-<Callout type="info">If you want to share your dashboard without requiring the other person to have a Swetrix account, you can password-protect your dashboard and share the password with them.@@ -54,7 +52,6 @@ To transfer ownership, navigate to your site settings, click on the "Transfer prYou will receive an email to confirm the transfer. Once you confirm it, the other person will become the owner of the website and will be responsible for billing.-<Callout>You can only transfer ownership to someone who is registered on Swetrix with the same email address you're transferring the website to.diff --git a/docs/content/docs/sitesettings/reset-sites-data.mdx b/docs/content/docs/sitesettings/reset-sites-data.mdxindex cf5ef8e26..b3a3ee603 100644--- a/docs/content/docs/sitesettings/reset-sites-data.mdx+++ b/docs/content/docs/sitesettings/reset-sites-data.mdx@@ -3,10 +3,8 @@ title: Reset your site's dataslug: /reset-sites-data----On your [site settings](/how-to-access-site-settings) page, you can reset your site's data. This will delete all analytics data, but keep your settings and site ID intact.-<Callout type="warn">This action is irreversible. Once you reset your site's data, all analytics data will be permanently deleted and cannot be recovered.diff --git a/docs/content/docs/sitesettings/transfer-ownership.mdx b/docs/content/docs/sitesettings/transfer-ownership.mdxindex 98537f085..f50531300 100644--- a/docs/content/docs/sitesettings/transfer-ownership.mdx+++ b/docs/content/docs/sitesettings/transfer-ownership.mdx@@ -3,7 +3,6 @@ title: How to transfer ownership of your websiteslug: /how-to-transfer-ownership-of-your-website----Swetrix lets you hand over control of a website (project) to another account.This is useful for freelancers, consultants, and agencies: you can set everything up - tracking code, custom events, spike alerts, etc. and then transfer project to the client.diff --git a/docs/content/docs/troubleshooting.mdx b/docs/content/docs/troubleshooting.mdxindex 2e8b35560..f7b2194f9 100644--- a/docs/content/docs/troubleshooting.mdx+++ b/docs/content/docs/troubleshooting.mdx@@ -4,7 +4,6 @@ slug: /troubleshootingicon: Wrench----After you [installed](/install-script) the Swetrix tracking script on your website, you should check if the integration is working properly. Visit your Swetrix dashboard, if you see the charts and numbers, then everything is working as expected. Enjoy!But if there is no data to display, or your visit is not counted, there might be something wrong with your integration. Read below to find out how to troubleshoot the most common issues.@@ -20,21 +19,25 @@ You should also check the "Network" tab to see if the script is loaded correctly### Open your websiteOpen the website you installed Swetrix script on.+</Step><Step>### Open DevToolsOpen the developer tools in your browser, you can do this by pressing `F12` for Chrome and Firefox, or `Ctrl + Shift + C` for Safari (alternatively, right-click anywhere on the page and press the "Inspect" button).+</Step><Step>### Check the Network tabClick on the "Network" tab in the developer tools (it will be empty at first, so you need to reload the page).+</Step><Step>### Look for Swetrix requestsSearch for `swetrix` related requests in the list of requests. You should see a bunch of POST requests to `api.swetrix.com`, and the status of these requests should be `201`.+</Step></Steps>@@ -52,22 +55,31 @@ In case you don't see any visits even after a delay, make sure you don't have an## Common issues and how to fix them<Accordions>-<Accordion title="Incorrect Project ID">-Make sure that you entered a correct Project ID in the script configuration. Sometimes mistype their Project IDs in the integration or use the wrong ID (for example, an API key). You can find your Project ID on the Project Settings page in dashboard.-</Accordion>-<Accordion title="Content Security Policy (CSP) blocking Swetrix">-If you set up CSP on your site, make sure to add Swetrix to the list of allowed domains. The simplest way to do this is `Content-Security-Policy: default-src 'self' *.swetrix.com *.swetrix.org`, but we recommend you to read more about CSP and set it up properly.-</Accordion>-<Accordion title="Testing on localhost">-By default, Swetrix doesn't track any events on localhost to prevent developers from polluting their data with test events. If you want to test your integration on localhost, you can enable the `devMode` option in the [script configuration](/swetrix-js-reference#init).-</Accordion>-<Accordion title="Site caching issues">-If you use caching on your site, make sure to purge the cache after you install Swetrix script, to ensure you're loading the latest version of your site.-</Accordion>-<Accordion title="Allowed domains misconfigured">-If you set up allowed domains in the Project settings, you might have misspelled your domain name or added a `www.` prefix to it while your site does not use it (or vice versa).-</Accordion>-<Accordion title="Using an SPA or similar framework">-You might have set up the script improperly. Generally, we recommend using [Swetrix via NPM](/install-script#install-swetrix-via-npm) for such application.-</Accordion>+ <Accordion title="Incorrect Project ID">+ Make sure that you entered a correct Project ID in the script configuration. Sometimes mistype+ their Project IDs in the integration or use the wrong ID (for example, an API key). You can find+ your Project ID on the Project Settings page in dashboard.+ </Accordion>+ <Accordion title="Content Security Policy (CSP) blocking Swetrix">+ If you set up CSP on your site, make sure to add Swetrix to the list of allowed domains. The+ simplest way to do this is `Content-Security-Policy: default-src 'self' *.swetrix.com+ *.swetrix.org`, but we recommend you to read more about CSP and set it up properly.+ </Accordion>+ <Accordion title="Testing on localhost">+ By default, Swetrix doesn't track any events on localhost to prevent developers from polluting+ their data with test events. If you want to test your integration on localhost, you can enable+ the `devMode` option in the [script configuration](/swetrix-js-reference#init).+ </Accordion>+ <Accordion title="Site caching issues">+ If you use caching on your site, make sure to purge the cache after you install Swetrix script,+ to ensure you're loading the latest version of your site.+ </Accordion>+ <Accordion title="Allowed domains misconfigured">+ If you set up allowed domains in the Project settings, you might have misspelled your domain+ name or added a `www.` prefix to it while your site does not use it (or vice versa).+ </Accordion>+ <Accordion title="Using an SPA or similar framework">+ You might have set up the script improperly. Generally, we recommend using [Swetrix via+ NPM](/install-script#install-swetrix-via-npm) for such application.+ </Accordion></Accordions>diff --git a/docs/lib/source.ts b/docs/lib/source.tsindex 599148fe4..343ca86b5 100644--- a/docs/lib/source.ts+++ b/docs/lib/source.ts@@ -1,73 +1,62 @@-import { docs } from 'fumadocs-mdx:collections/server';-import { loader } from 'fumadocs-core/source';-import { createElement } from 'react';-import { Icon } from '@/components/Icon';+import { docs } from "fumadocs-mdx:collections/server";+import { loader } from "fumadocs-core/source";+import { createElement } from "react";+import { Icon } from "@/components/Icon";const SLUG_MAP: Record<string, string[]> = {- 'introduction': [],+ introduction: [],// Root files with custom slugs- 'add-script': ['install-script'],- 'script-reference': ['swetrix-js-reference'],- 'integration-guides': ['integrations'],+ "add-script": ["install-script"],+ "script-reference": ["swetrix-js-reference"],+ "integration-guides": ["integrations"],// Integration special cases- 'integrations/google-tag-manager': ['gtm-integration'],- 'integrations/google-search-console': ['integrations', 'google-search-console'],+ "integrations/google-tag-manager": ["gtm-integration"],+ "integrations/google-search-console": ["integrations", "google-search-console"],// API files → flat URLs- 'api/stats': ['statistics-api'],- 'api/events': ['events-api'],- 'api/admin': ['admin-api'],+ "api/stats": ["statistics-api"],+ "api/events": ["events-api"],+ "api/admin": ["admin-api"],// Site settings → flat URLs- 'sitesettings/how-to-access-site-settings': ['how-to-access-site-settings'],- 'sitesettings/project-configuration': ['project-configuration-and-security'],- 'sitesettings/how-to-invite-users-to-your-website': [- 'how-to-invite-users-to-your-website',- ],- 'sitesettings/transfer-ownership': [- 'how-to-transfer-ownership-of-your-website',- ],- 'sitesettings/embed-your-analytics-dashboard-into-your-website': [- 'how-to-embed',- ],- 'sitesettings/get-analytics-email-reports': ['get-analytics-email-reports'],- 'sitesettings/get-traffic-alerts': ['get-traffic-alerts'],- 'sitesettings/reset-sites-data': ['reset-sites-data'],- 'sitesettings/annotations': ['annotations'],+ "sitesettings/how-to-access-site-settings": ["how-to-access-site-settings"],+ "sitesettings/project-configuration": ["project-configuration-and-security"],+ "sitesettings/how-to-invite-users-to-your-website": ["how-to-invite-users-to-your-website"],+ "sitesettings/transfer-ownership": ["how-to-transfer-ownership-of-your-website"],+ "sitesettings/embed-your-analytics-dashboard-into-your-website": ["how-to-embed"],+ "sitesettings/get-analytics-email-reports": ["get-analytics-email-reports"],+ "sitesettings/get-traffic-alerts": ["get-traffic-alerts"],+ "sitesettings/reset-sites-data": ["reset-sites-data"],+ "sitesettings/annotations": ["annotations"],// Account settings → mixed flat/nested URLs- 'accountsettings/two-factor-authentication': [- 'settings',- '2-factor-authentication',- ],- 'accountsettings/teams-and-integrations': ['teams-api-integrations'],- 'accountsettings/api-keys': ['settings', 'api-keys'],- 'accountsettings/email-reports': ['email-reports'],- 'accountsettings/change-email': ['settings', 'change-email'],- 'accountsettings/change-password': ['settings', 'change-password'],- 'accountsettings/delete-account': ['settings', 'delete-account'],- 'accountsettings/other-settings': ['settings', 'other-settings'],+ "accountsettings/two-factor-authentication": ["settings", "2-factor-authentication"],+ "accountsettings/teams-and-integrations": ["teams-api-integrations"],+ "accountsettings/api-keys": ["settings", "api-keys"],+ "accountsettings/email-reports": ["email-reports"],+ "accountsettings/change-email": ["settings", "change-email"],+ "accountsettings/change-password": ["settings", "change-password"],+ "accountsettings/delete-account": ["settings", "delete-account"],+ "accountsettings/other-settings": ["settings", "other-settings"],// Billing → flat URLs- 'billing/upgrade-from-trial': [- 'upgrade-from-trial-to-a-paid-subscription',- ],- 'billing/exceeding-plan-limits': ['exceeding-plan-limits'],- 'billing/update-subscription': ['update-your-subscription'],- 'billing/cancel-subscription': ['cancel-your-subscription'],- 'billing/faq': ['billing-faq'],+ "billing/upgrade-from-trial": ["upgrade-from-trial-to-a-paid-subscription"],+ "billing/exceeding-plan-limits": ["exceeding-plan-limits"],+ "billing/update-subscription": ["update-your-subscription"],+ "billing/cancel-subscription": ["cancel-your-subscription"],+ "billing/faq": ["billing-faq"],// Adblockers- 'adblockers/how-to-deal-with-adblockers': ['adblockers', 'how-to'],+ "adblockers/how-to-deal-with-adblockers": ["adblockers", "how-to"],// Contribute- 'contribute/how-to': ['contribute'],+ "contribute/how-to": ["contribute"],};export const source = loader({- baseUrl: '/',+ baseUrl: "/",source: docs.toFumadocsSource(),icon(iconString) {if (iconString) {@@ -76,16 +65,14 @@ export const source = loader({return undefined;},slugs(file) {- const p = file.path- .replace(/\.(mdx|md)$/, '')- .replace(/\/index$/, '');+ const p = file.path.replace(/\.(mdx|md)$/, "").replace(/\/index$/, "");if (p in SLUG_MAP) return SLUG_MAP[p];// Generic integration pattern: integrations/name → name-integration- if (p.startsWith('integrations/') && p !== 'integrations') {- const name = p.replace('integrations/', '');- return [name + '-integration'];+ if (p.startsWith("integrations/") && p !== "integrations") {+ const name = p.replace("integrations/", "");+ return [name + "-integration"];}return undefined;diff --git a/docs/mdx-components.tsx b/docs/mdx-components.tsxindex 565a501fe..b65e66368 100644--- a/docs/mdx-components.tsx+++ b/docs/mdx-components.tsx@@ -1,10 +1,10 @@-import defaultMdxComponents from 'fumadocs-ui/mdx';-import { Callout } from 'fumadocs-ui/components/callout';-import { Step, Steps } from 'fumadocs-ui/components/steps';-import { Tab, Tabs } from 'fumadocs-ui/components/tabs';-import { Accordion, Accordions } from 'fumadocs-ui/components/accordion';-import { File, Folder, Files } from 'fumadocs-ui/components/files';-import type { MDXComponents } from 'mdx/types';+import defaultMdxComponents from "fumadocs-ui/mdx";+import { Callout } from "fumadocs-ui/components/callout";+import { Step, Steps } from "fumadocs-ui/components/steps";+import { Tab, Tabs } from "fumadocs-ui/components/tabs";+import { Accordion, Accordions } from "fumadocs-ui/components/accordion";+import { File, Folder, Files } from "fumadocs-ui/components/files";+import type { MDXComponents } from "mdx/types";export function getMDXComponents(components?: MDXComponents): MDXComponents {return {diff --git a/docs/next.config.mjs b/docs/next.config.mjsindex 84e8f2271..e154c6d5c 100644--- a/docs/next.config.mjs+++ b/docs/next.config.mjs@@ -1,11 +1,11 @@-import { createMDX } from 'fumadocs-mdx/next';+import { createMDX } from "fumadocs-mdx/next";const withMDX = createMDX();/** @type {import('next').NextConfig} */const config = {reactStrictMode: true,- basePath: '/',+ basePath: "/",};export default withMDX(config);diff --git a/docs/package-lock.json b/docs/package-lock.jsonindex aea565403..16c933407 100644--- a/docs/package-lock.json+++ b/docs/package-lock.json@@ -24,6 +24,7 @@"@types/react": "^19.0.0","@types/react-dom": "^19.0.0","autoprefixer": "^10.4.14",+ "oxfmt": "^0.34.0","postcss": "^8.5.0","tailwindcss": "^4.0.0","typescript": "^5.7.0"@@ -1238,6 +1239,329 @@"node": ">= 20.0.0"}},+ "node_modules/@oxfmt/binding-android-arm-eabi": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.34.0.tgz",+ "integrity": "sha512-sqkqjh/Z38l+duOb1HtVqJTAj1grt2ttkobCopC/72+a4Xxz4xUgZPFyQ4HxrYMvyqO/YA0tvM1QbfOu70Gk1Q==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-android-arm64": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.34.0.tgz",+ "integrity": "sha512-1KRCtasHcVcGOMwfOP9d5Bus2NFsN8yAYM5cBwi8LBg5UtXC3C49WHKrlEa8iF1BjOS6CR2qIqiFbGoA0DJQNQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-darwin-arm64": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.34.0.tgz",+ "integrity": "sha512-b+Rmw9Bva6e/7PBES2wLO8sEU7Mi0+/Kv+pXSe/Y8i4fWNftZZlGwp8P01eECaUqpXATfSgNxdEKy7+ssVNz7g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-darwin-x64": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.34.0.tgz",+ "integrity": "sha512-QGjpevWzf1T9COEokZEWt80kPOtthW1zhRbo7x4Qoz646eTTfi6XsHG2uHeDWJmTbgBoJZPMgj2TAEV/ppEZaA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-freebsd-x64": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.34.0.tgz",+ "integrity": "sha512-VMSaC02cG75qL59M9M/szEaqq/RsLfgpzQ4nqUu8BUnX1zkiZIW2gTpUv3ZJ6qpWnHxIlAXiRZjQwmcwpvtbcg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-linux-arm-gnueabihf": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.34.0.tgz",+ "integrity": "sha512-Klm367PFJhH6vYK3vdIOxFepSJZHPaBfIuqwxdkOcfSQ4qqc/M8sgK0UTFnJWWTA/IkhMIh1kW6uEqiZ/xtQqg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-linux-arm-musleabihf": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.34.0.tgz",+ "integrity": "sha512-nqn0QueVXRfbN9m58/E9Zij0Ap8lzayx591eWBYn0sZrGzY1IRv9RYS7J/1YUXbb0Ugedo0a8qIWzUHU9bWQuA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-linux-arm64-gnu": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.34.0.tgz",+ "integrity": "sha512-DDn+dcqW+sMTCEjvLoQvC/VWJjG7h8wcdN/J+g7ZTdf/3/Dx730pQElxPPGsCXPhprb11OsPyMp5FwXjMY3qvA==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-linux-arm64-musl": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.34.0.tgz",+ "integrity": "sha512-H+F8+71gHQoGTFPPJ6z4dD0Fzfzi0UP8Zx94h5kUmIFThLvMq5K1Y/bUUubiXwwHfwb5C3MPjUpYijiy0rj51Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-linux-ppc64-gnu": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.34.0.tgz",+ "integrity": "sha512-dIGnzTNhCXqQD5pzBwduLg8pClm+t8R53qaE9i5h8iua1iaFAJyLffh4847CNZSlASb7gn1Ofuv7KoG/EpoGZg==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-linux-riscv64-gnu": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.34.0.tgz",+ "integrity": "sha512-FGQ2GTTooilDte/ogwWwkHuuL3lGtcE3uKM2EcC7kOXNWdUfMY6Jx3JCodNVVbFoybv4A+HuCj8WJji2uu1Ceg==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-linux-riscv64-musl": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.34.0.tgz",+ "integrity": "sha512-2dGbGneJ7ptOIVKMwEIHdCkdZEomh74X3ggo4hCzEXL/rl9HwfsZDR15MkqfQqAs6nVXMvtGIOMxjDYa5lwKaA==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-linux-s390x-gnu": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.34.0.tgz",+ "integrity": "sha512-cCtGgmrTrxq3OeSG0UAO+w6yLZTMeOF4XM9SAkNrRUxYhRQELSDQ/iNPCLyHhYNi38uHJQbS5RQweLUDpI4ajA==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-linux-x64-gnu": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.34.0.tgz",+ "integrity": "sha512-7AvMzmeX+k7GdgitXp99GQoIV/QZIpAS7rwxQvC/T541yWC45nwvk4mpnU8N+V6dE5SPEObnqfhCjO80s7qIsg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-linux-x64-musl": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.34.0.tgz",+ "integrity": "sha512-uNiglhcmivJo1oDMh3hoN/Z0WsbEXOpRXZdQ3W/IkOpyV8WF308jFjSC1ZxajdcNRXWej0zgge9QXba58Owt+g==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-openharmony-arm64": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.34.0.tgz",+ "integrity": "sha512-5eFsTjCyji25j6zznzlMc+wQAZJoL9oWy576xhqd2efv+N4g1swIzuSDcb1dz4gpcVC6veWe9pAwD7HnrGjLwg==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-win32-arm64-msvc": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.34.0.tgz",+ "integrity": "sha512-6id8kK0t5hKfbV6LHDzRO21wRTA6ctTlKGTZIsG/mcoir0rssvaYsedUymF4HDj7tbCUlnxCX/qOajKlEuqbIw==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-win32-ia32-msvc": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.34.0.tgz",+ "integrity": "sha512-QHaz+w673mlYqn9v/+fuiKZpjkmagleXQ+NygShDv8tdHpRYX2oYhTJwwt9j1ZfVhRgza1EIUW3JmzCXmtPdhQ==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },+ "node_modules/@oxfmt/binding-win32-x64-msvc": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.34.0.tgz",+ "integrity": "sha512-CXKQM/VaF+yuvGru8ktleHLJoBdjBtTFmAsLGePiESiTN0NjCI/PiaiOCfHMJ1HdP1LykvARUwMvgaN3tDhcrg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ }+ },"node_modules/@phosphor-icons/react": {"version": "2.1.10","resolved": "https://registry.npmjs.org/@phosphor-icons/react/-/react-2.1.10.tgz",@@ -5252,6 +5576,46 @@"regex-recursion": "^6.0.2"}},+ "node_modules/oxfmt": {+ "version": "0.34.0",+ "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.34.0.tgz",+ "integrity": "sha512-t+zTE4XGpzPTK+Zk9gSwcJcFi4pqjl6PwO/ZxPBJiJQ2XCKMucwjPlHxvPHyVKJtkMSyrDGfQ7Ntg/hUr4OgHQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tinypool": "2.1.0"+ },+ "bin": {+ "oxfmt": "bin/oxfmt"+ },+ "engines": {+ "node": "^20.19.0 || >=22.12.0"+ },+ "funding": {+ "url": "https://github.com/sponsors/Boshen"+ },+ "optionalDependencies": {+ "@oxfmt/binding-android-arm-eabi": "0.34.0",+ "@oxfmt/binding-android-arm64": "0.34.0",+ "@oxfmt/binding-darwin-arm64": "0.34.0",+ "@oxfmt/binding-darwin-x64": "0.34.0",+ "@oxfmt/binding-freebsd-x64": "0.34.0",+ "@oxfmt/binding-linux-arm-gnueabihf": "0.34.0",+ "@oxfmt/binding-linux-arm-musleabihf": "0.34.0",+ "@oxfmt/binding-linux-arm64-gnu": "0.34.0",+ "@oxfmt/binding-linux-arm64-musl": "0.34.0",+ "@oxfmt/binding-linux-ppc64-gnu": "0.34.0",+ "@oxfmt/binding-linux-riscv64-gnu": "0.34.0",+ "@oxfmt/binding-linux-riscv64-musl": "0.34.0",+ "@oxfmt/binding-linux-s390x-gnu": "0.34.0",+ "@oxfmt/binding-linux-x64-gnu": "0.34.0",+ "@oxfmt/binding-linux-x64-musl": "0.34.0",+ "@oxfmt/binding-openharmony-arm64": "0.34.0",+ "@oxfmt/binding-win32-arm64-msvc": "0.34.0",+ "@oxfmt/binding-win32-ia32-msvc": "0.34.0",+ "@oxfmt/binding-win32-x64-msvc": "0.34.0"+ }+ },"node_modules/parse-entities": {"version": "4.0.2","resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz",@@ -5959,6 +6323,16 @@"url": "https://github.com/sponsors/SuperchupuDev"}},+ "node_modules/tinypool": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-2.1.0.tgz",+ "integrity": "sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^20.0.0 || >=22.0.0"+ }+ },"node_modules/trim-lines": {"version": "3.0.1","resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",diff --git a/docs/package.json b/docs/package.jsonindex 11f55f4fa..236b8e88c 100644--- a/docs/package.json+++ b/docs/package.json@@ -5,7 +5,9 @@"scripts": {"dev": "next dev -p 5007","build": "next build",- "start": "next start -p 5007 -H 0.0.0.0"+ "start": "next start -p 5007 -H 0.0.0.0",+ "format": "oxfmt",+ "format:check": "oxfmt --check"},"dependencies": {"@phosphor-icons/react": "^2.1.10",@@ -24,6 +26,7 @@"@types/react": "^19.0.0","@types/react-dom": "^19.0.0","autoprefixer": "^10.4.14",+ "oxfmt": "^0.34.0","postcss": "^8.5.0","tailwindcss": "^4.0.0","typescript": "^5.7.0"diff --git a/docs/postcss.config.mjs b/docs/postcss.config.mjsindex 297374d80..61e36849c 100644--- a/docs/postcss.config.mjs+++ b/docs/postcss.config.mjs@@ -1,6 +1,6 @@const config = {plugins: {- '@tailwindcss/postcss': {},+ "@tailwindcss/postcss": {},},};diff --git a/docs/source.config.ts b/docs/source.config.tsindex 0b6ee4dff..7ca6ea4ce 100644--- a/docs/source.config.ts+++ b/docs/source.config.ts@@ -1,7 +1,7 @@-import { defineDocs, defineConfig } from 'fumadocs-mdx/config';+import { defineDocs, defineConfig } from "fumadocs-mdx/config";export const docs = defineDocs({- dir: 'content/docs',+ dir: "content/docs",});export default defineConfig();diff --git a/docs/tsconfig.json b/docs/tsconfig.jsonindex 03c152f0c..27b48b135 100644--- a/docs/tsconfig.json+++ b/docs/tsconfig.json@@ -1,11 +1,7 @@{"compilerOptions": {"target": "ES2017",- "lib": [- "dom",- "dom.iterable",- "esnext"- ],+ "lib": ["dom", "dom.iterable", "esnext"],"allowJs": true,"skipLibCheck": true,"strict": true,@@ -24,12 +20,8 @@],"baseUrl": ".","paths": {- "@/*": [- "./*"- ],- "fumadocs-mdx:collections/*": [- "./.source/*"- ]+ "@/*": ["./*"],+ "fumadocs-mdx:collections/*": ["./.source/*"]}},"include": [@@ -41,7 +33,5 @@".next/types/**/*.ts",".next/dev/types/**/*.ts"],- "exclude": [- "node_modules"- ]+ "exclude": ["node_modules"]}