π 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
Nextra integration
Blue Mouse673db7f7babd
diff --git a/docs/docs/integration-guides.md b/docs/docs/integration-guides.mdindex 7a2bcbed0..b2da2fe65 100644--- a/docs/docs/integration-guides.md+++ b/docs/docs/integration-guides.md@@ -43,6 +43,7 @@ Swetrix integrates with a wide range of platforms, frameworks, and tools. Choose- [Jekyll](/jekyll-integration)- [MkDocs / Material for MkDocs](/mkdocs-integration)- [Next.js](/nextjs-integration)+- [Nextra](/nextra-integration)- [Nuxt](/nuxt-integration)- [Preact](/preact-integration)- [Qwik / Qwik City](/qwik-integration)diff --git a/docs/docs/integrations/nextra.md b/docs/docs/integrations/nextra.mdnew file mode 100644index 000000000..88e762bcb--- /dev/null+++ b/docs/docs/integrations/nextra.md@@ -0,0 +1,317 @@+---+title: Nextra+slug: /nextra-integration+---++Integrate Swetrix with your [Nextra](https://nextra.site/) documentation site to track page views, monitor errors, and capture custom events β all while staying privacy-friendly and GDPR-compliant.++This guide covers both **Nextra 4** (App Router) and **Nextra 2 / 3** (Pages Router).++## Installation++Since Nextra is built on Next.js, the recommended approach is to install Swetrix as an npm package. This gives you full TypeScript support and works seamlessly with server-side rendering.++```bash+npm install swetrix+```++### Nextra 4 (App Router)++Nextra 4 uses the Next.js App Router. Create a client component that initialises Swetrix, then add it to your root layout. `trackViews()` automatically detects client-side route changes, so you only need to call it once.++**1. Create the analytics component**++Create a new file at `src/components/Analytics.tsx` (or `components/Analytics.tsx` depending on your project structure):++```tsx+'use client'++import { useEffect } from 'react'+import * as Swetrix from 'swetrix'++export default function Analytics() {+ useEffect(() => {+ Swetrix.init('YOUR_PROJECT_ID')+ Swetrix.trackViews()+ }, [])++ return null+}+```++**2. Add it to your root layout**++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'++export default function RootLayout({+ children,+}: {+ children: React.ReactNode+}) {+ return (+ <html lang="en">+ <body>+ {children}+ <Analytics />+ </body>+ </html>+ )+}+```++:::caution+Replace `YOUR_PROJECT_ID` with your actual Project ID from the [Swetrix dashboard](https://swetrix.com/projects), otherwise tracking won't work.+:::++### Nextra 2 / 3 (Pages Router)++Nextra 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'++export default function App({ Component, pageProps }: AppProps) {+ useEffect(() => {+ Swetrix.init('YOUR_PROJECT_ID')+ Swetrix.trackViews()+ }, [])++ return <Component {...pageProps} />+}+```++If your project already has a custom `_app` file, simply add the `useEffect` block to the existing component.++:::tip+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.+:::++### Noscript fallback (optional)++To track visitors who have JavaScript disabled, add a noscript image pixel.++**Nextra 4** β add to your root layout inside `<body>`:++```tsx+<noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"+ alt=""+ referrerPolicy="no-referrer-when-downgrade"+ />+</noscript>+```++**Nextra 2 / 3** β add to `pages/_document.tsx` inside `<body>`:++```tsx+import { Html, Head, Main, NextScript } from 'next/document'++export default function Document() {+ return (+ <Html>+ <Head />+ <body>+ <Main />+ <NextScript />+ <noscript>+ <img+ src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"+ alt=""+ referrerPolicy="no-referrer-when-downgrade"+ />+ </noscript>+ </body>+ </Html>+ )+}+```++## Disable tracking in development++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',+})+```++:::tip+If you want to verify tracking locally during development, set `devMode: true` instead:++```tsx+Swetrix.init('YOUR_PROJECT_ID', {+ devMode: true,+})+```++Remember to remove this before deploying to production.+:::++## Check your installation++Deploy your site (or temporarily enable `devMode`) and visit a few pages. Within a minute you should see new pageviews appearing in your Swetrix dashboard.++## Error tracking++Enable automatic client-side error monitoring by adding `trackErrors()` to your analytics setup. This captures unhandled JavaScript errors and reports them to Swetrix.++**Nextra 4** β update your analytics component:++```tsx+useEffect(() => {+ Swetrix.init('YOUR_PROJECT_ID')+ Swetrix.trackViews()+ Swetrix.trackErrors()+}, [])+```++**Nextra 2 / 3** β update `_app.tsx`:++```tsx+useEffect(() => {+ 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`.++## Tracking custom events++Custom events let you track specific user interactions β button clicks, form submissions, feedback responses, and more. Import `swetrix` in any client component and call `track()`.++### Example: docs feedback widget++Track whether visitors found a page helpful. Create a component at `components/DocsFeedback.tsx`:++```tsx+'use client'++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 sendFeedback = (answer: string) => {+ Swetrix.track({+ ev: 'DOCS_FEEDBACK',+ meta: {+ answer,+ path: pathname,+ },+ })++ setSubmitted(true)+ }++ if (submitted) {+ 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>+ </div>+ )+}+```++You can then use this component in any MDX page:++```mdx+import DocsFeedback from '@/components/DocsFeedback'++# Getting started++Your page content here...++<DocsFeedback />+```++### Example: tracking outbound links++Create a reusable component for external links:++```tsx+'use client'++import * as Swetrix from 'swetrix'++interface TrackedLinkProps {+ href: string+ children: React.ReactNode+ eventName?: string+}++export default function TrackedLink({+ href,+ children,+ 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'++Check out the <TrackedLink href="https://github.com/example/repo">source code</TrackedLink>.+```++### Event naming rules++Event names must:++- Contain only English letters (a-Z), numbers (0-9), underscores (`_`), and dots (`.`)+- Be fewer than 64 characters+- Start with an English letter++We recommend `UPPER_SNAKE_CASE` for consistency (e.g. `DOCS_FEEDBACK`, `OUTBOUND_CLICK`).++## Using environment variables for your Project ID++Rather than hardcoding your Project ID, you can use a Next.js environment variable. Since the analytics component runs on the client, the variable must be prefixed with `NEXT_PUBLIC_`.++**1. Add to your `.env.local` file:**++```+NEXT_PUBLIC_SWETRIX_PID=YOUR_PROJECT_ID+```++**2. Reference it in your analytics component:**++```tsx+Swetrix.init(process.env.NEXT_PUBLIC_SWETRIX_PID!)+```++## Further reading++- [Next.js integration](/nextjs-integration) β general Next.js setup guide (Nextra is built on Next.js).+- [Tracking script reference](/swetrix-js-reference) β full API documentation for `init()`, `track()`, `trackViews()`, `trackErrors()`, and more.+- [Swetrix npm package](https://www.npmjs.com/package/swetrix) β package details and changelog.diff --git a/docs/sidebars.js b/docs/sidebars.jsindex 9eac14b76..fa522e109 100644--- a/docs/sidebars.js+++ b/docs/sidebars.js@@ -43,6 +43,7 @@ module.exports = {items: ['integrations/gatsby','integrations/nextjs',+ 'integrations/nextra','integrations/preact','integrations/react','integrations/remix',