Docusaurus
Integrate Swetrix with your Docusaurus site to track page views, monitor errors, and capture custom events — all while staying privacy-friendly and GDPR-compliant.
Installation
The simplest way to add Swetrix to a Docusaurus site is by loading the tracking script through docusaurus.config.js and initialising it with a small setup file.
1. Add the scripts to your config
Open docusaurus.config.js and add the Swetrix script and your setup file to the scripts array:
const config = {
// ...your existing config
scripts: [
{
src: 'https://swetrix.org/swetrix.js',
defer: true,
},
{
src: '/js/setupswetrix.js',
defer: true,
},
],
}
2. Create the setup file
Create a new file at static/js/setupswetrix.js:
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.
Replace YOUR_PROJECT_ID with your actual Project ID from the Swetrix dashboard, otherwise tracking won't work.
Noscript fallback (optional)
To 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:
import React from 'react'
export default function Root({ children }) {
return (
<>
{children}
<noscript>
<img
src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"
alt=""
referrerPolicy="no-referrer-when-downgrade"
/>
</noscript>
</>
)
}
Check your installation
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.
During development, pageviews from localhost are not sent by default. Set devMode: true in the setup file if you want to verify tracking locally:
swetrix.init('YOUR_PROJECT_ID', {
devMode: true,
})
Remember to remove this before deploying to production.
Error tracking
You can enable automatic client-side error monitoring by adding trackErrors() to your setup file. This captures unhandled JavaScript errors and reports them to Swetrix.
Update static/js/setupswetrix.js:
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 for configuration options like sampleRate and callback.
Tracking custom events
Custom events let you track specific user interactions beyond page views — button clicks, form submissions, feature usage, and more. In Docusaurus, you can call swetrix.track() directly from any React component.
Since the Swetrix script is loaded globally, the swetrix object is available on window. Here's a helper pattern you can use in your components:
const trackEvent = (eventName, metadata = {}) => {
try {
window?.swetrix?.track({
ev: eventName,
meta: metadata,
})
} catch (error) {
console.error('Swetrix tracking error:', error)
}
}
Example: tracking button clicks
A simple example — track when users click a CTA button:
import React from 'react'
export default function SignUpButton() {
const handleClick = () => {
window?.swetrix?.track({
ev: 'CTA_CLICK',
meta: {
label: 'Sign up',
location: 'hero',
},
})
}
return (
<a href="https://swetrix.com/signup" onClick={handleClick}>
Get started free
</a>
)
}
Example: docs feedback widget
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:
import React, { useState } from 'react'
import { useLocation } from '@docusaurus/router'
export default function DocsFeedback() {
const { pathname } = useLocation()
const [submitted, setSubmitted] = useState(false)
const sendFeedback = async (answer) => {
try {
await window?.swetrix?.track({
ev: 'DOCS_FEEDBACK',
meta: {
answer,
path: pathname,
},
})
} catch (error) {
console.error('Error tracking feedback:', error)
}
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>
)
}
This sends a DOCS_FEEDBACK event to Swetrix with the user's answer and the current page path as metadata. You can then view conversion rates and filter by metadata values in the Custom events section of your dashboard.
Example: tracking search usage
If you use Docusaurus's built-in search (e.g. Algolia DocSearch), you can track when users open the search modal:
import React, { useEffect } from 'react'
export default function Root({ children }) {
useEffect(() => {
const handleKeyDown = (event) => {
if ((event.metaKey || event.ctrlKey) && event.key === 'k') {
window?.swetrix?.track({
ev: 'SEARCH_OPENED',
meta: { trigger: 'keyboard' },
})
}
}
const searchButton = document.querySelector('.DocSearch-Button')
const handleClick = () => {
window?.swetrix?.track({
ev: 'SEARCH_OPENED',
meta: { trigger: 'click' },
})
}
document.addEventListener('keydown', handleKeyDown)
searchButton?.addEventListener('click', handleClick)
return () => {
document.removeEventListener('keydown', handleKeyDown)
searchButton?.removeEventListener('click', handleClick)
}
}, [])
return <>{children}</>
}
Example: tracking outbound link clicks
Track when users click external links in your docs, useful for measuring referral traffic to third-party resources:
import React from 'react'
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:
import TrackedLink from '@site/src/components/TrackedLink'
Check out the <TrackedLink href="https://github.com/Swetrix/swetrix">source code</TrackedLink>.
Event naming conventions
When defining custom event names, keep in mind:
- Names can contain any characters (including spaces, unicode, etc.).
- Names must be no longer than 256 characters.
We recommend using UPPER_SNAKE_CASE for consistency (e.g. DOCS_FEEDBACK, CTA_CLICK, SEARCH_OPENED).
Further reading
- Tracking script reference — full API documentation for
init(),track(),trackViews(),trackErrors(), and more. - Swetrix npm package — if you prefer importing Swetrix as an ES module instead of loading it via a script tag.
Help us improve Swetrix
Was this page helpful to you?
