Cloudflare Web Analytics
Cloudflare Web Analytics with Nuxt is a great privacy analytics solution. It offers free, privacy-centric analytics for your website. It doesn't gather personal data from your visitors, yet provides detailed insights into your web pages' performance as experienced by your visitors.
The simplest way to load Cloudflare Web Analytics globally in your Nuxt App is to use Nuxt config. Alternatively you can directly use the useScriptCloudflareWebAnalytics composable.
Loading Globally
If you'd like to avoid loading the analytics in development, you can use the Environment overrides in your Nuxt config.
export default defineNuxtConfig({
scripts: {
registry: {
cloudflareWebAnalytics: {
token: 'YOUR_TOKEN_ID'
}
}
}
})
useScriptCloudflareWebAnalytics
The useScriptCloudflareWebAnalytics
composable lets you have fine-grain control over when and how Cloudflare Web Analytics is loaded on your site.
function useScriptCloudflareWebAnalytics<T extends CloudflareWebAnalyticsApi>(_options?: CloudflareWebAnalyticsInput) {}
Please follow the Registry Scripts guide to learn more about advanced usage.
The composable comes with the following defaults:
- Trigger: Client Script will load when the Nuxt is hydrating to keep web vital metrics accurate.
CloudflareWebAnalyticsInput
export const CloudflareWebAnalyticsOptions = object({
/**
* The Cloudflare Web Analytics token.
*/
token: string([minLength(32)]),
/**
* Cloudflare Web Analytics enables measuring SPAs automatically by overriding the History API’s pushState function
* and listening to the onpopstate. Hash-based router is not supported.
*
* @default true
*/
spa: optional(boolean()),
})
CloudflareWebAnalyticsApi
export interface CloudflareWebAnalyticsApi {
__cfBeacon: {
load: 'single'
spa: boolean
token: string
}
}
Example
Loading Cloudflare Web Analytics through the app.vue
when Nuxt is ready.
<script setup lang="ts">
useScriptCloudflareWebAnalytics({
token: '12ee46bf598b45c2868bbc07a3073f58',
scriptOptions: {
trigger: 'onNuxtReady'
}
})
</script>
The Cloudflare Web Analytics composable injects a window.__cfBeacon
object into the global scope. If you need
to access this you can do by awaiting the script.
const { onLoaded } = useScriptCloudflareWebAnalytics()
onLoaded(({ cfBeacon }) => {
console.log(cfBeacon)
})