Analytics
Overview
Analytics in VitePress allows you to track and analyze user behavior on your documentation site. This helps you understand how users interact with your content, which pages are most popular, and how to improve your documentation.
Setting Up Analytics
VitePress provides built-in support for popular analytics platforms. You can easily integrate them by adding configuration to your .vitepress/config.js
file.
Google Analytics
To set up Google Analytics:
// .vitepress/config.js
export default {
themeConfig: {
analytics: {
// Google Analytics tag ID
ga: 'UA-XXXXXXXXX-X',
// or use gtag
gtag: 'G-XXXXXXXXXX'
}
}
}
Other Analytics Providers
VitePress also supports other analytics providers through plugins:
Fathom
// .vitepress/config.js
export default {
themeConfig: {
analytics: {
fathom: {
siteId: 'ABCDEFGH'
}
}
}
}
Plausible
// .vitepress/config.js
export default {
themeConfig: {
analytics: {
plausible: {
domain: 'your-domain.com'
}
}
}
}
Custom Analytics Solutions
You can also implement custom analytics solutions by creating a plugin:
// .vitepress/theme/index.js
export default {
enhanceApp({ app, router }) {
// Add your custom analytics code here
if (!import.meta.env.SSR) {
router.onAfterRouteChanged = (to) => {
// Track page views
console.log('Page viewed:', to.path)
// Your analytics code here
}
}
}
}
Best Practices
Respect User Privacy: Always inform users about data collection and comply with privacy regulations like GDPR and CCPA.
Optimize for Performance: Analytics scripts can impact page load times. Consider using lightweight solutions or loading analytics asynchronously.
Track Meaningful Events: Beyond page views, consider tracking specific events like:
- Documentation search queries
- Time spent on pages
- Interaction with interactive examples
- Feedback submissions
Use Data to Improve Content: Regularly review analytics to identify:
- Most and least visited pages
- Common user paths through documentation
- Exit pages where users leave your site
- Search terms that yield no results
Frequently Asked Questions
How can I disable analytics in development mode?
Most analytics configurations in VitePress automatically disable tracking in development mode. If you need to explicitly control this:
// .vitepress/config.js
export default {
themeConfig: {
analytics: {
gtag: process.env.NODE_ENV === 'production' ? 'G-XXXXXXXXXX' : false
}
}
}
Can I use multiple analytics providers simultaneously?
Yes, you can configure multiple analytics providers in your VitePress configuration:
// .vitepress/config.js
export default {
themeConfig: {
analytics: {
gtag: 'G-XXXXXXXXXX',
plausible: {
domain: 'your-domain.com'
}
}
}
}
Related Resources
This document will be continuously updated. If you have any questions, please provide feedback through GitHub Issues.