Skip to main content

Nextra

Integrate Swetrix with your Nextra 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.

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):

'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:

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, 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):

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>:

<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>:

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:

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:

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:

useEffect(() => {
Swetrix.init('YOUR_PROJECT_ID')
Swetrix.trackViews()
Swetrix.trackErrors()
}, [])

Nextra 2 / 3 — update _app.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 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:

'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:

import DocsFeedback from '@/components/DocsFeedback'

# Getting started

Your page content here...

<DocsFeedback />

Create a reusable component for external links:

'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:

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 any characters (including spaces, unicode, etc.)
  • Be no longer than 256 characters

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:

Swetrix.init(process.env.NEXT_PUBLIC_SWETRIX_PID!)

Further reading

Help us improve Swetrix

Was this page helpful to you?